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