]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/Utils.php
Minor code cleanup: PHPDoc, spelling, unused variables, etc.
[github/shaarli/Shaarli.git] / application / Utils.php
CommitLineData
ca74886f
V
1<?php
2/**
3 * Shaarli utilities
4 */
5
1abe6555
V
6/**
7 * Logs a message to a text file
8 *
478ce8af
V
9 * The log format is compatible with fail2ban.
10 *
1abe6555
V
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 */
15function logm($logFile, $clientIp, $message)
16{
478ce8af
V
17 file_put_contents(
18 $logFile,
aa7f7b3e 19 date('Y/m/d H:i:s').' - '.$clientIp.' - '.strval($message).PHP_EOL,
478ce8af
V
20 FILE_APPEND
21 );
1abe6555
V
22}
23
ca74886f
V
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
7af9a418
A
35 *
36 * @param string $text Create a hash from this text.
37 *
38 * @return string generated small hash.
ca74886f
V
39 */
40function 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
5046bcb6
A
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.
ca74886f 54 */
5046bcb6 55function startsWith($haystack, $needle, $case = true)
ca74886f
V
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
5046bcb6
A
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.
ca74886f 71 */
5046bcb6 72function endsWith($haystack, $needle, $case = true)
ca74886f
V
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}
64bc92e3 79
64bc92e3 80/**
2925687e 81 * Htmlspecialchars wrapper
ee88a4bc 82 * Support multidimensional array of strings.
2925687e 83 *
ee88a4bc 84 * @param mixed $input Data to escape: a single string or an array of strings.
2925687e
A
85 *
86 * @return string escaped.
64bc92e3 87 */
ee88a4bc 88function escape($input)
64bc92e3 89{
ee88a4bc
A
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);
64bc92e3 98}
99
2925687e
A
100/**
101 * Reverse the escape function.
102 *
103 * @param string $str the string to unescape.
104 *
105 * @return string unescaped string.
106 */
107function unescape($str)
108{
109 return htmlspecialchars_decode($str);
110}
111
64bc92e3 112/**
7af9a418
A
113 * Sanitize link before rendering.
114 *
115 * @param array $link Link to escape.
64bc92e3 116 */
117function 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}
9186ab95
V
124
125/**
126 * Checks if a string represents a valid date
822bffce
A
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
9186ab95 132 *
822bffce
A
133 * @see http://php.net/manual/en/class.datetime.php
134 * @see http://php.net/manual/en/datetime.createfromformat.php
9186ab95
V
135 */
136function checkDateFormat($format, $string)
137{
138 $date = DateTime::createFromFormat($format, $string);
139 return $date && $date->format($string) == $string;
140}
775803a0
A
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 */
152function generateLocation($referer, $host, $loopTerms = array())
153{
d01c2342 154 $finalReferer = '?';
775803a0
A
155
156 // No referer if it contains any value in $loopCriteria.
157 foreach ($loopTerms as $value) {
158 if (strpos($referer, $value) !== false) {
d01c2342 159 return $finalReferer;
775803a0
A
160 }
161 }
162
163 // Remove port from HTTP_HOST
164 if ($pos = strpos($host, ':')) {
165 $host = substr($host, 0, $pos);
166 }
167
d01c2342
A
168 $refererHost = parse_url($referer, PHP_URL_HOST);
169 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
170 $finalReferer = $referer;
775803a0
A
171 }
172
d01c2342 173 return $finalReferer;
775803a0 174}
d1e2f8e5 175
06b6660a
A
176/**
177 * Validate session ID to prevent Full Path Disclosure.
68bc2135 178 *
06b6660a 179 * See #298.
68bc2135 180 * The session ID's format depends on the hash algorithm set in PHP settings
06b6660a
A
181 *
182 * @param string $sessionId Session ID
183 *
184 * @return true if valid, false otherwise.
68bc2135
V
185 *
186 * @see http://php.net/manual/en/function.hash-algos.php
187 * @see http://php.net/manual/en/session.configuration.php
06b6660a
A
188 */
189function is_session_id_valid($sessionId)
190{
191 if (empty($sessionId)) {
192 return false;
193 }
194
195 if (!$sessionId) {
196 return false;
197 }
198
68bc2135 199 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
06b6660a
A
200 return false;
201 }
202
203 return true;
204}
90e5bd65 205
7b63e4ca
A
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 **/
212function 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);
9ccca401 229}