]>
Commit | Line | Data |
---|---|---|
1 | <?php | |
2 | /** | |
3 | * Shaarli utilities | |
4 | */ | |
5 | ||
6 | /** | |
7 | * Logs a message to a text file | |
8 | * | |
9 | * The log format is compatible with fail2ban. | |
10 | * | |
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 | |
14 | */ | |
15 | function logm($logFile, $clientIp, $message) | |
16 | { | |
17 | file_put_contents( | |
18 | $logFile, | |
19 | date('Y/m/d H:i:s').' - '.$clientIp.' - '.strval($message).PHP_EOL, | |
20 | FILE_APPEND | |
21 | ); | |
22 | } | |
23 | ||
24 | /** | |
25 | * Returns the small hash of a string, using RFC 4648 base64url format | |
26 | * | |
27 | * Small hashes: | |
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) | |
32 | * | |
33 | * In Shaarli, they are used as a tinyurl-like link to individual entries, | |
34 | * built once with the combination of the date and item ID. | |
35 | * e.g. smallHash('20111006_131924' . 142) --> eaWxtQ | |
36 | * | |
37 | * @warning before v0.8.1, smallhashes were built only with the date, | |
38 | * and their value has been preserved. | |
39 | * | |
40 | * @param string $text Create a hash from this text. | |
41 | * | |
42 | * @return string generated small hash. | |
43 | */ | |
44 | function smallHash($text) | |
45 | { | |
46 | $t = rtrim(base64_encode(hash('crc32', $text, true)), '='); | |
47 | return strtr($t, '+/', '-_'); | |
48 | } | |
49 | ||
50 | /** | |
51 | * Tells if a string start with a substring | |
52 | * | |
53 | * @param string $haystack Given string. | |
54 | * @param string $needle String to search at the beginning of $haystack. | |
55 | * @param bool $case Case sensitive. | |
56 | * | |
57 | * @return bool True if $haystack starts with $needle. | |
58 | */ | |
59 | function startsWith($haystack, $needle, $case = true) | |
60 | { | |
61 | if ($case) { | |
62 | return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0); | |
63 | } | |
64 | return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0); | |
65 | } | |
66 | ||
67 | /** | |
68 | * Tells if a string ends with a substring | |
69 | * | |
70 | * @param string $haystack Given string. | |
71 | * @param string $needle String to search at the end of $haystack. | |
72 | * @param bool $case Case sensitive. | |
73 | * | |
74 | * @return bool True if $haystack ends with $needle. | |
75 | */ | |
76 | function endsWith($haystack, $needle, $case = true) | |
77 | { | |
78 | if ($case) { | |
79 | return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); | |
80 | } | |
81 | return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); | |
82 | } | |
83 | ||
84 | /** | |
85 | * Htmlspecialchars wrapper | |
86 | * Support multidimensional array of strings. | |
87 | * | |
88 | * @param mixed $input Data to escape: a single string or an array of strings. | |
89 | * | |
90 | * @return string escaped. | |
91 | */ | |
92 | function escape($input) | |
93 | { | |
94 | if (is_array($input)) { | |
95 | $out = array(); | |
96 | foreach($input as $key => $value) { | |
97 | $out[$key] = escape($value); | |
98 | } | |
99 | return $out; | |
100 | } | |
101 | return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false); | |
102 | } | |
103 | ||
104 | /** | |
105 | * Reverse the escape function. | |
106 | * | |
107 | * @param string $str the string to unescape. | |
108 | * | |
109 | * @return string unescaped string. | |
110 | */ | |
111 | function unescape($str) | |
112 | { | |
113 | return htmlspecialchars_decode($str); | |
114 | } | |
115 | ||
116 | /** | |
117 | * Sanitize link before rendering. | |
118 | * | |
119 | * @param array $link Link to escape. | |
120 | */ | |
121 | function sanitizeLink(&$link) | |
122 | { | |
123 | $link['url'] = escape($link['url']); // useful? | |
124 | $link['title'] = escape($link['title']); | |
125 | $link['description'] = escape($link['description']); | |
126 | $link['tags'] = escape($link['tags']); | |
127 | } | |
128 | ||
129 | /** | |
130 | * Checks if a string represents a valid date | |
131 | ||
132 | * @param string $format The expected DateTime format of the string | |
133 | * @param string $string A string-formatted date | |
134 | * | |
135 | * @return bool whether the string is a valid date | |
136 | * | |
137 | * @see http://php.net/manual/en/class.datetime.php | |
138 | * @see http://php.net/manual/en/datetime.createfromformat.php | |
139 | */ | |
140 | function checkDateFormat($format, $string) | |
141 | { | |
142 | $date = DateTime::createFromFormat($format, $string); | |
143 | return $date && $date->format($string) == $string; | |
144 | } | |
145 | ||
146 | /** | |
147 | * Generate a header location from HTTP_REFERER. | |
148 | * Make sure the referer is Shaarli itself and prevent redirection loop. | |
149 | * | |
150 | * @param string $referer - HTTP_REFERER. | |
151 | * @param string $host - Server HOST. | |
152 | * @param array $loopTerms - Contains list of term to prevent redirection loop. | |
153 | * | |
154 | * @return string $referer - final referer. | |
155 | */ | |
156 | function generateLocation($referer, $host, $loopTerms = array()) | |
157 | { | |
158 | $finalReferer = '?'; | |
159 | ||
160 | // No referer if it contains any value in $loopCriteria. | |
161 | foreach ($loopTerms as $value) { | |
162 | if (strpos($referer, $value) !== false) { | |
163 | return $finalReferer; | |
164 | } | |
165 | } | |
166 | ||
167 | // Remove port from HTTP_HOST | |
168 | if ($pos = strpos($host, ':')) { | |
169 | $host = substr($host, 0, $pos); | |
170 | } | |
171 | ||
172 | $refererHost = parse_url($referer, PHP_URL_HOST); | |
173 | if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) { | |
174 | $finalReferer = $referer; | |
175 | } | |
176 | ||
177 | return $finalReferer; | |
178 | } | |
179 | ||
180 | /** | |
181 | * Validate session ID to prevent Full Path Disclosure. | |
182 | * | |
183 | * See #298. | |
184 | * The session ID's format depends on the hash algorithm set in PHP settings | |
185 | * | |
186 | * @param string $sessionId Session ID | |
187 | * | |
188 | * @return true if valid, false otherwise. | |
189 | * | |
190 | * @see http://php.net/manual/en/function.hash-algos.php | |
191 | * @see http://php.net/manual/en/session.configuration.php | |
192 | */ | |
193 | function is_session_id_valid($sessionId) | |
194 | { | |
195 | if (empty($sessionId)) { | |
196 | return false; | |
197 | } | |
198 | ||
199 | if (!$sessionId) { | |
200 | return false; | |
201 | } | |
202 | ||
203 | if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) { | |
204 | return false; | |
205 | } | |
206 | ||
207 | return true; | |
208 | } | |
209 | ||
210 | /** | |
211 | * Sniff browser language to set the locale automatically. | |
212 | * Note that is may not work on your server if the corresponding locale is not installed. | |
213 | * | |
214 | * @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"). | |
215 | **/ | |
216 | function autoLocale($headerLocale) | |
217 | { | |
218 | // Default if browser does not send HTTP_ACCEPT_LANGUAGE | |
219 | $attempts = array('en_US'); | |
220 | if (isset($headerLocale)) { | |
221 | // (It's a bit crude, but it works very well. Preferred language is always presented first.) | |
222 | if (preg_match('/([a-z]{2})-?([a-z]{2})?/i', $headerLocale, $matches)) { | |
223 | $loc = $matches[1] . (!empty($matches[2]) ? '_' . strtoupper($matches[2]) : ''); | |
224 | $attempts = array( | |
225 | $loc.'.UTF-8', $loc, str_replace('_', '-', $loc).'.UTF-8', str_replace('_', '-', $loc), | |
226 | $loc . '_' . strtoupper($loc).'.UTF-8', $loc . '_' . strtoupper($loc), | |
227 | $loc . '_' . $loc.'.UTF-8', $loc . '_' . $loc, $loc . '-' . strtoupper($loc).'.UTF-8', | |
228 | $loc . '-' . strtoupper($loc), $loc . '-' . $loc.'.UTF-8', $loc . '-' . $loc | |
229 | ); | |
230 | } | |
231 | } | |
232 | setlocale(LC_ALL, $attempts); | |
233 | } | |
234 | ||
235 | /** | |
236 | * Generates a default API secret. | |
237 | * | |
238 | * Note that the random-ish methods used in this function are predictable, | |
239 | * which makes them NOT suitable for crypto. | |
240 | * BUT the random string is salted with the salt and hashed with the username. | |
241 | * It makes the generated API secret secured enough for Shaarli. | |
242 | * | |
243 | * PHP 7 provides random_int(), designed for cryptography. | |
244 | * More info: http://stackoverflow.com/questions/4356289/php-random-string-generator | |
245 | ||
246 | * @param string $username Shaarli login username | |
247 | * @param string $salt Shaarli password hash salt | |
248 | * | |
249 | * @return string|bool Generated API secret, 12 char length. | |
250 | * Or false if invalid parameters are provided (which will make the API unusable). | |
251 | */ | |
252 | function generate_api_secret($username, $salt) | |
253 | { | |
254 | if (empty($username) || empty($salt)) { | |
255 | return false; | |
256 | } | |
257 | ||
258 | return str_shuffle(substr(hash_hmac('sha512', uniqid($salt), $username), 10, 12)); | |
259 | } |