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