]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/Utils.php
Add a token available everywhere
[github/shaarli/Shaarli.git] / application / Utils.php
CommitLineData
ca74886f
V
1<?php
2/**
3 * Shaarli utilities
4 */
5
1abe6555
V
6/**
7 * Logs a message to a text file
8 *
478ce8af
V
9 * The log format is compatible with fail2ban.
10 *
1abe6555
V
11 * @param string $logFile where to write the logs
12 * @param string $clientIp the client's remote IPv4/IPv6 address
13 * @param string $message the message to log
14 */
15function logm($logFile, $clientIp, $message)
16{
478ce8af
V
17 file_put_contents(
18 $logFile,
aa7f7b3e 19 date('Y/m/d H:i:s').' - '.$clientIp.' - '.strval($message).PHP_EOL,
478ce8af
V
20 FILE_APPEND
21 );
1abe6555
V
22}
23
ca74886f
V
24/**
25 * Returns the small hash of a string, using RFC 4648 base64url format
26 *
27 * Small hashes:
28 * - are unique (well, as unique as crc32, at last)
29 * - are always 6 characters long.
30 * - only use the following characters: a-z A-Z 0-9 - _ @
31 * - are NOT cryptographically secure (they CAN be forged)
32 *
33 * In Shaarli, they are used as a tinyurl-like link to individual entries,
d592daea
A
34 * built once with the combination of the date and item ID.
35 * e.g. smallHash('20111006_131924' . 142) --> eaWxtQ
36 *
37 * @warning before v0.8.1, smallhashes were built only with the date,
38 * and their value has been preserved.
7af9a418
A
39 *
40 * @param string $text Create a hash from this text.
41 *
42 * @return string generated small hash.
ca74886f
V
43 */
44function smallHash($text)
45{
46 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
47 return strtr($t, '+/', '-_');
48}
49
50/**
51 * Tells if a string start with a substring
5046bcb6
A
52 *
53 * @param string $haystack Given string.
54 * @param string $needle String to search at the beginning of $haystack.
55 * @param bool $case Case sensitive.
56 *
57 * @return bool True if $haystack starts with $needle.
ca74886f 58 */
5046bcb6 59function startsWith($haystack, $needle, $case = true)
ca74886f
V
60{
61 if ($case) {
62 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
63 }
64 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
65}
66
67/**
68 * Tells if a string ends with a substring
5046bcb6
A
69 *
70 * @param string $haystack Given string.
71 * @param string $needle String to search at the end of $haystack.
72 * @param bool $case Case sensitive.
73 *
74 * @return bool True if $haystack ends with $needle.
ca74886f 75 */
5046bcb6 76function endsWith($haystack, $needle, $case = true)
ca74886f
V
77{
78 if ($case) {
79 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
80 }
81 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
82}
64bc92e3 83
64bc92e3 84/**
2925687e 85 * Htmlspecialchars wrapper
ee88a4bc 86 * Support multidimensional array of strings.
2925687e 87 *
ee88a4bc 88 * @param mixed $input Data to escape: a single string or an array of strings.
2925687e
A
89 *
90 * @return string escaped.
64bc92e3 91 */
ee88a4bc 92function escape($input)
64bc92e3 93{
ee88a4bc
A
94 if (is_array($input)) {
95 $out = array();
96 foreach($input as $key => $value) {
97 $out[$key] = escape($value);
98 }
99 return $out;
100 }
101 return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false);
64bc92e3 102}
103
2925687e
A
104/**
105 * Reverse the escape function.
106 *
107 * @param string $str the string to unescape.
108 *
109 * @return string unescaped string.
110 */
111function unescape($str)
112{
113 return htmlspecialchars_decode($str);
114}
115
64bc92e3 116/**
7af9a418
A
117 * Sanitize link before rendering.
118 *
119 * @param array $link Link to escape.
64bc92e3 120 */
121function sanitizeLink(&$link)
122{
123 $link['url'] = escape($link['url']); // useful?
124 $link['title'] = escape($link['title']);
125 $link['description'] = escape($link['description']);
126 $link['tags'] = escape($link['tags']);
127}
9186ab95
V
128
129/**
130 * Checks if a string represents a valid date
822bffce
A
131
132 * @param string $format The expected DateTime format of the string
133 * @param string $string A string-formatted date
134 *
135 * @return bool whether the string is a valid date
9186ab95 136 *
822bffce
A
137 * @see http://php.net/manual/en/class.datetime.php
138 * @see http://php.net/manual/en/datetime.createfromformat.php
9186ab95
V
139 */
140function checkDateFormat($format, $string)
141{
142 $date = DateTime::createFromFormat($format, $string);
143 return $date && $date->format($string) == $string;
144}
775803a0
A
145
146/**
147 * Generate a header location from HTTP_REFERER.
148 * Make sure the referer is Shaarli itself and prevent redirection loop.
149 *
150 * @param string $referer - HTTP_REFERER.
151 * @param string $host - Server HOST.
152 * @param array $loopTerms - Contains list of term to prevent redirection loop.
153 *
154 * @return string $referer - final referer.
155 */
156function generateLocation($referer, $host, $loopTerms = array())
157{
d01c2342 158 $finalReferer = '?';
775803a0
A
159
160 // No referer if it contains any value in $loopCriteria.
161 foreach ($loopTerms as $value) {
162 if (strpos($referer, $value) !== false) {
d01c2342 163 return $finalReferer;
775803a0
A
164 }
165 }
166
167 // Remove port from HTTP_HOST
168 if ($pos = strpos($host, ':')) {
169 $host = substr($host, 0, $pos);
170 }
171
d01c2342
A
172 $refererHost = parse_url($referer, PHP_URL_HOST);
173 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
174 $finalReferer = $referer;
775803a0
A
175 }
176
d01c2342 177 return $finalReferer;
775803a0 178}
d1e2f8e5 179
06b6660a
A
180/**
181 * Validate session ID to prevent Full Path Disclosure.
68bc2135 182 *
06b6660a 183 * See #298.
68bc2135 184 * The session ID's format depends on the hash algorithm set in PHP settings
06b6660a
A
185 *
186 * @param string $sessionId Session ID
187 *
188 * @return true if valid, false otherwise.
68bc2135
V
189 *
190 * @see http://php.net/manual/en/function.hash-algos.php
191 * @see http://php.net/manual/en/session.configuration.php
06b6660a
A
192 */
193function is_session_id_valid($sessionId)
194{
195 if (empty($sessionId)) {
196 return false;
197 }
198
199 if (!$sessionId) {
200 return false;
201 }
202
68bc2135 203 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
06b6660a
A
204 return false;
205 }
206
207 return true;
208}
90e5bd65 209
7b63e4ca
A
210/**
211 * Sniff browser language to set the locale automatically.
212 * Note that is may not work on your server if the corresponding locale is not installed.
213 *
214 * @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").
215 **/
216function autoLocale($headerLocale)
217{
218 // Default if browser does not send HTTP_ACCEPT_LANGUAGE
03b9cb60
A
219 $locales = array('en_US', 'en_US.utf8', 'en_US.UTF-8');
220 if (! empty($headerLocale)) {
221 if (preg_match_all('/([a-z]{2,3})[-_]?([a-z]{2})?,?/i', $headerLocale, $matches, PREG_SET_ORDER)) {
222 $attempts = [];
223 foreach ($matches as $match) {
224 $first = [strtolower($match[1]), strtoupper($match[1])];
225 $separators = ['_', '-'];
226 $encodings = ['utf8', 'UTF-8'];
227 if (!empty($match[2])) {
228 $second = [strtoupper($match[2]), strtolower($match[2])];
229 $items = [$first, $separators, $second, ['.'], $encodings];
230 } else {
231 $items = [$first, $separators, $first, ['.'], $encodings];
232 }
233 $attempts = array_merge($attempts, iterator_to_array(cartesian_product_generator($items)));
234 }
235
236 if (! empty($attempts)) {
237 $locales = array_merge(array_map('implode', $attempts), $locales);
1255a42c 238 }
7b63e4ca
A
239 }
240 }
03b9cb60
A
241
242 setlocale(LC_ALL, $locales);
9ccca401 243}
cbfdcff2 244
1255a42c 245/**
52b50310 246 * Build a Generator object representing the cartesian product from given $items.
1255a42c
A
247 *
248 * Example:
249 * [['a'], ['b', 'c']]
250 * will generate:
52b50310
A
251 * [
252 * ['a', 'b'],
253 * ['a', 'c'],
254 * ]
1255a42c
A
255 *
256 * @param array $items array of array of string
257 *
52b50310
A
258 * @return Generator representing the cartesian product of given array.
259 *
260 * @see https://en.wikipedia.org/wiki/Cartesian_product
1255a42c 261 */
52b50310 262function cartesian_product_generator($items)
1255a42c 263{
52b50310
A
264 if (empty($items)) {
265 yield [];
266 }
267 $subArray = array_pop($items);
268 if (empty($subArray)) {
269 return;
270 }
271 foreach (cartesian_product_generator($items) as $item) {
272 foreach ($subArray as $value) {
273 yield $item + [count($item) => $value];
1255a42c 274 }
1255a42c 275 }
1255a42c
A
276}
277
cbfdcff2
A
278/**
279 * Generates a default API secret.
280 *
281 * Note that the random-ish methods used in this function are predictable,
282 * which makes them NOT suitable for crypto.
283 * BUT the random string is salted with the salt and hashed with the username.
284 * It makes the generated API secret secured enough for Shaarli.
285 *
286 * PHP 7 provides random_int(), designed for cryptography.
287 * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator
288
289 * @param string $username Shaarli login username
290 * @param string $salt Shaarli password hash salt
291 *
292 * @return string|bool Generated API secret, 12 char length.
293 * Or false if invalid parameters are provided (which will make the API unusable).
294 */
295function generate_api_secret($username, $salt)
296{
297 if (empty($username) || empty($salt)) {
298 return false;
299 }
300
301 return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12));
302}
b3051a6a
A
303
304/**
305 * Trim string, replace sequences of whitespaces by a single space.
306 * PHP equivalent to `normalize-space` XSLT function.
307 *
308 * @param string $string Input string.
309 *
310 * @return mixed Normalized string.
311 */
312function normalize_spaces($string)
313{
314 return preg_replace('/\s{2,}/', ' ', trim($string));
315}
52b50310
A
316
317/**
318 * Format the date according to the locale.
319 *
320 * Requires php-intl to display international datetimes,
321 * otherwise default format '%c' will be returned.
322 *
323 * @param DateTime $date to format.
81bd104d 324 * @param bool $time Displays time if true.
52b50310
A
325 * @param bool $intl Use international format if true.
326 *
327 * @return bool|string Formatted date, or false if the input is invalid.
328 */
81bd104d 329function format_date($date, $time = true, $intl = true)
52b50310
A
330{
331 if (! $date instanceof DateTime) {
332 return false;
333 }
334
335 if (! $intl || ! class_exists('IntlDateFormatter')) {
81bd104d
A
336 $format = $time ? '%c' : '%x';
337 return strftime($format, $date->getTimestamp());
52b50310
A
338 }
339
340 $formatter = new IntlDateFormatter(
341 setlocale(LC_TIME, 0),
342 IntlDateFormatter::LONG,
81bd104d 343 $time ? IntlDateFormatter::LONG : IntlDateFormatter::NONE
52b50310
A
344 );
345
346 return $formatter->format($date);
347}
84315a3b
A
348
349/**
350 * Check if the input is an integer, no matter its real type.
351 *
352 * PHP is a bit messy regarding this:
353 * - is_int returns false if the input is a string
354 * - ctype_digit returns false if the input is an integer or negative
355 *
356 * @param mixed $input value
357 *
358 * @return bool true if the input is an integer, false otherwise
359 */
360function is_integer_mixed($input)
361{
362 if (is_array($input) || is_bool($input) || is_object($input)) {
363 return false;
364 }
365 $input = strval($input);
366 return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
367}
368
369/**
370 * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
371 *
372 * @param string $val Size expressed in string.
373 *
374 * @return int Size expressed in bytes.
375 */
376function return_bytes($val)
377{
378 if (is_integer_mixed($val) || $val === '0' || empty($val)) {
379 return $val;
380 }
381 $val = trim($val);
382 $last = strtolower($val[strlen($val)-1]);
383 $val = intval(substr($val, 0, -1));
384 switch($last) {
385 case 'g': $val *= 1024;
386 case 'm': $val *= 1024;
387 case 'k': $val *= 1024;
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}