]>
Commit | Line | Data |
---|---|---|
ca74886f | 1 | <?php |
53054b2b | 2 | |
ca74886f V |
3 | /** |
4 | * Shaarli utilities | |
5 | */ | |
6 | ||
1abe6555 | 7 | /** |
b38a1b02 | 8 | * Format log using provided data. |
1abe6555 | 9 | * |
b38a1b02 A |
10 | * @param string $message the message to log |
11 | * @param string|null $clientIp the client's remote IPv4/IPv6 address | |
478ce8af | 12 | * |
b38a1b02 | 13 | * @return string Formatted message to log |
1abe6555 | 14 | */ |
b38a1b02 | 15 | function format_log(string $message, string $clientIp = null): string |
1abe6555 | 16 | { |
b38a1b02 A |
17 | $out = $message; |
18 | ||
19 | if (!empty($clientIp)) { | |
20 | // Note: we keep the first dash to avoid breaking fail2ban configs | |
21 | $out = '- ' . $clientIp . ' - ' . $out; | |
22 | } | |
23 | ||
24 | return $out; | |
1abe6555 V |
25 | } |
26 | ||
ca74886f V |
27 | /** |
28 | * Returns the small hash of a string, using RFC 4648 base64url format | |
29 | * | |
30 | * Small hashes: | |
31 | * - are unique (well, as unique as crc32, at last) | |
32 | * - are always 6 characters long. | |
33 | * - only use the following characters: a-z A-Z 0-9 - _ @ | |
34 | * - are NOT cryptographically secure (they CAN be forged) | |
35 | * | |
36 | * In Shaarli, they are used as a tinyurl-like link to individual entries, | |
d592daea A |
37 | * built once with the combination of the date and item ID. |
38 | * e.g. smallHash('20111006_131924' . 142) --> eaWxtQ | |
39 | * | |
40 | * @warning before v0.8.1, smallhashes were built only with the date, | |
41 | * and their value has been preserved. | |
7af9a418 A |
42 | * |
43 | * @param string $text Create a hash from this text. | |
44 | * | |
45 | * @return string generated small hash. | |
ca74886f V |
46 | */ |
47 | function smallHash($text) | |
48 | { | |
49 | $t = rtrim(base64_encode(hash('crc32', $text, true)), '='); | |
50 | return strtr($t, '+/', '-_'); | |
51 | } | |
52 | ||
53 | /** | |
54 | * Tells if a string start with a substring | |
5046bcb6 A |
55 | * |
56 | * @param string $haystack Given string. | |
57 | * @param string $needle String to search at the beginning of $haystack. | |
58 | * @param bool $case Case sensitive. | |
59 | * | |
60 | * @return bool True if $haystack starts with $needle. | |
ca74886f | 61 | */ |
5046bcb6 | 62 | function startsWith($haystack, $needle, $case = true) |
ca74886f V |
63 | { |
64 | if ($case) { | |
65 | return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0); | |
66 | } | |
67 | return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0); | |
68 | } | |
69 | ||
70 | /** | |
71 | * Tells if a string ends with a substring | |
5046bcb6 A |
72 | * |
73 | * @param string $haystack Given string. | |
74 | * @param string $needle String to search at the end of $haystack. | |
75 | * @param bool $case Case sensitive. | |
76 | * | |
77 | * @return bool True if $haystack ends with $needle. | |
ca74886f | 78 | */ |
5046bcb6 | 79 | function endsWith($haystack, $needle, $case = true) |
ca74886f V |
80 | { |
81 | if ($case) { | |
82 | return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); | |
83 | } | |
84 | return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); | |
85 | } | |
64bc92e3 | 86 | |
64bc92e3 | 87 | /** |
2925687e | 88 | * Htmlspecialchars wrapper |
ee88a4bc | 89 | * Support multidimensional array of strings. |
2925687e | 90 | * |
ee88a4bc | 91 | * @param mixed $input Data to escape: a single string or an array of strings. |
2925687e | 92 | * |
c266a89d | 93 | * @return string|array escaped. |
64bc92e3 | 94 | */ |
ee88a4bc | 95 | function escape($input) |
64bc92e3 | 96 | { |
c22fa57a A |
97 | if (null === $input) { |
98 | return null; | |
99 | } | |
100 | ||
72fbbcd6 | 101 | if (is_bool($input) || is_int($input) || is_float($input) || $input instanceof DateTimeInterface) { |
7d86f40b A |
102 | return $input; |
103 | } | |
104 | ||
ee88a4bc | 105 | if (is_array($input)) { |
53054b2b | 106 | $out = []; |
f211e417 | 107 | foreach ($input as $key => $value) { |
72fbbcd6 | 108 | $out[escape($key)] = escape($value); |
ee88a4bc A |
109 | } |
110 | return $out; | |
111 | } | |
112 | return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false); | |
64bc92e3 | 113 | } |
114 | ||
2925687e A |
115 | /** |
116 | * Reverse the escape function. | |
117 | * | |
118 | * @param string $str the string to unescape. | |
119 | * | |
120 | * @return string unescaped string. | |
121 | */ | |
122 | function unescape($str) | |
123 | { | |
124 | return htmlspecialchars_decode($str); | |
125 | } | |
126 | ||
64bc92e3 | 127 | /** |
7af9a418 A |
128 | * Sanitize link before rendering. |
129 | * | |
130 | * @param array $link Link to escape. | |
64bc92e3 | 131 | */ |
132 | function sanitizeLink(&$link) | |
133 | { | |
134 | $link['url'] = escape($link['url']); // useful? | |
135 | $link['title'] = escape($link['title']); | |
136 | $link['description'] = escape($link['description']); | |
137 | $link['tags'] = escape($link['tags']); | |
138 | } | |
9186ab95 V |
139 | |
140 | /** | |
141 | * Checks if a string represents a valid date | |
822bffce A |
142 | |
143 | * @param string $format The expected DateTime format of the string | |
144 | * @param string $string A string-formatted date | |
145 | * | |
146 | * @return bool whether the string is a valid date | |
9186ab95 | 147 | * |
822bffce A |
148 | * @see http://php.net/manual/en/class.datetime.php |
149 | * @see http://php.net/manual/en/datetime.createfromformat.php | |
9186ab95 V |
150 | */ |
151 | function checkDateFormat($format, $string) | |
152 | { | |
153 | $date = DateTime::createFromFormat($format, $string); | |
154 | return $date && $date->format($string) == $string; | |
155 | } | |
775803a0 A |
156 | |
157 | /** | |
158 | * Generate a header location from HTTP_REFERER. | |
159 | * Make sure the referer is Shaarli itself and prevent redirection loop. | |
160 | * | |
161 | * @param string $referer - HTTP_REFERER. | |
162 | * @param string $host - Server HOST. | |
163 | * @param array $loopTerms - Contains list of term to prevent redirection loop. | |
164 | * | |
165 | * @return string $referer - final referer. | |
166 | */ | |
53054b2b | 167 | function generateLocation($referer, $host, $loopTerms = []) |
775803a0 | 168 | { |
9e4cc28e | 169 | $finalReferer = './?'; |
775803a0 A |
170 | |
171 | // No referer if it contains any value in $loopCriteria. | |
cf92b4dd | 172 | foreach (array_filter($loopTerms) as $value) { |
775803a0 | 173 | if (strpos($referer, $value) !== false) { |
d01c2342 | 174 | return $finalReferer; |
775803a0 A |
175 | } |
176 | } | |
177 | ||
178 | // Remove port from HTTP_HOST | |
179 | if ($pos = strpos($host, ':')) { | |
180 | $host = substr($host, 0, $pos); | |
181 | } | |
182 | ||
d01c2342 A |
183 | $refererHost = parse_url($referer, PHP_URL_HOST); |
184 | if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) { | |
185 | $finalReferer = $referer; | |
775803a0 A |
186 | } |
187 | ||
d01c2342 | 188 | return $finalReferer; |
775803a0 | 189 | } |
d1e2f8e5 | 190 | |
7b63e4ca A |
191 | /** |
192 | * Sniff browser language to set the locale automatically. | |
193 | * Note that is may not work on your server if the corresponding locale is not installed. | |
194 | * | |
195 | * @param string $headerLocale Locale send in HTTP headers (e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"). | |
196 | **/ | |
197 | function autoLocale($headerLocale) | |
198 | { | |
199 | // Default if browser does not send HTTP_ACCEPT_LANGUAGE | |
53054b2b | 200 | $locales = ['en_US', 'en_US.utf8', 'en_US.UTF-8']; |
03b9cb60 A |
201 | if (! empty($headerLocale)) { |
202 | if (preg_match_all('/([a-z]{2,3})[-_]?([a-z]{2})?,?/i', $headerLocale, $matches, PREG_SET_ORDER)) { | |
203 | $attempts = []; | |
204 | foreach ($matches as $match) { | |
205 | $first = [strtolower($match[1]), strtoupper($match[1])]; | |
206 | $separators = ['_', '-']; | |
207 | $encodings = ['utf8', 'UTF-8']; | |
208 | if (!empty($match[2])) { | |
209 | $second = [strtoupper($match[2]), strtolower($match[2])]; | |
210 | $items = [$first, $separators, $second, ['.'], $encodings]; | |
211 | } else { | |
212 | $items = [$first, $separators, $first, ['.'], $encodings]; | |
213 | } | |
214 | $attempts = array_merge($attempts, iterator_to_array(cartesian_product_generator($items))); | |
215 | } | |
216 | ||
217 | if (! empty($attempts)) { | |
218 | $locales = array_merge(array_map('implode', $attempts), $locales); | |
1255a42c | 219 | } |
7b63e4ca A |
220 | } |
221 | } | |
03b9cb60 A |
222 | |
223 | setlocale(LC_ALL, $locales); | |
9ccca401 | 224 | } |
cbfdcff2 | 225 | |
1255a42c | 226 | /** |
52b50310 | 227 | * Build a Generator object representing the cartesian product from given $items. |
1255a42c A |
228 | * |
229 | * Example: | |
230 | * [['a'], ['b', 'c']] | |
231 | * will generate: | |
52b50310 A |
232 | * [ |
233 | * ['a', 'b'], | |
234 | * ['a', 'c'], | |
235 | * ] | |
1255a42c A |
236 | * |
237 | * @param array $items array of array of string | |
238 | * | |
52b50310 A |
239 | * @return Generator representing the cartesian product of given array. |
240 | * | |
241 | * @see https://en.wikipedia.org/wiki/Cartesian_product | |
1255a42c | 242 | */ |
52b50310 | 243 | function cartesian_product_generator($items) |
1255a42c | 244 | { |
52b50310 A |
245 | if (empty($items)) { |
246 | yield []; | |
247 | } | |
248 | $subArray = array_pop($items); | |
249 | if (empty($subArray)) { | |
250 | return; | |
251 | } | |
252 | foreach (cartesian_product_generator($items) as $item) { | |
253 | foreach ($subArray as $value) { | |
254 | yield $item + [count($item) => $value]; | |
1255a42c | 255 | } |
1255a42c | 256 | } |
1255a42c A |
257 | } |
258 | ||
cbfdcff2 A |
259 | /** |
260 | * Generates a default API secret. | |
261 | * | |
262 | * Note that the random-ish methods used in this function are predictable, | |
263 | * which makes them NOT suitable for crypto. | |
264 | * BUT the random string is salted with the salt and hashed with the username. | |
265 | * It makes the generated API secret secured enough for Shaarli. | |
266 | * | |
267 | * PHP 7 provides random_int(), designed for cryptography. | |
268 | * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator | |
269 | ||
270 | * @param string $username Shaarli login username | |
271 | * @param string $salt Shaarli password hash salt | |
272 | * | |
273 | * @return string|bool Generated API secret, 12 char length. | |
274 | * Or false if invalid parameters are provided (which will make the API unusable). | |
275 | */ | |
276 | function generate_api_secret($username, $salt) | |
277 | { | |
278 | if (empty($username) || empty($salt)) { | |
279 | return false; | |
280 | } | |
281 | ||
282 | return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12)); | |
283 | } | |
b3051a6a A |
284 | |
285 | /** | |
286 | * Trim string, replace sequences of whitespaces by a single space. | |
287 | * PHP equivalent to `normalize-space` XSLT function. | |
288 | * | |
289 | * @param string $string Input string. | |
290 | * | |
291 | * @return mixed Normalized string. | |
292 | */ | |
293 | function normalize_spaces($string) | |
294 | { | |
295 | return preg_replace('/\s{2,}/', ' ', trim($string)); | |
296 | } | |
52b50310 A |
297 | |
298 | /** | |
299 | * Format the date according to the locale. | |
300 | * | |
301 | * Requires php-intl to display international datetimes, | |
302 | * otherwise default format '%c' will be returned. | |
303 | * | |
69e29ff6 A |
304 | * @param DateTimeInterface $date to format. |
305 | * @param bool $time Displays time if true. | |
306 | * @param bool $intl Use international format if true. | |
52b50310 A |
307 | * |
308 | * @return bool|string Formatted date, or false if the input is invalid. | |
309 | */ | |
81bd104d | 310 | function format_date($date, $time = true, $intl = true) |
52b50310 | 311 | { |
69e29ff6 | 312 | if (! $date instanceof DateTimeInterface) { |
52b50310 A |
313 | return false; |
314 | } | |
315 | ||
316 | if (! $intl || ! class_exists('IntlDateFormatter')) { | |
81bd104d A |
317 | $format = $time ? '%c' : '%x'; |
318 | return strftime($format, $date->getTimestamp()); | |
52b50310 A |
319 | } |
320 | ||
321 | $formatter = new IntlDateFormatter( | |
322 | setlocale(LC_TIME, 0), | |
323 | IntlDateFormatter::LONG, | |
81bd104d | 324 | $time ? IntlDateFormatter::LONG : IntlDateFormatter::NONE |
52b50310 A |
325 | ); |
326 | ||
327 | return $formatter->format($date); | |
328 | } | |
84315a3b | 329 | |
36e6d88d A |
330 | /** |
331 | * Format the date month according to the locale. | |
332 | * | |
333 | * @param DateTimeInterface $date to format. | |
334 | * | |
335 | * @return bool|string Formatted date, or false if the input is invalid. | |
336 | */ | |
337 | function format_month(DateTimeInterface $date) | |
338 | { | |
339 | if (! $date instanceof DateTimeInterface) { | |
340 | return false; | |
341 | } | |
342 | ||
343 | return strftime('%B', $date->getTimestamp()); | |
344 | } | |
345 | ||
346 | ||
84315a3b A |
347 | /** |
348 | * Check if the input is an integer, no matter its real type. | |
349 | * | |
350 | * PHP is a bit messy regarding this: | |
351 | * - is_int returns false if the input is a string | |
352 | * - ctype_digit returns false if the input is an integer or negative | |
353 | * | |
354 | * @param mixed $input value | |
355 | * | |
356 | * @return bool true if the input is an integer, false otherwise | |
357 | */ | |
358 | function is_integer_mixed($input) | |
359 | { | |
360 | if (is_array($input) || is_bool($input) || is_object($input)) { | |
361 | return false; | |
362 | } | |
363 | $input = strval($input); | |
364 | return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1))); | |
365 | } | |
366 | ||
367 | /** | |
368 | * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes. | |
369 | * | |
370 | * @param string $val Size expressed in string. | |
371 | * | |
372 | * @return int Size expressed in bytes. | |
373 | */ | |
374 | function return_bytes($val) | |
375 | { | |
376 | if (is_integer_mixed($val) || $val === '0' || empty($val)) { | |
377 | return $val; | |
378 | } | |
379 | $val = trim($val); | |
53054b2b | 380 | $last = strtolower($val[strlen($val) - 1]); |
84315a3b | 381 | $val = intval(substr($val, 0, -1)); |
f211e417 V |
382 | switch ($last) { |
383 | case 'g': | |
384 | $val *= 1024; | |
b99e00f7 | 385 | // do no break in order 1024^2 for each unit |
f211e417 V |
386 | case 'm': |
387 | $val *= 1024; | |
b99e00f7 | 388 | // do no break in order 1024^2 for each unit |
f211e417 V |
389 | case 'k': |
390 | $val *= 1024; | |
84315a3b A |
391 | } |
392 | return $val; | |
393 | } | |
394 | ||
395 | /** | |
396 | * Return a human readable size from bytes. | |
397 | * | |
398 | * @param int $bytes value | |
399 | * | |
400 | * @return string Human readable size | |
401 | */ | |
402 | function human_bytes($bytes) | |
403 | { | |
404 | if ($bytes === '') { | |
405 | return t('Setting not set'); | |
406 | } | |
407 | if (! is_integer_mixed($bytes)) { | |
408 | return $bytes; | |
409 | } | |
410 | $bytes = intval($bytes); | |
411 | if ($bytes === 0) { | |
412 | return t('Unlimited'); | |
413 | } | |
414 | ||
415 | $units = [t('B'), t('kiB'), t('MiB'), t('GiB')]; | |
416 | for ($i = 0; $i < count($units) && $bytes >= 1024; ++$i) { | |
417 | $bytes /= 1024; | |
418 | } | |
419 | ||
6a19124a | 420 | return round($bytes) . $units[$i]; |
84315a3b A |
421 | } |
422 | ||
423 | /** | |
424 | * Try to determine max file size for uploads (POST). | |
6a19124a | 425 | * Returns an integer (in bytes) or formatted depending on $format. |
84315a3b A |
426 | * |
427 | * @param mixed $limitPost post_max_size PHP setting | |
428 | * @param mixed $limitUpload upload_max_filesize PHP setting | |
6a19124a | 429 | * @param bool $format Format max upload size to human readable size |
84315a3b | 430 | * |
6a19124a | 431 | * @return int|string max upload file size |
84315a3b | 432 | */ |
6a19124a | 433 | function get_max_upload_size($limitPost, $limitUpload, $format = true) |
84315a3b A |
434 | { |
435 | $size1 = return_bytes($limitPost); | |
436 | $size2 = return_bytes($limitUpload); | |
437 | // Return the smaller of two: | |
438 | $maxsize = min($size1, $size2); | |
6a19124a | 439 | return $format ? human_bytes($maxsize) : $maxsize; |
84315a3b | 440 | } |
aa4797ba A |
441 | |
442 | /** | |
443 | * Sort the given array alphabetically using php-intl if available. | |
444 | * Case sensitive. | |
445 | * | |
446 | * Note: doesn't support multidimensional arrays | |
447 | * | |
448 | * @param array $data Input array, passed by reference | |
449 | * @param bool $reverse Reverse sort if set to true | |
450 | * @param bool $byKeys Sort the array by keys if set to true, by value otherwise. | |
451 | */ | |
452 | function alphabetical_sort(&$data, $reverse = false, $byKeys = false) | |
453 | { | |
12266213 | 454 | $callback = function ($a, $b) use ($reverse) { |
aa4797ba A |
455 | // Collator is part of PHP intl. |
456 | if (class_exists('Collator')) { | |
457 | $collator = new Collator(setlocale(LC_COLLATE, 0)); | |
458 | if (!intl_is_failure(intl_get_error_code())) { | |
459 | return $collator->compare($a, $b) * ($reverse ? -1 : 1); | |
460 | } | |
461 | } | |
462 | ||
463 | return strcasecmp($a, $b) * ($reverse ? -1 : 1); | |
464 | }; | |
465 | ||
466 | if ($byKeys) { | |
467 | uksort($data, $callback); | |
468 | } else { | |
469 | usort($data, $callback); | |
470 | } | |
471 | } | |
12266213 A |
472 | |
473 | /** | |
474 | * Wrapper function for translation which match the API | |
475 | * of gettext()/_() and ngettext(). | |
476 | * | |
36e6d88d A |
477 | * @param string $text Text to translate. |
478 | * @param string $nText The plural message ID. | |
479 | * @param int $nb The number of items for plural forms. | |
480 | * @param string $domain The domain where the translation is stored (default: shaarli). | |
481 | * @param array $variables Associative array of variables to replace in translated text. | |
482 | * @param bool $fixCase Apply `ucfirst` on the translated string, might be useful for strings with variables. | |
12266213 | 483 | * |
6a65bc57 | 484 | * @return string Text translated. |
12266213 | 485 | */ |
36e6d88d | 486 | function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false) |
f211e417 | 487 | { |
53054b2b A |
488 | $postFunction = $fixCase ? 'ucfirst' : function ($input) { |
489 | return $input; | |
490 | }; | |
36e6d88d A |
491 | |
492 | return $postFunction(dn__($domain, $text, $nText, $nb, $variables)); | |
12266213 | 493 | } |
5c06c087 A |
494 | |
495 | /** | |
496 | * Converts an exception into a printable stack trace string. | |
497 | */ | |
498 | function exception2text(Throwable $e): string | |
499 | { | |
500 | return $e->getMessage() . PHP_EOL . $e->getFile() . $e->getLine() . PHP_EOL . $e->getTraceAsString(); | |
501 | } |