Utils.php 13 KB

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