]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
7 * Logs a message to a text file
9 * The log format is compatible with fail2ban.
11 * @param string $logFile where to write the logs
12 * @param string $clientIp the client's remote IPv4/IPv6 address
13 * @param string $message the message to log
15 function logm($logFile, $clientIp, $message)
19 date('Y/m/d H:i:s').' - '.$clientIp.' - '.strval($message).PHP_EOL
,
25 * Returns the small hash of a string, using RFC 4648 base64url format
28 * - are unique (well, as unique as crc32, at last)
29 * - are always 6 characters long.
30 * - only use the following characters: a-z A-Z 0-9 - _ @
31 * - are NOT cryptographically secure (they CAN be forged)
33 * In Shaarli, they are used as a tinyurl-like link to individual entries,
34 * e.g. smallHash('20111006_131924') --> yZH23w
36 * @param string $text Create a hash from this text.
38 * @return string generated small hash.
40 function smallHash($text)
42 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
43 return strtr($t, '+/', '-_');
47 * Tells if a string start with a substring
49 * @param string $haystack Given string.
50 * @param string $needle String to search at the beginning of $haystack.
51 * @param bool $case Case sensitive.
53 * @return bool True if $haystack starts with $needle.
55 function startsWith($haystack, $needle, $case = true)
58 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
60 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
64 * Tells if a string ends with a substring
66 * @param string $haystack Given string.
67 * @param string $needle String to search at the end of $haystack.
68 * @param bool $case Case sensitive.
70 * @return bool True if $haystack ends with $needle.
72 function endsWith($haystack, $needle, $case = true)
75 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
77 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
81 * Htmlspecialchars wrapper
82 * Support multidimensional array of strings.
84 * @param mixed $input Data to escape: a single string or an array of strings.
86 * @return string escaped.
88 function escape($input)
90 if (is_array($input)) {
92 foreach($input as $key => $value) {
93 $out[$key] = escape($value);
97 return htmlspecialchars($input, ENT_COMPAT
, 'UTF-8', false);
101 * Reverse the escape function.
103 * @param string $str the string to unescape.
105 * @return string unescaped string.
107 function unescape($str)
109 return htmlspecialchars_decode($str);
113 * Sanitize link before rendering.
115 * @param array $link Link to escape.
117 function sanitizeLink(&$link)
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']);
126 * Checks if a string represents a valid date
128 * @param string $format The expected DateTime format of the string
129 * @param string $string A string-formatted date
131 * @return bool whether the string is a valid date
133 * @see http://php.net/manual/en/class.datetime.php
134 * @see http://php.net/manual/en/datetime.createfromformat.php
136 function checkDateFormat($format, $string)
138 $date = DateTime
::createFromFormat($format, $string);
139 return $date && $date->format($string) == $string;
143 * Generate a header location from HTTP_REFERER.
144 * Make sure the referer is Shaarli itself and prevent redirection loop.
146 * @param string $referer - HTTP_REFERER.
147 * @param string $host - Server HOST.
148 * @param array $loopTerms - Contains list of term to prevent redirection loop.
150 * @return string $referer - final referer.
152 function generateLocation($referer, $host, $loopTerms = array())
156 // No referer if it contains any value in $loopCriteria.
157 foreach ($loopTerms as $value) {
158 if (strpos($referer, $value) !== false) {
159 return $finalReferer;
163 // Remove port from HTTP_HOST
164 if ($pos = strpos($host, ':')) {
165 $host = substr($host, 0, $pos);
168 $refererHost = parse_url($referer, PHP_URL_HOST
);
169 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
170 $finalReferer = $referer;
173 return $finalReferer;
177 * Validate session ID to prevent Full Path Disclosure.
180 * The session ID's format depends on the hash algorithm set in PHP settings
182 * @param string $sessionId Session ID
184 * @return true if valid, false otherwise.
186 * @see http://php.net/manual/en/function.hash-algos.php
187 * @see http://php.net/manual/en/session.configuration.php
189 function is_session_id_valid($sessionId)
191 if (empty($sessionId)) {
199 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
207 * Sniff browser language to set the locale automatically.
208 * Note that is may not work on your server if the corresponding locale is not installed.
210 * @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").
212 function autoLocale($headerLocale)
214 // Default if browser does not send HTTP_ACCEPT_LANGUAGE
215 $attempts = array('en_US');
216 if (isset($headerLocale)) {
217 // (It's a bit crude, but it works very well. Preferred language is always presented first.)
218 if (preg_match('/([a-z]{2})-?([a-z]{2})?/i', $headerLocale, $matches)) {
219 $loc = $matches[1] . (!empty($matches[2]) ? '_' . strtoupper($matches[2]) : '');
221 $loc.'.UTF-8', $loc, str_replace('_', '-', $loc).'.UTF-8', str_replace('_', '-', $loc),
222 $loc . '_' . strtoupper($loc).'.UTF-8', $loc . '_' . strtoupper($loc),
223 $loc . '_' . $loc.'.UTF-8', $loc . '_' . $loc, $loc . '-' . strtoupper($loc).'.UTF-8',
224 $loc . '-' . strtoupper($loc), $loc . '-' . $loc.'.UTF-8', $loc . '-' . $loc
228 setlocale(LC_ALL
, $attempts);