]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
Makes escape a recursive function which handle array of strings
[github/shaarli/Shaarli.git] / application / Utils.php
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 * e.g. smallHash('20111006_131924') --> yZH23w
35 */
36 function smallHash($text)
37 {
38 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
39 return strtr($t, '+/', '-_');
40 }
41
42 /**
43 * Tells if a string start with a substring
44 */
45 function startsWith($haystack, $needle, $case=true)
46 {
47 if ($case) {
48 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
49 }
50 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
51 }
52
53 /**
54 * Tells if a string ends with a substring
55 */
56 function endsWith($haystack, $needle, $case=true)
57 {
58 if ($case) {
59 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
60 }
61 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
62 }
63
64 /**
65 * Htmlspecialchars wrapper
66 * Support multidimensional array of strings.
67 *
68 * @param mixed $input Data to escape: a single string or an array of strings.
69 *
70 * @return string escaped.
71 */
72 function escape($input)
73 {
74 if (is_array($input)) {
75 $out = array();
76 foreach($input as $key => $value) {
77 $out[$key] = escape($value);
78 }
79 return $out;
80 }
81 return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false);
82 }
83
84 /**
85 * Reverse the escape function.
86 *
87 * @param string $str the string to unescape.
88 *
89 * @return string unescaped string.
90 */
91 function unescape($str)
92 {
93 return htmlspecialchars_decode($str);
94 }
95
96 /**
97 * Link sanitization before templating
98 */
99 function sanitizeLink(&$link)
100 {
101 $link['url'] = escape($link['url']); // useful?
102 $link['title'] = escape($link['title']);
103 $link['description'] = escape($link['description']);
104 $link['tags'] = escape($link['tags']);
105 }
106
107 /**
108 * Checks if a string represents a valid date
109
110 * @param string $format The expected DateTime format of the string
111 * @param string $string A string-formatted date
112 *
113 * @return bool whether the string is a valid date
114 *
115 * @see http://php.net/manual/en/class.datetime.php
116 * @see http://php.net/manual/en/datetime.createfromformat.php
117 */
118 function checkDateFormat($format, $string)
119 {
120 $date = DateTime::createFromFormat($format, $string);
121 return $date && $date->format($string) == $string;
122 }
123
124 /**
125 * Generate a header location from HTTP_REFERER.
126 * Make sure the referer is Shaarli itself and prevent redirection loop.
127 *
128 * @param string $referer - HTTP_REFERER.
129 * @param string $host - Server HOST.
130 * @param array $loopTerms - Contains list of term to prevent redirection loop.
131 *
132 * @return string $referer - final referer.
133 */
134 function generateLocation($referer, $host, $loopTerms = array())
135 {
136 $finalReferer = '?';
137
138 // No referer if it contains any value in $loopCriteria.
139 foreach ($loopTerms as $value) {
140 if (strpos($referer, $value) !== false) {
141 return $finalReferer;
142 }
143 }
144
145 // Remove port from HTTP_HOST
146 if ($pos = strpos($host, ':')) {
147 $host = substr($host, 0, $pos);
148 }
149
150 $refererHost = parse_url($referer, PHP_URL_HOST);
151 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
152 $finalReferer = $referer;
153 }
154
155 return $finalReferer;
156 }
157
158 /**
159 * Validate session ID to prevent Full Path Disclosure.
160 *
161 * See #298.
162 * The session ID's format depends on the hash algorithm set in PHP settings
163 *
164 * @param string $sessionId Session ID
165 *
166 * @return true if valid, false otherwise.
167 *
168 * @see http://php.net/manual/en/function.hash-algos.php
169 * @see http://php.net/manual/en/session.configuration.php
170 */
171 function is_session_id_valid($sessionId)
172 {
173 if (empty($sessionId)) {
174 return false;
175 }
176
177 if (!$sessionId) {
178 return false;
179 }
180
181 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
182 return false;
183 }
184
185 return true;
186 }
187
188 /**
189 * In a string, converts URLs to clickable links.
190 *
191 * @param string $text input string.
192 * @param string $redirector if a redirector is set, use it to gerenate links.
193 *
194 * @return string returns $text with all links converted to HTML links.
195 *
196 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
197 */
198 function text2clickable($text, $redirector)
199 {
200 $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si';
201
202 if (empty($redirector)) {
203 return preg_replace($regex, '<a href="$1">$1</a>', $text);
204 }
205 // Redirector is set, urlencode the final URL.
206 return preg_replace_callback(
207 $regex,
208 function ($matches) use ($redirector) {
209 return '<a href="' . $redirector . urlencode($matches[1]) .'">'. $matches[1] .'</a>';
210 },
211 $text
212 );
213 }
214
215 /**
216 * This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
217 * even in the absence of <pre> (This is used in description to keep text formatting).
218 *
219 * @param string $text input text.
220 *
221 * @return string formatted text.
222 */
223 function space2nbsp($text)
224 {
225 return preg_replace('/(^| ) /m', '$1&nbsp;', $text);
226 }
227
228 /**
229 * Format Shaarli's description
230 * TODO: Move me to ApplicationUtils when it's ready.
231 *
232 * @param string $description shaare's description.
233 * @param string $redirector if a redirector is set, use it to gerenate links.
234 *
235 * @return string formatted description.
236 */
237 function format_description($description, $redirector = false) {
238 return nl2br(space2nbsp(text2clickable($description, $redirector)));
239 }
240
241 /**
242 * Sniff browser language to set the locale automatically.
243 * Note that is may not work on your server if the corresponding locale is not installed.
244 *
245 * @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").
246 **/
247 function autoLocale($headerLocale)
248 {
249 // Default if browser does not send HTTP_ACCEPT_LANGUAGE
250 $attempts = array('en_US');
251 if (isset($headerLocale)) {
252 // (It's a bit crude, but it works very well. Preferred language is always presented first.)
253 if (preg_match('/([a-z]{2})-?([a-z]{2})?/i', $headerLocale, $matches)) {
254 $loc = $matches[1] . (!empty($matches[2]) ? '_' . strtoupper($matches[2]) : '');
255 $attempts = array(
256 $loc.'.UTF-8', $loc, str_replace('_', '-', $loc).'.UTF-8', str_replace('_', '-', $loc),
257 $loc . '_' . strtoupper($loc).'.UTF-8', $loc . '_' . strtoupper($loc),
258 $loc . '_' . $loc.'.UTF-8', $loc . '_' . $loc, $loc . '-' . strtoupper($loc).'.UTF-8',
259 $loc . '-' . strtoupper($loc), $loc . '-' . $loc.'.UTF-8', $loc . '-' . $loc
260 );
261 }
262 }
263 setlocale(LC_ALL, $attempts);
264 }