]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
8 * Format log using provided data.
10 * @param string $message the message to log
11 * @param string|null $clientIp the client's remote IPv4/IPv6 address
13 * @return string Formatted message to log
15 function format_log(string $message, string $clientIp = null): string
19 if (!empty($clientIp)) {
20 // Note: we keep the first dash to avoid breaking fail2ban configs
21 $out = '- ' . $clientIp . ' - ' . $out;
28 * Returns the small hash of a string, using RFC 4648 base64url format
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)
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
40 * @warning before v0.8.1, smallhashes were built only with the date,
41 * and their value has been preserved.
43 * @param string $text Create a hash from this text.
45 * @return string generated small hash.
47 function smallHash($text)
49 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
50 return strtr($t, '+/', '-_');
54 * Tells if a string start with a substring
56 * @param string $haystack Given string.
57 * @param string $needle String to search at the beginning of $haystack.
58 * @param bool $case Case sensitive.
60 * @return bool True if $haystack starts with $needle.
62 function startsWith($haystack, $needle, $case = true)
65 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
67 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
71 * Tells if a string ends with a substring
73 * @param string $haystack Given string.
74 * @param string $needle String to search at the end of $haystack.
75 * @param bool $case Case sensitive.
77 * @return bool True if $haystack ends with $needle.
79 function endsWith($haystack, $needle, $case = true)
82 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
84 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
88 * Htmlspecialchars wrapper
89 * Support multidimensional array of strings.
91 * @param mixed $input Data to escape: a single string or an array of strings.
93 * @return string|array escaped.
95 function escape($input)
97 if (null === $input) {
101 if (is_bool($input) || is_int($input) || is_float($input) || $input instanceof DateTimeInterface
) {
105 if (is_array($input)) {
107 foreach ($input as $key => $value) {
108 $out[escape($key)] = escape($value);
112 return htmlspecialchars($input, ENT_COMPAT
, 'UTF-8', false);
116 * Reverse the escape function.
118 * @param string $str the string to unescape.
120 * @return string unescaped string.
122 function unescape($str)
124 return htmlspecialchars_decode($str);
128 * Sanitize link before rendering.
130 * @param array $link Link to escape.
132 function sanitizeLink(&$link)
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']);
141 * Checks if a string represents a valid date
143 * @param string $format The expected DateTime format of the string
144 * @param string $string A string-formatted date
146 * @return bool whether the string is a valid date
148 * @see http://php.net/manual/en/class.datetime.php
149 * @see http://php.net/manual/en/datetime.createfromformat.php
151 function checkDateFormat($format, $string)
153 $date = DateTime
::createFromFormat($format, $string);
154 return $date && $date->format($string) == $string;
158 * Generate a header location from HTTP_REFERER.
159 * Make sure the referer is Shaarli itself and prevent redirection loop.
161 * @param string $referer - HTTP_REFERER.
162 * @param string $host - Server HOST.
163 * @param array $loopTerms - Contains list of term to prevent redirection loop.
165 * @return string $referer - final referer.
167 function generateLocation($referer, $host, $loopTerms = [])
169 $finalReferer = './?';
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;
178 // Remove port from HTTP_HOST
179 if ($pos = strpos($host, ':')) {
180 $host = substr($host, 0, $pos);
183 $refererHost = parse_url($referer, PHP_URL_HOST
);
184 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
185 $finalReferer = $referer;
188 return $finalReferer;
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.
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").
197 function autoLocale($headerLocale)
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
)) {
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];
212 $items = [$first, $separators, $first, ['.'], $encodings];
214 $attempts = array_merge($attempts, iterator_to_array(cartesian_product_generator($items)));
217 if (! empty($attempts)) {
218 $locales = array_merge(array_map('implode', $attempts), $locales);
223 setlocale(LC_ALL
, $locales);
227 * Build a Generator object representing the cartesian product from given $items.
230 * [['a'], ['b', 'c']]
237 * @param array $items array of array of string
239 * @return Generator representing the cartesian product of given array.
241 * @see https://en.wikipedia.org/wiki/Cartesian_product
243 function cartesian_product_generator($items)
248 $subArray = array_pop($items);
249 if (empty($subArray)) {
252 foreach (cartesian_product_generator($items) as $item) {
253 foreach ($subArray as $value) {
254 yield
$item +
[count($item) => $value];
260 * Generates a default API secret.
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.
267 * PHP 7 provides random_int(), designed for cryptography.
268 * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator
270 * @param string $username Shaarli login username
271 * @param string $salt Shaarli password hash salt
273 * @return string|bool Generated API secret, 12 char length.
274 * Or false if invalid parameters are provided (which will make the API unusable).
276 function generate_api_secret($username, $salt)
278 if (empty($username) || empty($salt)) {
282 return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12));
286 * Trim string, replace sequences of whitespaces by a single space.
287 * PHP equivalent to `normalize-space` XSLT function.
289 * @param string $string Input string.
291 * @return mixed Normalized string.
293 function normalize_spaces($string)
295 return preg_replace('/\s{2,}/', ' ', trim($string));
299 * Format the date according to the locale.
301 * Requires php-intl to display international datetimes,
302 * otherwise default format '%c' will be returned.
304 * @param DateTimeInterface $date to format.
305 * @param bool $time Displays time if true.
306 * @param bool $intl Use international format if true.
308 * @return bool|string Formatted date, or false if the input is invalid.
310 function format_date($date, $time = true, $intl = true)
312 if (! $date instanceof DateTimeInterface
) {
316 if (! $intl || ! class_exists('IntlDateFormatter')) {
317 $format = $time ? '%c' : '%x';
318 return strftime($format, $date->getTimestamp());
321 $formatter = new IntlDateFormatter(
322 setlocale(LC_TIME
, 0),
323 IntlDateFormatter
::LONG
,
324 $time ? IntlDateFormatter
::LONG
: IntlDateFormatter
::NONE
326 $formatter->setTimeZone($date->getTimezone());
328 return $formatter->format($date);
332 * Format the date month according to the locale.
334 * @param DateTimeInterface $date to format.
336 * @return bool|string Formatted date, or false if the input is invalid.
338 function format_month(DateTimeInterface
$date)
340 if (! $date instanceof DateTimeInterface
) {
344 return strftime('%B', $date->getTimestamp());
349 * Check if the input is an integer, no matter its real type.
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
355 * @param mixed $input value
357 * @return bool true if the input is an integer, false otherwise
359 function is_integer_mixed($input)
361 if (is_array($input) || is_bool($input) || is_object($input)) {
364 $input = strval($input);
365 return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
369 * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
371 * @param string $val Size expressed in string.
373 * @return int Size expressed in bytes.
375 function return_bytes($val)
377 if (is_integer_mixed($val) || $val === '0' || empty($val)) {
381 $last = strtolower($val[strlen($val) - 1]);
382 $val = intval(substr($val, 0, -1));
386 // do no break in order 1024^2 for each unit
389 // do no break in order 1024^2 for each unit
397 * Return a human readable size from bytes.
399 * @param int $bytes value
401 * @return string Human readable size
403 function human_bytes($bytes)
406 return t('Setting not set');
408 if (! is_integer_mixed($bytes)) {
411 $bytes = intval($bytes);
413 return t('Unlimited');
416 $units = [t('B'), t('kiB'), t('MiB'), t('GiB')];
417 for ($i = 0; $i < count($units) && $bytes >= 1024; ++
$i) {
421 return round($bytes) . $units[$i];
425 * Try to determine max file size for uploads (POST).
426 * Returns an integer (in bytes) or formatted depending on $format.
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
432 * @return int|string max upload file size
434 function get_max_upload_size($limitPost, $limitUpload, $format = true)
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;
444 * Sort the given array alphabetically using php-intl if available.
447 * Note: doesn't support multidimensional arrays
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.
453 function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
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);
464 return strcasecmp($a, $b) * ($reverse ? -1 : 1);
468 uksort($data, $callback);
470 usort($data, $callback);
475 * Wrapper function for translation which match the API
476 * of gettext()/_() and ngettext().
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.
485 * @return string Text translated.
487 function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false)
489 $postFunction = $fixCase ? 'ucfirst' : function ($input) {
493 return $postFunction(dn__($domain, $text, $nText, $nb, $variables));
497 * Converts an exception into a printable stack trace string.
499 function exception2text(Throwable
$e): string
501 return $e->getMessage() . PHP_EOL
. $e->getFile() . $e->getLine() . PHP_EOL
. $e->getTraceAsString();