]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
Minor code cleanup: PHPDoc, spelling, unused variables, etc.
[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 * @param string $text Create a hash from this text.
37 *
38 * @return string generated small hash.
39 */
40 function smallHash($text)
41 {
42 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
43 return strtr($t, '+/', '-_');
44 }
45
46 /**
47 * Tells if a string start with a substring
48 *
49 * @param string $haystack Given string.
50 * @param string $needle String to search at the beginning of $haystack.
51 * @param bool $case Case sensitive.
52 *
53 * @return bool True if $haystack starts with $needle.
54 */
55 function startsWith($haystack, $needle, $case = true)
56 {
57 if ($case) {
58 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
59 }
60 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
61 }
62
63 /**
64 * Tells if a string ends with a substring
65 *
66 * @param string $haystack Given string.
67 * @param string $needle String to search at the end of $haystack.
68 * @param bool $case Case sensitive.
69 *
70 * @return bool True if $haystack ends with $needle.
71 */
72 function endsWith($haystack, $needle, $case = true)
73 {
74 if ($case) {
75 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
76 }
77 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
78 }
79
80 /**
81 * Htmlspecialchars wrapper
82 * Support multidimensional array of strings.
83 *
84 * @param mixed $input Data to escape: a single string or an array of strings.
85 *
86 * @return string escaped.
87 */
88 function escape($input)
89 {
90 if (is_array($input)) {
91 $out = array();
92 foreach($input as $key => $value) {
93 $out[$key] = escape($value);
94 }
95 return $out;
96 }
97 return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false);
98 }
99
100 /**
101 * Reverse the escape function.
102 *
103 * @param string $str the string to unescape.
104 *
105 * @return string unescaped string.
106 */
107 function unescape($str)
108 {
109 return htmlspecialchars_decode($str);
110 }
111
112 /**
113 * Sanitize link before rendering.
114 *
115 * @param array $link Link to escape.
116 */
117 function sanitizeLink(&$link)
118 {
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']);
123 }
124
125 /**
126 * Checks if a string represents a valid date
127
128 * @param string $format The expected DateTime format of the string
129 * @param string $string A string-formatted date
130 *
131 * @return bool whether the string is a valid date
132 *
133 * @see http://php.net/manual/en/class.datetime.php
134 * @see http://php.net/manual/en/datetime.createfromformat.php
135 */
136 function checkDateFormat($format, $string)
137 {
138 $date = DateTime::createFromFormat($format, $string);
139 return $date && $date->format($string) == $string;
140 }
141
142 /**
143 * Generate a header location from HTTP_REFERER.
144 * Make sure the referer is Shaarli itself and prevent redirection loop.
145 *
146 * @param string $referer - HTTP_REFERER.
147 * @param string $host - Server HOST.
148 * @param array $loopTerms - Contains list of term to prevent redirection loop.
149 *
150 * @return string $referer - final referer.
151 */
152 function generateLocation($referer, $host, $loopTerms = array())
153 {
154 $finalReferer = '?';
155
156 // No referer if it contains any value in $loopCriteria.
157 foreach ($loopTerms as $value) {
158 if (strpos($referer, $value) !== false) {
159 return $finalReferer;
160 }
161 }
162
163 // Remove port from HTTP_HOST
164 if ($pos = strpos($host, ':')) {
165 $host = substr($host, 0, $pos);
166 }
167
168 $refererHost = parse_url($referer, PHP_URL_HOST);
169 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
170 $finalReferer = $referer;
171 }
172
173 return $finalReferer;
174 }
175
176 /**
177 * Validate session ID to prevent Full Path Disclosure.
178 *
179 * See #298.
180 * The session ID's format depends on the hash algorithm set in PHP settings
181 *
182 * @param string $sessionId Session ID
183 *
184 * @return true if valid, false otherwise.
185 *
186 * @see http://php.net/manual/en/function.hash-algos.php
187 * @see http://php.net/manual/en/session.configuration.php
188 */
189 function is_session_id_valid($sessionId)
190 {
191 if (empty($sessionId)) {
192 return false;
193 }
194
195 if (!$sessionId) {
196 return false;
197 }
198
199 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
200 return false;
201 }
202
203 return true;
204 }
205
206 /**
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.
209 *
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").
211 **/
212 function autoLocale($headerLocale)
213 {
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]) : '');
220 $attempts = array(
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
225 );
226 }
227 }
228 setlocale(LC_ALL, $attempts);
229 }