Utils.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. $attempts = array('en_US');
  201. if (isset($headerLocale)) {
  202. // (It's a bit crude, but it works very well. Preferred language is always presented first.)
  203. if (preg_match('/([a-z]{2})-?([a-z]{2})?/i', $headerLocale, $matches)) {
  204. $loc = $matches[1] . (!empty($matches[2]) ? '_' . strtoupper($matches[2]) : '');
  205. $attempts = array(
  206. $loc.'.UTF-8', $loc, str_replace('_', '-', $loc).'.UTF-8', str_replace('_', '-', $loc),
  207. $loc . '_' . strtoupper($loc).'.UTF-8', $loc . '_' . strtoupper($loc),
  208. $loc . '_' . $loc.'.UTF-8', $loc . '_' . $loc, $loc . '-' . strtoupper($loc).'.UTF-8',
  209. $loc . '-' . strtoupper($loc), $loc . '-' . $loc.'.UTF-8', $loc . '-' . $loc
  210. );
  211. }
  212. }
  213. setlocale(LC_ALL, $attempts);
  214. }
  215. /**
  216. * Generates a default API secret.
  217. *
  218. * Note that the random-ish methods used in this function are predictable,
  219. * which makes them NOT suitable for crypto.
  220. * BUT the random string is salted with the salt and hashed with the username.
  221. * It makes the generated API secret secured enough for Shaarli.
  222. *
  223. * PHP 7 provides random_int(), designed for cryptography.
  224. * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator
  225. * @param string $username Shaarli login username
  226. * @param string $salt Shaarli password hash salt
  227. *
  228. * @return string|bool Generated API secret, 12 char length.
  229. * Or false if invalid parameters are provided (which will make the API unusable).
  230. */
  231. function generate_api_secret($username, $salt)
  232. {
  233. if (empty($username) || empty($salt)) {
  234. return false;
  235. }
  236. return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12));
  237. }
  238. /**
  239. * Trim string, replace sequences of whitespaces by a single space.
  240. * PHP equivalent to `normalize-space` XSLT function.
  241. *
  242. * @param string $string Input string.
  243. *
  244. * @return mixed Normalized string.
  245. */
  246. function normalize_spaces($string)
  247. {
  248. return preg_replace('/\s{2,}/', ' ', trim($string));
  249. }