]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
7 * Format log using provided data.
9 * @param string $message the message to log
10 * @param string|null $clientIp the client's remote IPv4/IPv6 address
12 * @return string Formatted message to log
14 function format_log(string $message, string $clientIp = null): string
18 if (!empty($clientIp)) {
19 // Note: we keep the first dash to avoid breaking fail2ban configs
20 $out = '- ' . $clientIp . ' - ' . $out;
27 * Returns the small hash of a string, using RFC 4648 base64url format
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)
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
39 * @warning before v0.8.1, smallhashes were built only with the date,
40 * and their value has been preserved.
42 * @param string $text Create a hash from this text.
44 * @return string generated small hash.
46 function smallHash($text)
48 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
49 return strtr($t, '+/', '-_');
53 * Tells if a string start with a substring
55 * @param string $haystack Given string.
56 * @param string $needle String to search at the beginning of $haystack.
57 * @param bool $case Case sensitive.
59 * @return bool True if $haystack starts with $needle.
61 function startsWith($haystack, $needle, $case = true)
64 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
66 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
70 * Tells if a string ends with a substring
72 * @param string $haystack Given string.
73 * @param string $needle String to search at the end of $haystack.
74 * @param bool $case Case sensitive.
76 * @return bool True if $haystack ends with $needle.
78 function endsWith($haystack, $needle, $case = true)
81 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
83 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
87 * Htmlspecialchars wrapper
88 * Support multidimensional array of strings.
90 * @param mixed $input Data to escape: a single string or an array of strings.
92 * @return string|array escaped.
94 function escape($input)
96 if (null === $input) {
100 if (is_bool($input) || is_int($input) || is_float($input) || $input instanceof DateTimeInterface
) {
104 if (is_array($input)) {
106 foreach ($input as $key => $value) {
107 $out[escape($key)] = escape($value);
111 return htmlspecialchars($input, ENT_COMPAT
, 'UTF-8', false);
115 * Reverse the escape function.
117 * @param string $str the string to unescape.
119 * @return string unescaped string.
121 function unescape($str)
123 return htmlspecialchars_decode($str);
127 * Sanitize link before rendering.
129 * @param array $link Link to escape.
131 function sanitizeLink(&$link)
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']);
140 * Checks if a string represents a valid date
142 * @param string $format The expected DateTime format of the string
143 * @param string $string A string-formatted date
145 * @return bool whether the string is a valid date
147 * @see http://php.net/manual/en/class.datetime.php
148 * @see http://php.net/manual/en/datetime.createfromformat.php
150 function checkDateFormat($format, $string)
152 $date = DateTime
::createFromFormat($format, $string);
153 return $date && $date->format($string) == $string;
157 * Generate a header location from HTTP_REFERER.
158 * Make sure the referer is Shaarli itself and prevent redirection loop.
160 * @param string $referer - HTTP_REFERER.
161 * @param string $host - Server HOST.
162 * @param array $loopTerms - Contains list of term to prevent redirection loop.
164 * @return string $referer - final referer.
166 function generateLocation($referer, $host, $loopTerms = array())
168 $finalReferer = './?';
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;
177 // Remove port from HTTP_HOST
178 if ($pos = strpos($host, ':')) {
179 $host = substr($host, 0, $pos);
182 $refererHost = parse_url($referer, PHP_URL_HOST
);
183 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
184 $finalReferer = $referer;
187 return $finalReferer;
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.
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").
196 function autoLocale($headerLocale)
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
)) {
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];
211 $items = [$first, $separators, $first, ['.'], $encodings];
213 $attempts = array_merge($attempts, iterator_to_array(cartesian_product_generator($items)));
216 if (! empty($attempts)) {
217 $locales = array_merge(array_map('implode', $attempts), $locales);
222 setlocale(LC_ALL
, $locales);
226 * Build a Generator object representing the cartesian product from given $items.
229 * [['a'], ['b', 'c']]
236 * @param array $items array of array of string
238 * @return Generator representing the cartesian product of given array.
240 * @see https://en.wikipedia.org/wiki/Cartesian_product
242 function cartesian_product_generator($items)
247 $subArray = array_pop($items);
248 if (empty($subArray)) {
251 foreach (cartesian_product_generator($items) as $item) {
252 foreach ($subArray as $value) {
253 yield
$item +
[count($item) => $value];
259 * Generates a default API secret.
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.
266 * PHP 7 provides random_int(), designed for cryptography.
267 * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator
269 * @param string $username Shaarli login username
270 * @param string $salt Shaarli password hash salt
272 * @return string|bool Generated API secret, 12 char length.
273 * Or false if invalid parameters are provided (which will make the API unusable).
275 function generate_api_secret($username, $salt)
277 if (empty($username) || empty($salt)) {
281 return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12));
285 * Trim string, replace sequences of whitespaces by a single space.
286 * PHP equivalent to `normalize-space` XSLT function.
288 * @param string $string Input string.
290 * @return mixed Normalized string.
292 function normalize_spaces($string)
294 return preg_replace('/\s{2,}/', ' ', trim($string));
298 * Format the date according to the locale.
300 * Requires php-intl to display international datetimes,
301 * otherwise default format '%c' will be returned.
303 * @param DateTimeInterface $date to format.
304 * @param bool $time Displays time if true.
305 * @param bool $intl Use international format if true.
307 * @return bool|string Formatted date, or false if the input is invalid.
309 function format_date($date, $time = true, $intl = true)
311 if (! $date instanceof DateTimeInterface
) {
315 if (! $intl || ! class_exists('IntlDateFormatter')) {
316 $format = $time ? '%c' : '%x';
317 return strftime($format, $date->getTimestamp());
320 $formatter = new IntlDateFormatter(
321 setlocale(LC_TIME
, 0),
322 IntlDateFormatter
::LONG
,
323 $time ? IntlDateFormatter
::LONG
: IntlDateFormatter
::NONE
326 return $formatter->format($date);
330 * Format the date month according to the locale.
332 * @param DateTimeInterface $date to format.
334 * @return bool|string Formatted date, or false if the input is invalid.
336 function format_month(DateTimeInterface
$date)
338 if (! $date instanceof DateTimeInterface
) {
342 return strftime('%B', $date->getTimestamp());
347 * Check if the input is an integer, no matter its real type.
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
353 * @param mixed $input value
355 * @return bool true if the input is an integer, false otherwise
357 function is_integer_mixed($input)
359 if (is_array($input) || is_bool($input) || is_object($input)) {
362 $input = strval($input);
363 return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
367 * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
369 * @param string $val Size expressed in string.
371 * @return int Size expressed in bytes.
373 function return_bytes($val)
375 if (is_integer_mixed($val) || $val === '0' || empty($val)) {
379 $last = strtolower($val[strlen($val)-1]);
380 $val = intval(substr($val, 0, -1));
393 * Return a human readable size from bytes.
395 * @param int $bytes value
397 * @return string Human readable size
399 function human_bytes($bytes)
402 return t('Setting not set');
404 if (! is_integer_mixed($bytes)) {
407 $bytes = intval($bytes);
409 return t('Unlimited');
412 $units = [t('B'), t('kiB'), t('MiB'), t('GiB')];
413 for ($i = 0; $i < count($units) && $bytes >= 1024; ++
$i) {
417 return round($bytes) . $units[$i];
421 * Try to determine max file size for uploads (POST).
422 * Returns an integer (in bytes) or formatted depending on $format.
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
428 * @return int|string max upload file size
430 function get_max_upload_size($limitPost, $limitUpload, $format = true)
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;
440 * Sort the given array alphabetically using php-intl if available.
443 * Note: doesn't support multidimensional arrays
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.
449 function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
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);
460 return strcasecmp($a, $b) * ($reverse ? -1 : 1);
464 uksort($data, $callback);
466 usort($data, $callback);
471 * Wrapper function for translation which match the API
472 * of gettext()/_() and ngettext().
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.
481 * @return string Text translated.
483 function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false)
485 $postFunction = $fixCase ? 'ucfirst' : function ($input) { return $input
; };
487 return $postFunction(dn__($domain, $text, $nText, $nb, $variables));
491 * Converts an exception into a printable stack trace string.
493 function exception2text(Throwable
$e): string
495 return $e->getMessage() . PHP_EOL
. $e->getFile() . $e->getLine() . PHP_EOL
. $e->getTraceAsString();