Utils.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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_array($input)) {
  90. $out = array();
  91. foreach($input as $key => $value) {
  92. $out[$key] = escape($value);
  93. }
  94. return $out;
  95. }
  96. return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false);
  97. }
  98. /**
  99. * Reverse the escape function.
  100. *
  101. * @param string $str the string to unescape.
  102. *
  103. * @return string unescaped string.
  104. */
  105. function unescape($str)
  106. {
  107. return htmlspecialchars_decode($str);
  108. }
  109. /**
  110. * Sanitize link before rendering.
  111. *
  112. * @param array $link Link to escape.
  113. */
  114. function sanitizeLink(&$link)
  115. {
  116. $link['url'] = escape($link['url']); // useful?
  117. $link['title'] = escape($link['title']);
  118. $link['description'] = escape($link['description']);
  119. $link['tags'] = escape($link['tags']);
  120. }
  121. /**
  122. * Checks if a string represents a valid date
  123. * @param string $format The expected DateTime format of the string
  124. * @param string $string A string-formatted date
  125. *
  126. * @return bool whether the string is a valid date
  127. *
  128. * @see http://php.net/manual/en/class.datetime.php
  129. * @see http://php.net/manual/en/datetime.createfromformat.php
  130. */
  131. function checkDateFormat($format, $string)
  132. {
  133. $date = DateTime::createFromFormat($format, $string);
  134. return $date && $date->format($string) == $string;
  135. }
  136. /**
  137. * Generate a header location from HTTP_REFERER.
  138. * Make sure the referer is Shaarli itself and prevent redirection loop.
  139. *
  140. * @param string $referer - HTTP_REFERER.
  141. * @param string $host - Server HOST.
  142. * @param array $loopTerms - Contains list of term to prevent redirection loop.
  143. *
  144. * @return string $referer - final referer.
  145. */
  146. function generateLocation($referer, $host, $loopTerms = array())
  147. {
  148. $finalReferer = '?';
  149. // No referer if it contains any value in $loopCriteria.
  150. foreach ($loopTerms as $value) {
  151. if (strpos($referer, $value) !== false) {
  152. return $finalReferer;
  153. }
  154. }
  155. // Remove port from HTTP_HOST
  156. if ($pos = strpos($host, ':')) {
  157. $host = substr($host, 0, $pos);
  158. }
  159. $refererHost = parse_url($referer, PHP_URL_HOST);
  160. if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
  161. $finalReferer = $referer;
  162. }
  163. return $finalReferer;
  164. }
  165. /**
  166. * Validate session ID to prevent Full Path Disclosure.
  167. *
  168. * See #298.
  169. * The session ID's format depends on the hash algorithm set in PHP settings
  170. *
  171. * @param string $sessionId Session ID
  172. *
  173. * @return true if valid, false otherwise.
  174. *
  175. * @see http://php.net/manual/en/function.hash-algos.php
  176. * @see http://php.net/manual/en/session.configuration.php
  177. */
  178. function is_session_id_valid($sessionId)
  179. {
  180. if (empty($sessionId)) {
  181. return false;
  182. }
  183. if (!$sessionId) {
  184. return false;
  185. }
  186. if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
  187. return false;
  188. }
  189. return true;
  190. }
  191. /**
  192. * Sniff browser language to set the locale automatically.
  193. * Note that is may not work on your server if the corresponding locale is not installed.
  194. *
  195. * @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. **/
  197. function autoLocale($headerLocale)
  198. {
  199. // Default if browser does not send HTTP_ACCEPT_LANGUAGE
  200. $locales = array('en_US', 'en_US.utf8', 'en_US.UTF-8');
  201. if (! empty($headerLocale)) {
  202. if (preg_match_all('/([a-z]{2,3})[-_]?([a-z]{2})?,?/i', $headerLocale, $matches, PREG_SET_ORDER)) {
  203. $attempts = [];
  204. foreach ($matches as $match) {
  205. $first = [strtolower($match[1]), strtoupper($match[1])];
  206. $separators = ['_', '-'];
  207. $encodings = ['utf8', 'UTF-8'];
  208. if (!empty($match[2])) {
  209. $second = [strtoupper($match[2]), strtolower($match[2])];
  210. $items = [$first, $separators, $second, ['.'], $encodings];
  211. } else {
  212. $items = [$first, $separators, $first, ['.'], $encodings];
  213. }
  214. $attempts = array_merge($attempts, iterator_to_array(cartesian_product_generator($items)));
  215. }
  216. if (! empty($attempts)) {
  217. $locales = array_merge(array_map('implode', $attempts), $locales);
  218. }
  219. }
  220. }
  221. setlocale(LC_ALL, $locales);
  222. }
  223. /**
  224. * Build a Generator object representing the cartesian product from given $items.
  225. *
  226. * Example:
  227. * [['a'], ['b', 'c']]
  228. * will generate:
  229. * [
  230. * ['a', 'b'],
  231. * ['a', 'c'],
  232. * ]
  233. *
  234. * @param array $items array of array of string
  235. *
  236. * @return Generator representing the cartesian product of given array.
  237. *
  238. * @see https://en.wikipedia.org/wiki/Cartesian_product
  239. */
  240. function cartesian_product_generator($items)
  241. {
  242. if (empty($items)) {
  243. yield [];
  244. }
  245. $subArray = array_pop($items);
  246. if (empty($subArray)) {
  247. return;
  248. }
  249. foreach (cartesian_product_generator($items) as $item) {
  250. foreach ($subArray as $value) {
  251. yield $item + [count($item) => $value];
  252. }
  253. }
  254. }
  255. /**
  256. * Generates a default API secret.
  257. *
  258. * Note that the random-ish methods used in this function are predictable,
  259. * which makes them NOT suitable for crypto.
  260. * BUT the random string is salted with the salt and hashed with the username.
  261. * It makes the generated API secret secured enough for Shaarli.
  262. *
  263. * PHP 7 provides random_int(), designed for cryptography.
  264. * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator
  265. * @param string $username Shaarli login username
  266. * @param string $salt Shaarli password hash salt
  267. *
  268. * @return string|bool Generated API secret, 12 char length.
  269. * Or false if invalid parameters are provided (which will make the API unusable).
  270. */
  271. function generate_api_secret($username, $salt)
  272. {
  273. if (empty($username) || empty($salt)) {
  274. return false;
  275. }
  276. return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12));
  277. }
  278. /**
  279. * Trim string, replace sequences of whitespaces by a single space.
  280. * PHP equivalent to `normalize-space` XSLT function.
  281. *
  282. * @param string $string Input string.
  283. *
  284. * @return mixed Normalized string.
  285. */
  286. function normalize_spaces($string)
  287. {
  288. return preg_replace('/\s{2,}/', ' ', trim($string));
  289. }
  290. /**
  291. * Format the date according to the locale.
  292. *
  293. * Requires php-intl to display international datetimes,
  294. * otherwise default format '%c' will be returned.
  295. *
  296. * @param DateTime $date to format.
  297. * @param bool $time Displays time if true.
  298. * @param bool $intl Use international format if true.
  299. *
  300. * @return bool|string Formatted date, or false if the input is invalid.
  301. */
  302. function format_date($date, $time = true, $intl = true)
  303. {
  304. if (! $date instanceof DateTime) {
  305. return false;
  306. }
  307. if (! $intl || ! class_exists('IntlDateFormatter')) {
  308. $format = $time ? '%c' : '%x';
  309. return strftime($format, $date->getTimestamp());
  310. }
  311. $formatter = new IntlDateFormatter(
  312. setlocale(LC_TIME, 0),
  313. IntlDateFormatter::LONG,
  314. $time ? IntlDateFormatter::LONG : IntlDateFormatter::NONE
  315. );
  316. return $formatter->format($date);
  317. }
  318. /**
  319. * Check if the input is an integer, no matter its real type.
  320. *
  321. * PHP is a bit messy regarding this:
  322. * - is_int returns false if the input is a string
  323. * - ctype_digit returns false if the input is an integer or negative
  324. *
  325. * @param mixed $input value
  326. *
  327. * @return bool true if the input is an integer, false otherwise
  328. */
  329. function is_integer_mixed($input)
  330. {
  331. if (is_array($input) || is_bool($input) || is_object($input)) {
  332. return false;
  333. }
  334. $input = strval($input);
  335. return ctype_digit($input) || (startsWith($input, '-') && ctype_digit(substr($input, 1)));
  336. }
  337. /**
  338. * Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
  339. *
  340. * @param string $val Size expressed in string.
  341. *
  342. * @return int Size expressed in bytes.
  343. */
  344. function return_bytes($val)
  345. {
  346. if (is_integer_mixed($val) || $val === '0' || empty($val)) {
  347. return $val;
  348. }
  349. $val = trim($val);
  350. $last = strtolower($val[strlen($val)-1]);
  351. $val = intval(substr($val, 0, -1));
  352. switch($last) {
  353. case 'g': $val *= 1024;
  354. case 'm': $val *= 1024;
  355. case 'k': $val *= 1024;
  356. }
  357. return $val;
  358. }
  359. /**
  360. * Return a human readable size from bytes.
  361. *
  362. * @param int $bytes value
  363. *
  364. * @return string Human readable size
  365. */
  366. function human_bytes($bytes)
  367. {
  368. if ($bytes === '') {
  369. return t('Setting not set');
  370. }
  371. if (! is_integer_mixed($bytes)) {
  372. return $bytes;
  373. }
  374. $bytes = intval($bytes);
  375. if ($bytes === 0) {
  376. return t('Unlimited');
  377. }
  378. $units = [t('B'), t('kiB'), t('MiB'), t('GiB')];
  379. for ($i = 0; $i < count($units) && $bytes >= 1024; ++$i) {
  380. $bytes /= 1024;
  381. }
  382. return round($bytes) . $units[$i];
  383. }
  384. /**
  385. * Try to determine max file size for uploads (POST).
  386. * Returns an integer (in bytes) or formatted depending on $format.
  387. *
  388. * @param mixed $limitPost post_max_size PHP setting
  389. * @param mixed $limitUpload upload_max_filesize PHP setting
  390. * @param bool $format Format max upload size to human readable size
  391. *
  392. * @return int|string max upload file size
  393. */
  394. function get_max_upload_size($limitPost, $limitUpload, $format = true)
  395. {
  396. $size1 = return_bytes($limitPost);
  397. $size2 = return_bytes($limitUpload);
  398. // Return the smaller of two:
  399. $maxsize = min($size1, $size2);
  400. return $format ? human_bytes($maxsize) : $maxsize;
  401. }