]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
Logging: move logm() from index.php to application/Utils.php
[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 * @param string $logFile where to write the logs
10 * @param string $clientIp the client's remote IPv4/IPv6 address
11 * @param string $message the message to log
12 */
13 function logm($logFile, $clientIp, $message)
14 {
15 $line = strval(date('Y/m/d_H:i:s')).' - '.$clientIp.' - '.strval($message).'\n';
16 file_put_contents($logFile, $line, FILE_APPEND);
17 }
18
19 /**
20 * Returns the small hash of a string, using RFC 4648 base64url format
21 *
22 * Small hashes:
23 * - are unique (well, as unique as crc32, at last)
24 * - are always 6 characters long.
25 * - only use the following characters: a-z A-Z 0-9 - _ @
26 * - are NOT cryptographically secure (they CAN be forged)
27 *
28 * In Shaarli, they are used as a tinyurl-like link to individual entries,
29 * e.g. smallHash('20111006_131924') --> yZH23w
30 */
31 function smallHash($text)
32 {
33 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
34 return strtr($t, '+/', '-_');
35 }
36
37 /**
38 * Tells if a string start with a substring
39 */
40 function startsWith($haystack, $needle, $case=true)
41 {
42 if ($case) {
43 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
44 }
45 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
46 }
47
48 /**
49 * Tells if a string ends with a substring
50 */
51 function endsWith($haystack, $needle, $case=true)
52 {
53 if ($case) {
54 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
55 }
56 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
57 }
58
59 /**
60 * Same as nl2br(), but escapes < and >
61 */
62 function nl2br_escaped($html)
63 {
64 return str_replace('>', '&gt;', str_replace('<', '&lt;', nl2br($html)));
65 }
66
67 /**
68 * htmlspecialchars wrapper
69 */
70 function escape($str)
71 {
72 return htmlspecialchars($str, ENT_COMPAT, 'UTF-8', false);
73 }
74
75 /**
76 * Link sanitization before templating
77 */
78 function sanitizeLink(&$link)
79 {
80 $link['url'] = escape($link['url']); // useful?
81 $link['title'] = escape($link['title']);
82 $link['description'] = escape($link['description']);
83 $link['tags'] = escape($link['tags']);
84 }
85
86 /**
87 * Checks if a string represents a valid date
88
89 * @param string $format The expected DateTime format of the string
90 * @param string $string A string-formatted date
91 *
92 * @return bool whether the string is a valid date
93 *
94 * @see http://php.net/manual/en/class.datetime.php
95 * @see http://php.net/manual/en/datetime.createfromformat.php
96 */
97 function checkDateFormat($format, $string)
98 {
99 $date = DateTime::createFromFormat($format, $string);
100 return $date && $date->format($string) == $string;
101 }
102
103 /**
104 * Generate a header location from HTTP_REFERER.
105 * Make sure the referer is Shaarli itself and prevent redirection loop.
106 *
107 * @param string $referer - HTTP_REFERER.
108 * @param string $host - Server HOST.
109 * @param array $loopTerms - Contains list of term to prevent redirection loop.
110 *
111 * @return string $referer - final referer.
112 */
113 function generateLocation($referer, $host, $loopTerms = array())
114 {
115 $finalReferer = '?';
116
117 // No referer if it contains any value in $loopCriteria.
118 foreach ($loopTerms as $value) {
119 if (strpos($referer, $value) !== false) {
120 return $finalReferer;
121 }
122 }
123
124 // Remove port from HTTP_HOST
125 if ($pos = strpos($host, ':')) {
126 $host = substr($host, 0, $pos);
127 }
128
129 $refererHost = parse_url($referer, PHP_URL_HOST);
130 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
131 $finalReferer = $referer;
132 }
133
134 return $finalReferer;
135 }
136
137 /**
138 * Validate session ID to prevent Full Path Disclosure.
139 *
140 * See #298.
141 * The session ID's format depends on the hash algorithm set in PHP settings
142 *
143 * @param string $sessionId Session ID
144 *
145 * @return true if valid, false otherwise.
146 *
147 * @see http://php.net/manual/en/function.hash-algos.php
148 * @see http://php.net/manual/en/session.configuration.php
149 */
150 function is_session_id_valid($sessionId)
151 {
152 if (empty($sessionId)) {
153 return false;
154 }
155
156 if (!$sessionId) {
157 return false;
158 }
159
160 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
161 return false;
162 }
163
164 return true;
165 }
166
167 /**
168 * In a string, converts URLs to clickable links.
169 *
170 * @param string $text input string.
171 * @param string $redirector if a redirector is set, use it to gerenate links.
172 *
173 * @return string returns $text with all links converted to HTML links.
174 *
175 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
176 */
177 function text2clickable($text, $redirector)
178 {
179 $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si';
180
181 if (empty($redirector)) {
182 return preg_replace($regex, '<a href="$1">$1</a>', $text);
183 }
184 // Redirector is set, urlencode the final URL.
185 return preg_replace_callback(
186 $regex,
187 function ($matches) use ($redirector) {
188 return '<a href="' . $redirector . urlencode($matches[1]) .'">'. $matches[1] .'</a>';
189 },
190 $text
191 );
192 }
193
194 /**
195 * This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
196 * even in the absence of <pre> (This is used in description to keep text formatting).
197 *
198 * @param string $text input text.
199 *
200 * @return string formatted text.
201 */
202 function space2nbsp($text)
203 {
204 return preg_replace('/(^| ) /m', '$1&nbsp;', $text);
205 }
206
207 /**
208 * Format Shaarli's description
209 * TODO: Move me to ApplicationUtils when it's ready.
210 *
211 * @param string $description shaare's description.
212 * @param string $redirector if a redirector is set, use it to gerenate links.
213 *
214 * @return string formatted description.
215 */
216 function format_description($description, $redirector) {
217 return nl2br(space2nbsp(text2clickable($description, $redirector)));
218 }