]>
Commit | Line | Data |
---|---|---|
1 | <?php | |
2 | ||
3 | /** | |
4 | * Shaarli utilities | |
5 | */ | |
6 | ||
7 | /** | |
8 | * Format log using provided data. | |
9 | * | |
10 | * @param string $message the message to log | |
11 | * @param string|null $clientIp the client's remote IPv4/IPv6 address | |
12 | * | |
13 | * @return string Formatted message to log | |
14 | */ | |
15 | function format_log(string $message, string $clientIp = null): string | |
16 | { | |
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; | |
25 | } | |
26 | ||
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, | |
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. | |
42 | * | |
43 | * @param string $text Create a hash from this text. | |
44 | * | |
45 | * @return string generated small hash. | |
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 | |
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. | |
61 | */ | |
62 | function startsWith($haystack, $needle, $case = true) | |
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 | |
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. | |
78 | */ | |
79 | function endsWith($haystack, $needle, $case = true) | |
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 | } | |
86 | ||
87 | /** | |
88 | * Htmlspecialchars wrapper | |
89 | * Support multidimensional array of strings. | |
90 | * | |
91 | * @param mixed $input Data to escape: a single string or an array of strings. | |
92 | * | |
93 | * @return string|array escaped. | |
94 | */ | |
95 | function escape($input) | |
96 | { | |
97 | if (null === $input) { | |
98 | return null; | |
99 | } | |
100 | ||
101 | if (is_bool($input) || is_int($input) || is_float($input) || $input instanceof DateTimeInterface) { | |
102 | return $input; | |
103 | } | |
104 | ||
105 | if (is_array($input)) { | |
106 | $out = []; | |
107 | foreach ($input as $key => $value) { | |
108 | $out[escape($key)] = escape($value); | |
109 | } | |
110 | return $out; | |
111 | } | |
112 | return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false); | |
113 | } | |
114 | ||
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 | ||
127 | /** | |
128 | * Sanitize link before rendering. | |
129 | * | |
130 | * @param array $link Link to escape. | |
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 | } | |
139 | ||
140 | /** | |
141 | * Checks if a string represents a valid date | |
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 | |
147 | * | |
148 | * @see http://php.net/manual/en/class.datetime.php | |
149 | * @see http://php.net/manual/en/datetime.createfromformat.php | |
150 | */ | |
151 | function checkDateFormat($format, $string) | |
152 | { | |
153 | $date = DateTime::createFromFormat($format, $string); | |
154 | return $date && $date->format($string) == $string; | |
155 | } | |
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 | */ | |
167 | function generateLocation($referer, $host, $loopTerms = []) | |
168 | { | |
169 | $finalReferer = './?'; | |
170 | ||
171 | // No referer if it contains any value in $loopCriteria. | |
172 | foreach (array_filter($loopTerms) as $value) { | |
173 | if (strpos($referer, $value) !== false) { | |
174 | return $finalReferer; | |
175 | } | |
176 | } | |
177 | ||
178 | // Remove port from HTTP_HOST | |
179 | if ($pos = strpos($host, ':')) { | |
180 | $host = substr($host, 0, $pos); | |
181 | } | |
182 | ||
183 | $refererHost = parse_url($referer, PHP_URL_HOST); | |
184 | if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) { | |
185 | $finalReferer = $referer; | |
186 | } | |
187 | ||
188 | return $finalReferer; | |
189 | } | |
190 | ||
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 | |
200 | $locales = ['en_US', 'en_US.utf8', 'en_US.UTF-8']; | |
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); | |
219 | } | |
220 | } | |
221 | } | |
222 | ||
223 | setlocale(LC_ALL, $locales); | |
224 | } | |
225 | ||
226 | /** | |
227 | * Build a Generator object representing the cartesian product from given $items. | |
228 | * | |
229 | * Example: | |
230 | * [['a'], ['b', 'c']] | |
231 | * will generate: | |
232 | * [ | |
233 | * ['a', 'b'], | |
234 | * ['a', 'c'], | |
235 | * ] | |
236 | * | |
237 | * @param array $items array of array of string | |
238 | * | |
239 | * @return Generator representing the cartesian product of given array. | |
240 | * | |
241 | * @see https://en.wikipedia.org/wiki/Cartesian_product | |
242 | */ | |
243 | function cartesian_product_generator($items) | |
244 | { | |
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]; | |
255 | } | |
256 | } | |
257 | } | |
258 | ||
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 | } | |
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 | } | |
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 | * | |
304 | * @param DateTimeInterface $date to format. | |
305 | * @param bool $time Displays time if true. | |
306 | * @param bool $intl Use international format if true. | |
307 | * | |
308 | * @return bool|string Formatted date, or false if the input is invalid. | |
309 | */ | |
310 | function format_date($date, $time = true, $intl = true) | |
311 | { | |
312 | if (! $date instanceof DateTimeInterface) { | |
313 | return false; | |
314 | } | |
315 | ||
316 | if (! $intl || ! class_exists('IntlDateFormatter')) { | |
317 | $format = $time ? '%c' : '%x'; | |
318 | return strftime($format, $date->getTimestamp()); | |
319 | } | |
320 | ||
321 | $formatter = new IntlDateFormatter( | |
322 | setlocale(LC_TIME, 0), | |
323 | IntlDateFormatter::LONG, | |
324 | $time ? IntlDateFormatter::LONG : IntlDateFormatter::NONE | |
325 | ); | |
326 | ||
327 | return $formatter->format($date); | |
328 | } | |
329 | ||
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 | ||
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); | |
380 | $last = strtolower($val[strlen($val) - 1]); | |
381 | $val = intval(substr($val, 0, -1)); | |
382 | switch ($last) { | |
383 | case 'g': | |
384 | $val *= 1024; | |
385 | // do no break in order 1024^2 for each unit | |
386 | case 'm': | |
387 | $val *= 1024; | |
388 | // do no break in order 1024^2 for each unit | |
389 | case 'k': | |
390 | $val *= 1024; | |
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 | ||
420 | return round($bytes) . $units[$i]; | |
421 | } | |
422 | ||
423 | /** | |
424 | * Try to determine max file size for uploads (POST). | |
425 | * Returns an integer (in bytes) or formatted depending on $format. | |
426 | * | |
427 | * @param mixed $limitPost post_max_size PHP setting | |
428 | * @param mixed $limitUpload upload_max_filesize PHP setting | |
429 | * @param bool $format Format max upload size to human readable size | |
430 | * | |
431 | * @return int|string max upload file size | |
432 | */ | |
433 | function get_max_upload_size($limitPost, $limitUpload, $format = true) | |
434 | { | |
435 | $size1 = return_bytes($limitPost); | |
436 | $size2 = return_bytes($limitUpload); | |
437 | // Return the smaller of two: | |
438 | $maxsize = min($size1, $size2); | |
439 | return $format ? human_bytes($maxsize) : $maxsize; | |
440 | } | |
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 | { | |
454 | $callback = function ($a, $b) use ($reverse) { | |
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 | } | |
472 | ||
473 | /** | |
474 | * Wrapper function for translation which match the API | |
475 | * of gettext()/_() and ngettext(). | |
476 | * | |
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. | |
483 | * | |
484 | * @return string Text translated. | |
485 | */ | |
486 | function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false) | |
487 | { | |
488 | $postFunction = $fixCase ? 'ucfirst' : function ($input) { | |
489 | return $input; | |
490 | }; | |
491 | ||
492 | return $postFunction(dn__($domain, $text, $nText, $nb, $variables)); | |
493 | } | |
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 | } |