]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/Utils.php
Move utils classes to Shaarli\Helper namespace and folder
[github/shaarli/Shaarli.git] / application / Utils.php
CommitLineData
ca74886f
V
1<?php
2/**
3 * Shaarli utilities
4 */
5
1abe6555 6/**
b38a1b02 7 * Format log using provided data.
1abe6555 8 *
b38a1b02
A
9 * @param string $message the message to log
10 * @param string|null $clientIp the client's remote IPv4/IPv6 address
478ce8af 11 *
b38a1b02 12 * @return string Formatted message to log
1abe6555 13 */
b38a1b02 14function format_log(string $message, string $clientIp = null): string
1abe6555 15{
b38a1b02
A
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;
1abe6555
V
24}
25
ca74886f
V
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,
d592daea
A
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.
7af9a418
A
41 *
42 * @param string $text Create a hash from this text.
43 *
44 * @return string generated small hash.
ca74886f
V
45 */
46function 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
5046bcb6
A
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.
ca74886f 60 */
5046bcb6 61function startsWith($haystack, $needle, $case = true)
ca74886f
V
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
5046bcb6
A
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.
ca74886f 77 */
5046bcb6 78function endsWith($haystack, $needle, $case = true)
ca74886f
V
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}
64bc92e3 85
64bc92e3 86/**
2925687e 87 * Htmlspecialchars wrapper
ee88a4bc 88 * Support multidimensional array of strings.
2925687e 89 *
ee88a4bc 90 * @param mixed $input Data to escape: a single string or an array of strings.
2925687e 91 *
c266a89d 92 * @return string|array escaped.
64bc92e3 93 */
ee88a4bc 94function escape($input)
64bc92e3 95{
c22fa57a
A
96 if (null === $input) {
97 return null;
98 }
99
72fbbcd6 100 if (is_bool($input) || is_int($input) || is_float($input) || $input instanceof DateTimeInterface) {
7d86f40b
A
101 return $input;
102 }
103
ee88a4bc
A
104 if (is_array($input)) {
105 $out = array();
f211e417 106 foreach ($input as $key => $value) {
72fbbcd6 107 $out[escape($key)] = escape($value);
ee88a4bc
A
108 }
109 return $out;
110 }
111 return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false);
64bc92e3 112}
113
2925687e
A
114/**
115 * Reverse the escape function.
116 *
117 * @param string $str the string to unescape.
118 *
119 * @return string unescaped string.
120 */
121function unescape($str)
122{
123 return htmlspecialchars_decode($str);
124}
125
64bc92e3 126/**
7af9a418
A
127 * Sanitize link before rendering.
128 *
129 * @param array $link Link to escape.
64bc92e3 130 */
131function 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}
9186ab95
V
138
139/**
140 * Checks if a string represents a valid date
822bffce
A
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
9186ab95 146 *
822bffce
A
147 * @see http://php.net/manual/en/class.datetime.php
148 * @see http://php.net/manual/en/datetime.createfromformat.php
9186ab95
V
149 */
150function checkDateFormat($format, $string)
151{
152 $date = DateTime::createFromFormat($format, $string);
153 return $date && $date->format($string) == $string;
154}
775803a0
A
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 */
166function generateLocation($referer, $host, $loopTerms = array())
167{
9e4cc28e 168 $finalReferer = './?';
775803a0
A
169
170 // No referer if it contains any value in $loopCriteria.
cf92b4dd 171 foreach (array_filter($loopTerms) as $value) {
775803a0 172 if (strpos($referer, $value) !== false) {
d01c2342 173 return $finalReferer;
775803a0
A
174 }
175 }
176
177 // Remove port from HTTP_HOST
178 if ($pos = strpos($host, ':')) {
179 $host = substr($host, 0, $pos);
180 }
181
d01c2342
A
182 $refererHost = parse_url($referer, PHP_URL_HOST);
183 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
184 $finalReferer = $referer;
775803a0
A
185 }
186
d01c2342 187 return $finalReferer;
775803a0 188}
d1e2f8e5 189
7b63e4ca
A
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 **/
196function autoLocale($headerLocale)
197{
198 // Default if browser does not send HTTP_ACCEPT_LANGUAGE
03b9cb60
A
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);
1255a42c 218 }
7b63e4ca
A
219 }
220 }
03b9cb60
A
221
222 setlocale(LC_ALL, $locales);
9ccca401 223}
cbfdcff2 224
1255a42c 225/**
52b50310 226 * Build a Generator object representing the cartesian product from given $items.
1255a42c
A
227 *
228 * Example:
229 * [['a'], ['b', 'c']]
230 * will generate:
52b50310
A
231 * [
232 * ['a', 'b'],
233 * ['a', 'c'],
234 * ]
1255a42c
A
235 *
236 * @param array $items array of array of string
237 *
52b50310
A
238 * @return Generator representing the cartesian product of given array.
239 *
240 * @see https://en.wikipedia.org/wiki/Cartesian_product
1255a42c 241 */
52b50310 242function cartesian_product_generator($items)
1255a42c 243{
52b50310
A
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];
1255a42c 254 }
1255a42c 255 }
1255a42c
A
256}
257
cbfdcff2
A
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 */
275function 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}
b3051a6a
A
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 */
292function normalize_spaces($string)
293{
294 return preg_replace('/\s{2,}/', ' ', trim($string));
295}
52b50310
A
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 *
69e29ff6
A
303 * @param DateTimeInterface $date to format.
304 * @param bool $time Displays time if true.
305 * @param bool $intl Use international format if true.
52b50310
A
306 *
307 * @return bool|string Formatted date, or false if the input is invalid.
308 */
81bd104d 309function format_date($date, $time = true, $intl = true)
52b50310 310{
69e29ff6 311 if (! $date instanceof DateTimeInterface) {
52b50310
A
312 return false;
313 }
314
315 if (! $intl || ! class_exists('IntlDateFormatter')) {
81bd104d
A
316 $format = $time ? '%c' : '%x';
317 return strftime($format, $date->getTimestamp());
52b50310
A
318 }
319
320 $formatter = new IntlDateFormatter(
321 setlocale(LC_TIME, 0),
322 IntlDateFormatter::LONG,
81bd104d 323 $time ? IntlDateFormatter::LONG : IntlDateFormatter::NONE
52b50310
A
324 );
325
326 return $formatter->format($date);
327}
84315a3b
A
328
329/**
330 * Check if the input is an integer, no matter its real type.
331 *
332 * PHP is a bit messy regarding this:
333 * - is_int returns false if the input is a string
334 * - ctype_digit returns false if the input is an integer or negative
335 *
336 * @param mixed $input value
337 *
338 * @return bool true if the input is an integer, false otherwise
339 */
340function is_integer_mixed($input)
341{
342 if (is_array($input) || is_bool($input) || is_object($input)) {
343 return false;
344 }
345 $input = strval($input);
346 return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
347}
348
349/**
350 * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
351 *
352 * @param string $val Size expressed in string.
353 *
354 * @return int Size expressed in bytes.
355 */
356function return_bytes($val)
357{
358 if (is_integer_mixed($val) || $val === '0' || empty($val)) {
359 return $val;
360 }
361 $val = trim($val);
362 $last = strtolower($val[strlen($val)-1]);
363 $val = intval(substr($val, 0, -1));
f211e417
V
364 switch ($last) {
365 case 'g':
366 $val *= 1024;
367 case 'm':
368 $val *= 1024;
369 case 'k':
370 $val *= 1024;
84315a3b
A
371 }
372 return $val;
373}
374
375/**
376 * Return a human readable size from bytes.
377 *
378 * @param int $bytes value
379 *
380 * @return string Human readable size
381 */
382function human_bytes($bytes)
383{
384 if ($bytes === '') {
385 return t('Setting not set');
386 }
387 if (! is_integer_mixed($bytes)) {
388 return $bytes;
389 }
390 $bytes = intval($bytes);
391 if ($bytes === 0) {
392 return t('Unlimited');
393 }
394
395 $units = [t('B'), t('kiB'), t('MiB'), t('GiB')];
396 for ($i = 0; $i < count($units) && $bytes >= 1024; ++$i) {
397 $bytes /= 1024;
398 }
399
6a19124a 400 return round($bytes) . $units[$i];
84315a3b
A
401}
402
403/**
404 * Try to determine max file size for uploads (POST).
6a19124a 405 * Returns an integer (in bytes) or formatted depending on $format.
84315a3b
A
406 *
407 * @param mixed $limitPost post_max_size PHP setting
408 * @param mixed $limitUpload upload_max_filesize PHP setting
6a19124a 409 * @param bool $format Format max upload size to human readable size
84315a3b 410 *
6a19124a 411 * @return int|string max upload file size
84315a3b 412 */
6a19124a 413function get_max_upload_size($limitPost, $limitUpload, $format = true)
84315a3b
A
414{
415 $size1 = return_bytes($limitPost);
416 $size2 = return_bytes($limitUpload);
417 // Return the smaller of two:
418 $maxsize = min($size1, $size2);
6a19124a 419 return $format ? human_bytes($maxsize) : $maxsize;
84315a3b 420}
aa4797ba
A
421
422/**
423 * Sort the given array alphabetically using php-intl if available.
424 * Case sensitive.
425 *
426 * Note: doesn't support multidimensional arrays
427 *
428 * @param array $data Input array, passed by reference
429 * @param bool $reverse Reverse sort if set to true
430 * @param bool $byKeys Sort the array by keys if set to true, by value otherwise.
431 */
432function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
433{
12266213 434 $callback = function ($a, $b) use ($reverse) {
aa4797ba
A
435 // Collator is part of PHP intl.
436 if (class_exists('Collator')) {
437 $collator = new Collator(setlocale(LC_COLLATE, 0));
438 if (!intl_is_failure(intl_get_error_code())) {
439 return $collator->compare($a, $b) * ($reverse ? -1 : 1);
440 }
441 }
442
443 return strcasecmp($a, $b) * ($reverse ? -1 : 1);
444 };
445
446 if ($byKeys) {
447 uksort($data, $callback);
448 } else {
449 usort($data, $callback);
450 }
451}
12266213
A
452
453/**
454 * Wrapper function for translation which match the API
455 * of gettext()/_() and ngettext().
456 *
457 * @param string $text Text to translate.
458 * @param string $nText The plural message ID.
459 * @param int $nb The number of items for plural forms.
460 * @param string $domain The domain where the translation is stored (default: shaarli).
461 *
6a65bc57 462 * @return string Text translated.
12266213 463 */
f211e417
V
464function t($text, $nText = '', $nb = 1, $domain = 'shaarli')
465{
12266213
A
466 return dn__($domain, $text, $nText, $nb);
467}
5c06c087
A
468
469/**
470 * Converts an exception into a printable stack trace string.
471 */
472function exception2text(Throwable $e): string
473{
474 return $e->getMessage() . PHP_EOL . $e->getFile() . $e->getLine() . PHP_EOL . $e->getTraceAsString();
475}
476