Utils.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. * e.g. smallHash('20111006_131924') --> yZH23w
  33. */
  34. function smallHash($text)
  35. {
  36. $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
  37. return strtr($t, '+/', '-_');
  38. }
  39. /**
  40. * Tells if a string start with a substring
  41. */
  42. function startsWith($haystack, $needle, $case=true)
  43. {
  44. if ($case) {
  45. return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
  46. }
  47. return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
  48. }
  49. /**
  50. * Tells if a string ends with a substring
  51. */
  52. function endsWith($haystack, $needle, $case=true)
  53. {
  54. if ($case) {
  55. return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
  56. }
  57. return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
  58. }
  59. /**
  60. * Same as nl2br(), but escapes < and >
  61. */
  62. function nl2br_escaped($html)
  63. {
  64. return str_replace('>', '&gt;', str_replace('<', '&lt;', nl2br($html)));
  65. }
  66. /**
  67. * htmlspecialchars wrapper
  68. */
  69. function escape($str)
  70. {
  71. return htmlspecialchars($str, ENT_COMPAT, 'UTF-8', false);
  72. }
  73. /**
  74. * Link sanitization before templating
  75. */
  76. function sanitizeLink(&$link)
  77. {
  78. $link['url'] = escape($link['url']); // useful?
  79. $link['title'] = escape($link['title']);
  80. $link['description'] = escape($link['description']);
  81. $link['tags'] = escape($link['tags']);
  82. }
  83. /**
  84. * Checks if a string represents a valid date
  85. * @param string $format The expected DateTime format of the string
  86. * @param string $string A string-formatted date
  87. *
  88. * @return bool whether the string is a valid date
  89. *
  90. * @see http://php.net/manual/en/class.datetime.php
  91. * @see http://php.net/manual/en/datetime.createfromformat.php
  92. */
  93. function checkDateFormat($format, $string)
  94. {
  95. $date = DateTime::createFromFormat($format, $string);
  96. return $date && $date->format($string) == $string;
  97. }
  98. /**
  99. * Generate a header location from HTTP_REFERER.
  100. * Make sure the referer is Shaarli itself and prevent redirection loop.
  101. *
  102. * @param string $referer - HTTP_REFERER.
  103. * @param string $host - Server HOST.
  104. * @param array $loopTerms - Contains list of term to prevent redirection loop.
  105. *
  106. * @return string $referer - final referer.
  107. */
  108. function generateLocation($referer, $host, $loopTerms = array())
  109. {
  110. $finalReferer = '?';
  111. // No referer if it contains any value in $loopCriteria.
  112. foreach ($loopTerms as $value) {
  113. if (strpos($referer, $value) !== false) {
  114. return $finalReferer;
  115. }
  116. }
  117. // Remove port from HTTP_HOST
  118. if ($pos = strpos($host, ':')) {
  119. $host = substr($host, 0, $pos);
  120. }
  121. $refererHost = parse_url($referer, PHP_URL_HOST);
  122. if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
  123. $finalReferer = $referer;
  124. }
  125. return $finalReferer;
  126. }
  127. /**
  128. * Validate session ID to prevent Full Path Disclosure.
  129. *
  130. * See #298.
  131. * The session ID's format depends on the hash algorithm set in PHP settings
  132. *
  133. * @param string $sessionId Session ID
  134. *
  135. * @return true if valid, false otherwise.
  136. *
  137. * @see http://php.net/manual/en/function.hash-algos.php
  138. * @see http://php.net/manual/en/session.configuration.php
  139. */
  140. function is_session_id_valid($sessionId)
  141. {
  142. if (empty($sessionId)) {
  143. return false;
  144. }
  145. if (!$sessionId) {
  146. return false;
  147. }
  148. if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
  149. return false;
  150. }
  151. return true;
  152. }
  153. /**
  154. * In a string, converts URLs to clickable links.
  155. *
  156. * @param string $text input string.
  157. * @param string $redirector if a redirector is set, use it to gerenate links.
  158. *
  159. * @return string returns $text with all links converted to HTML links.
  160. *
  161. * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
  162. */
  163. function text2clickable($text, $redirector)
  164. {
  165. $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si';
  166. if (empty($redirector)) {
  167. return preg_replace($regex, '<a href="$1">$1</a>', $text);
  168. }
  169. // Redirector is set, urlencode the final URL.
  170. return preg_replace_callback(
  171. $regex,
  172. function ($matches) use ($redirector) {
  173. return '<a href="' . $redirector . urlencode($matches[1]) .'">'. $matches[1] .'</a>';
  174. },
  175. $text
  176. );
  177. }
  178. /**
  179. * This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
  180. * even in the absence of <pre> (This is used in description to keep text formatting).
  181. *
  182. * @param string $text input text.
  183. *
  184. * @return string formatted text.
  185. */
  186. function space2nbsp($text)
  187. {
  188. return preg_replace('/(^| ) /m', '$1&nbsp;', $text);
  189. }
  190. /**
  191. * Format Shaarli's description
  192. * TODO: Move me to ApplicationUtils when it's ready.
  193. *
  194. * @param string $description shaare's description.
  195. * @param string $redirector if a redirector is set, use it to gerenate links.
  196. *
  197. * @return string formatted description.
  198. */
  199. function format_description($description, $redirector) {
  200. return nl2br(space2nbsp(text2clickable($description, $redirector)));
  201. }