Utils.php 5.7 KB

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