]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/Utils.php
Merge pull request #1698 from ArthurHoaro/feature/plugins-search-filter
[github/shaarli/Shaarli.git] / application / Utils.php
CommitLineData
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 15function 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 */
47function 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 62function 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 79function 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 95function 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 */
122function 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 */
132function 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 */
151function 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 167function 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 **/
197function 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 243function 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 */
276function 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 */
293function 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 310function 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 325 );
dafd3f08 326 $formatter->setTimeZone($date->getTimezone());
52b50310
A
327
328 return $formatter->format($date);
329}
84315a3b 330
36e6d88d
A
331/**
332 * Format the date month according to the locale.
333 *
334 * @param DateTimeInterface $date to format.
335 *
336 * @return bool|string Formatted date, or false if the input is invalid.
337 */
338function format_month(DateTimeInterface $date)
339{
340 if (! $date instanceof DateTimeInterface) {
341 return false;
342 }
343
344 return strftime('%B', $date->getTimestamp());
345}
346
347
84315a3b
A
348/**
349 * Check if the input is an integer, no matter its real type.
350 *
351 * PHP is a bit messy regarding this:
352 * - is_int returns false if the input is a string
353 * - ctype_digit returns false if the input is an integer or negative
354 *
355 * @param mixed $input value
356 *
357 * @return bool true if the input is an integer, false otherwise
358 */
359function is_integer_mixed($input)
360{
361 if (is_array($input) || is_bool($input) || is_object($input)) {
362 return false;
363 }
364 $input = strval($input);
365 return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
366}
367
368/**
369 * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
370 *
371 * @param string $val Size expressed in string.
372 *
373 * @return int Size expressed in bytes.
374 */
375function return_bytes($val)
376{
377 if (is_integer_mixed($val) || $val === '0' || empty($val)) {
378 return $val;
379 }
380 $val = trim($val);
53054b2b 381 $last = strtolower($val[strlen($val) - 1]);
84315a3b 382 $val = intval(substr($val, 0, -1));
f211e417
V
383 switch ($last) {
384 case 'g':
385 $val *= 1024;
b99e00f7 386 // do no break in order 1024^2 for each unit
f211e417
V
387 case 'm':
388 $val *= 1024;
b99e00f7 389 // do no break in order 1024^2 for each unit
f211e417
V
390 case 'k':
391 $val *= 1024;
84315a3b
A
392 }
393 return $val;
394}
395
396/**
397 * Return a human readable size from bytes.
398 *
399 * @param int $bytes value
400 *
401 * @return string Human readable size
402 */
403function human_bytes($bytes)
404{
405 if ($bytes === '') {
406 return t('Setting not set');
407 }
408 if (! is_integer_mixed($bytes)) {
409 return $bytes;
410 }
411 $bytes = intval($bytes);
412 if ($bytes === 0) {
413 return t('Unlimited');
414 }
415
416 $units = [t('B'), t('kiB'), t('MiB'), t('GiB')];
417 for ($i = 0; $i < count($units) && $bytes >= 1024; ++$i) {
418 $bytes /= 1024;
419 }
420
6a19124a 421 return round($bytes) . $units[$i];
84315a3b
A
422}
423
424/**
425 * Try to determine max file size for uploads (POST).
6a19124a 426 * Returns an integer (in bytes) or formatted depending on $format.
84315a3b
A
427 *
428 * @param mixed $limitPost post_max_size PHP setting
429 * @param mixed $limitUpload upload_max_filesize PHP setting
6a19124a 430 * @param bool $format Format max upload size to human readable size
84315a3b 431 *
6a19124a 432 * @return int|string max upload file size
84315a3b 433 */
6a19124a 434function get_max_upload_size($limitPost, $limitUpload, $format = true)
84315a3b
A
435{
436 $size1 = return_bytes($limitPost);
437 $size2 = return_bytes($limitUpload);
438 // Return the smaller of two:
439 $maxsize = min($size1, $size2);
6a19124a 440 return $format ? human_bytes($maxsize) : $maxsize;
84315a3b 441}
aa4797ba
A
442
443/**
444 * Sort the given array alphabetically using php-intl if available.
445 * Case sensitive.
446 *
447 * Note: doesn't support multidimensional arrays
448 *
449 * @param array $data Input array, passed by reference
450 * @param bool $reverse Reverse sort if set to true
451 * @param bool $byKeys Sort the array by keys if set to true, by value otherwise.
452 */
453function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
454{
12266213 455 $callback = function ($a, $b) use ($reverse) {
aa4797ba
A
456 // Collator is part of PHP intl.
457 if (class_exists('Collator')) {
458 $collator = new Collator(setlocale(LC_COLLATE, 0));
459 if (!intl_is_failure(intl_get_error_code())) {
460 return $collator->compare($a, $b) * ($reverse ? -1 : 1);
461 }
462 }
463
464 return strcasecmp($a, $b) * ($reverse ? -1 : 1);
465 };
466
467 if ($byKeys) {
468 uksort($data, $callback);
469 } else {
470 usort($data, $callback);
471 }
472}
12266213
A
473
474/**
475 * Wrapper function for translation which match the API
476 * of gettext()/_() and ngettext().
477 *
36e6d88d
A
478 * @param string $text Text to translate.
479 * @param string $nText The plural message ID.
480 * @param int $nb The number of items for plural forms.
481 * @param string $domain The domain where the translation is stored (default: shaarli).
482 * @param array $variables Associative array of variables to replace in translated text.
483 * @param bool $fixCase Apply `ucfirst` on the translated string, might be useful for strings with variables.
12266213 484 *
6a65bc57 485 * @return string Text translated.
12266213 486 */
36e6d88d 487function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false)
f211e417 488{
53054b2b
A
489 $postFunction = $fixCase ? 'ucfirst' : function ($input) {
490 return $input;
491 };
36e6d88d
A
492
493 return $postFunction(dn__($domain, $text, $nText, $nb, $variables));
12266213 494}
5c06c087
A
495
496/**
497 * Converts an exception into a printable stack trace string.
498 */
499function exception2text(Throwable $e): string
500{
501 return $e->getMessage() . PHP_EOL . $e->getFile() . $e->getLine() . PHP_EOL . $e->getTraceAsString();
502}