]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
format_date: include timezone in IntlDateFormatter object
[github/shaarli/Shaarli.git] / application / Utils.php
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 $formatter->setTimeZone($date->getTimezone());
327
328 return $formatter->format($date);
329 }
330
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 */
338 function format_month(DateTimeInterface $date)
339 {
340 if (! $date instanceof DateTimeInterface) {
341 return false;
342 }
343
344 return strftime('%B', $date->getTimestamp());
345 }
346
347
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 */
359 function 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 */
375 function return_bytes($val)
376 {
377 if (is_integer_mixed($val) || $val === '0' || empty($val)) {
378 return $val;
379 }
380 $val = trim($val);
381 $last = strtolower($val[strlen($val) - 1]);
382 $val = intval(substr($val, 0, -1));
383 switch ($last) {
384 case 'g':
385 $val *= 1024;
386 // do no break in order 1024^2 for each unit
387 case 'm':
388 $val *= 1024;
389 // do no break in order 1024^2 for each unit
390 case 'k':
391 $val *= 1024;
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 */
403 function 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
421 return round($bytes) . $units[$i];
422 }
423
424 /**
425 * Try to determine max file size for uploads (POST).
426 * Returns an integer (in bytes) or formatted depending on $format.
427 *
428 * @param mixed $limitPost post_max_size PHP setting
429 * @param mixed $limitUpload upload_max_filesize PHP setting
430 * @param bool $format Format max upload size to human readable size
431 *
432 * @return int|string max upload file size
433 */
434 function get_max_upload_size($limitPost, $limitUpload, $format = true)
435 {
436 $size1 = return_bytes($limitPost);
437 $size2 = return_bytes($limitUpload);
438 // Return the smaller of two:
439 $maxsize = min($size1, $size2);
440 return $format ? human_bytes($maxsize) : $maxsize;
441 }
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 */
453 function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
454 {
455 $callback = function ($a, $b) use ($reverse) {
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 }
473
474 /**
475 * Wrapper function for translation which match the API
476 * of gettext()/_() and ngettext().
477 *
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.
484 *
485 * @return string Text translated.
486 */
487 function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false)
488 {
489 $postFunction = $fixCase ? 'ucfirst' : function ($input) {
490 return $input;
491 };
492
493 return $postFunction(dn__($domain, $text, $nText, $nb, $variables));
494 }
495
496 /**
497 * Converts an exception into a printable stack trace string.
498 */
499 function exception2text(Throwable $e): string
500 {
501 return $e->getMessage() . PHP_EOL . $e->getFile() . $e->getLine() . PHP_EOL . $e->getTraceAsString();
502 }