]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/Utils.php
Feature: add weekly and monthly view/RSS feed for daily page
[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 328
36e6d88d
A
329/**
330 * Format the date month according to the locale.
331 *
332 * @param DateTimeInterface $date to format.
333 *
334 * @return bool|string Formatted date, or false if the input is invalid.
335 */
336function format_month(DateTimeInterface $date)
337{
338 if (! $date instanceof DateTimeInterface) {
339 return false;
340 }
341
342 return strftime('%B', $date->getTimestamp());
343}
344
345
84315a3b
A
346/**
347 * Check if the input is an integer, no matter its real type.
348 *
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
352 *
353 * @param mixed $input value
354 *
355 * @return bool true if the input is an integer, false otherwise
356 */
357function is_integer_mixed($input)
358{
359 if (is_array($input) || is_bool($input) || is_object($input)) {
360 return false;
361 }
362 $input = strval($input);
363 return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
364}
365
366/**
367 * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
368 *
369 * @param string $val Size expressed in string.
370 *
371 * @return int Size expressed in bytes.
372 */
373function return_bytes($val)
374{
375 if (is_integer_mixed($val) || $val === '0' || empty($val)) {
376 return $val;
377 }
378 $val = trim($val);
379 $last = strtolower($val[strlen($val)-1]);
380 $val = intval(substr($val, 0, -1));
f211e417
V
381 switch ($last) {
382 case 'g':
383 $val *= 1024;
384 case 'm':
385 $val *= 1024;
386 case 'k':
387 $val *= 1024;
84315a3b
A
388 }
389 return $val;
390}
391
392/**
393 * Return a human readable size from bytes.
394 *
395 * @param int $bytes value
396 *
397 * @return string Human readable size
398 */
399function human_bytes($bytes)
400{
401 if ($bytes === '') {
402 return t('Setting not set');
403 }
404 if (! is_integer_mixed($bytes)) {
405 return $bytes;
406 }
407 $bytes = intval($bytes);
408 if ($bytes === 0) {
409 return t('Unlimited');
410 }
411
412 $units = [t('B'), t('kiB'), t('MiB'), t('GiB')];
413 for ($i = 0; $i < count($units) && $bytes >= 1024; ++$i) {
414 $bytes /= 1024;
415 }
416
6a19124a 417 return round($bytes) . $units[$i];
84315a3b
A
418}
419
420/**
421 * Try to determine max file size for uploads (POST).
6a19124a 422 * Returns an integer (in bytes) or formatted depending on $format.
84315a3b
A
423 *
424 * @param mixed $limitPost post_max_size PHP setting
425 * @param mixed $limitUpload upload_max_filesize PHP setting
6a19124a 426 * @param bool $format Format max upload size to human readable size
84315a3b 427 *
6a19124a 428 * @return int|string max upload file size
84315a3b 429 */
6a19124a 430function get_max_upload_size($limitPost, $limitUpload, $format = true)
84315a3b
A
431{
432 $size1 = return_bytes($limitPost);
433 $size2 = return_bytes($limitUpload);
434 // Return the smaller of two:
435 $maxsize = min($size1, $size2);
6a19124a 436 return $format ? human_bytes($maxsize) : $maxsize;
84315a3b 437}
aa4797ba
A
438
439/**
440 * Sort the given array alphabetically using php-intl if available.
441 * Case sensitive.
442 *
443 * Note: doesn't support multidimensional arrays
444 *
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.
448 */
449function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
450{
12266213 451 $callback = function ($a, $b) use ($reverse) {
aa4797ba
A
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);
457 }
458 }
459
460 return strcasecmp($a, $b) * ($reverse ? -1 : 1);
461 };
462
463 if ($byKeys) {
464 uksort($data, $callback);
465 } else {
466 usort($data, $callback);
467 }
468}
12266213
A
469
470/**
471 * Wrapper function for translation which match the API
472 * of gettext()/_() and ngettext().
473 *
36e6d88d
A
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.
12266213 480 *
6a65bc57 481 * @return string Text translated.
12266213 482 */
36e6d88d 483function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false)
f211e417 484{
36e6d88d
A
485 $postFunction = $fixCase ? 'ucfirst' : function ($input) { return $input; };
486
487 return $postFunction(dn__($domain, $text, $nText, $nb, $variables));
12266213 488}
5c06c087
A
489
490/**
491 * Converts an exception into a printable stack trace string.
492 */
493function exception2text(Throwable $e): string
494{
495 return $e->getMessage() . PHP_EOL . $e->getFile() . $e->getLine() . PHP_EOL . $e->getTraceAsString();
496}
497