]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
Merge pull request #424 from ArthurHoaro/search
[github/shaarli/Shaarli.git] / application / Utils.php
1 <?php
2 /**
3 * Shaarli utilities
4 */
5
6 /**
7 * Returns the small hash of a string, using RFC 4648 base64url format
8 *
9 * Small hashes:
10 * - are unique (well, as unique as crc32, at last)
11 * - are always 6 characters long.
12 * - only use the following characters: a-z A-Z 0-9 - _ @
13 * - are NOT cryptographically secure (they CAN be forged)
14 *
15 * In Shaarli, they are used as a tinyurl-like link to individual entries,
16 * e.g. smallHash('20111006_131924') --> yZH23w
17 */
18 function smallHash($text)
19 {
20 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
21 return strtr($t, '+/', '-_');
22 }
23
24 /**
25 * Tells if a string start with a substring
26 */
27 function startsWith($haystack, $needle, $case=true)
28 {
29 if ($case) {
30 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
31 }
32 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
33 }
34
35 /**
36 * Tells if a string ends with a substring
37 */
38 function endsWith($haystack, $needle, $case=true)
39 {
40 if ($case) {
41 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
42 }
43 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
44 }
45
46 /**
47 * Same as nl2br(), but escapes < and >
48 */
49 function nl2br_escaped($html)
50 {
51 return str_replace('>', '&gt;', str_replace('<', '&lt;', nl2br($html)));
52 }
53
54 /**
55 * htmlspecialchars wrapper
56 */
57 function escape($str)
58 {
59 return htmlspecialchars($str, ENT_COMPAT, 'UTF-8', false);
60 }
61
62 /**
63 * Link sanitization before templating
64 */
65 function sanitizeLink(&$link)
66 {
67 $link['url'] = escape($link['url']); // useful?
68 $link['title'] = escape($link['title']);
69 $link['description'] = escape($link['description']);
70 $link['tags'] = escape($link['tags']);
71 }
72
73 /**
74 * Checks if a string represents a valid date
75
76 * @param string $format The expected DateTime format of the string
77 * @param string $string A string-formatted date
78 *
79 * @return bool whether the string is a valid date
80 *
81 * @see http://php.net/manual/en/class.datetime.php
82 * @see http://php.net/manual/en/datetime.createfromformat.php
83 */
84 function checkDateFormat($format, $string)
85 {
86 $date = DateTime::createFromFormat($format, $string);
87 return $date && $date->format($string) == $string;
88 }
89
90 /**
91 * Generate a header location from HTTP_REFERER.
92 * Make sure the referer is Shaarli itself and prevent redirection loop.
93 *
94 * @param string $referer - HTTP_REFERER.
95 * @param string $host - Server HOST.
96 * @param array $loopTerms - Contains list of term to prevent redirection loop.
97 *
98 * @return string $referer - final referer.
99 */
100 function generateLocation($referer, $host, $loopTerms = array())
101 {
102 $finalReferer = '?';
103
104 // No referer if it contains any value in $loopCriteria.
105 foreach ($loopTerms as $value) {
106 if (strpos($referer, $value) !== false) {
107 return $finalReferer;
108 }
109 }
110
111 // Remove port from HTTP_HOST
112 if ($pos = strpos($host, ':')) {
113 $host = substr($host, 0, $pos);
114 }
115
116 $refererHost = parse_url($referer, PHP_URL_HOST);
117 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
118 $finalReferer = $referer;
119 }
120
121 return $finalReferer;
122 }
123
124 /**
125 * Validate session ID to prevent Full Path Disclosure.
126 *
127 * See #298.
128 * The session ID's format depends on the hash algorithm set in PHP settings
129 *
130 * @param string $sessionId Session ID
131 *
132 * @return true if valid, false otherwise.
133 *
134 * @see http://php.net/manual/en/function.hash-algos.php
135 * @see http://php.net/manual/en/session.configuration.php
136 */
137 function is_session_id_valid($sessionId)
138 {
139 if (empty($sessionId)) {
140 return false;
141 }
142
143 if (!$sessionId) {
144 return false;
145 }
146
147 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
148 return false;
149 }
150
151 return true;
152 }
153
154 /**
155 * In a string, converts URLs to clickable links.
156 *
157 * @param string $text input string.
158 * @param string $redirector if a redirector is set, use it to gerenate links.
159 *
160 * @return string returns $text with all links converted to HTML links.
161 *
162 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
163 */
164 function text2clickable($text, $redirector)
165 {
166 $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si';
167
168 if (empty($redirector)) {
169 return preg_replace($regex, '<a href="$1">$1</a>', $text);
170 }
171 // Redirector is set, urlencode the final URL.
172 return preg_replace_callback(
173 $regex,
174 function ($matches) use ($redirector) {
175 return '<a href="' . $redirector . urlencode($matches[1]) .'">'. $matches[1] .'</a>';
176 },
177 $text
178 );
179 }
180
181 /**
182 * This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
183 * even in the absence of <pre> (This is used in description to keep text formatting).
184 *
185 * @param string $text input text.
186 *
187 * @return string formatted text.
188 */
189 function space2nbsp($text)
190 {
191 return preg_replace('/(^| ) /m', '$1&nbsp;', $text);
192 }
193
194 /**
195 * Format Shaarli's description
196 * TODO: Move me to ApplicationUtils when it's ready.
197 *
198 * @param string $description shaare's description.
199 * @param string $redirector if a redirector is set, use it to gerenate links.
200 *
201 * @return string formatted description.
202 */
203 function format_description($description, $redirector) {
204 return nl2br(space2nbsp(text2clickable($description, $redirector)));
205 }