]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/Utils.php
Implemented searching for a phrase in double-quotes or all words in no particular...
[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
35 */
36function 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 */
45function 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 */
56function 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}
64bc92e3 63
64/**
65 * Same as nl2br(), but escapes < and >
66 */
67function nl2br_escaped($html)
68{
d1e2f8e5 69 return str_replace('>', '&gt;', str_replace('<', '&lt;', nl2br($html)));
64bc92e3 70}
71
72/**
73 * htmlspecialchars wrapper
74 */
75function escape($str)
76{
77 return htmlspecialchars($str, ENT_COMPAT, 'UTF-8', false);
78}
79
80/**
81 * Link sanitization before templating
82 */
83function sanitizeLink(&$link)
84{
85 $link['url'] = escape($link['url']); // useful?
86 $link['title'] = escape($link['title']);
87 $link['description'] = escape($link['description']);
88 $link['tags'] = escape($link['tags']);
89}
9186ab95
V
90
91/**
92 * Checks if a string represents a valid date
822bffce
A
93
94 * @param string $format The expected DateTime format of the string
95 * @param string $string A string-formatted date
96 *
97 * @return bool whether the string is a valid date
9186ab95 98 *
822bffce
A
99 * @see http://php.net/manual/en/class.datetime.php
100 * @see http://php.net/manual/en/datetime.createfromformat.php
9186ab95
V
101 */
102function checkDateFormat($format, $string)
103{
104 $date = DateTime::createFromFormat($format, $string);
105 return $date && $date->format($string) == $string;
106}
775803a0
A
107
108/**
109 * Generate a header location from HTTP_REFERER.
110 * Make sure the referer is Shaarli itself and prevent redirection loop.
111 *
112 * @param string $referer - HTTP_REFERER.
113 * @param string $host - Server HOST.
114 * @param array $loopTerms - Contains list of term to prevent redirection loop.
115 *
116 * @return string $referer - final referer.
117 */
118function generateLocation($referer, $host, $loopTerms = array())
119{
d01c2342 120 $finalReferer = '?';
775803a0
A
121
122 // No referer if it contains any value in $loopCriteria.
123 foreach ($loopTerms as $value) {
124 if (strpos($referer, $value) !== false) {
d01c2342 125 return $finalReferer;
775803a0
A
126 }
127 }
128
129 // Remove port from HTTP_HOST
130 if ($pos = strpos($host, ':')) {
131 $host = substr($host, 0, $pos);
132 }
133
d01c2342
A
134 $refererHost = parse_url($referer, PHP_URL_HOST);
135 if (!empty($referer) && (strpos($refererHost, $host) !== false || startsWith('?', $refererHost))) {
136 $finalReferer = $referer;
775803a0
A
137 }
138
d01c2342 139 return $finalReferer;
775803a0 140}
d1e2f8e5 141
06b6660a
A
142/**
143 * Validate session ID to prevent Full Path Disclosure.
68bc2135 144 *
06b6660a 145 * See #298.
68bc2135 146 * The session ID's format depends on the hash algorithm set in PHP settings
06b6660a
A
147 *
148 * @param string $sessionId Session ID
149 *
150 * @return true if valid, false otherwise.
68bc2135
V
151 *
152 * @see http://php.net/manual/en/function.hash-algos.php
153 * @see http://php.net/manual/en/session.configuration.php
06b6660a
A
154 */
155function is_session_id_valid($sessionId)
156{
157 if (empty($sessionId)) {
158 return false;
159 }
160
161 if (!$sessionId) {
162 return false;
163 }
164
68bc2135 165 if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
06b6660a
A
166 return false;
167 }
168
169 return true;
170}
90e5bd65
A
171
172/**
173 * In a string, converts URLs to clickable links.
174 *
175 * @param string $text input string.
176 * @param string $redirector if a redirector is set, use it to gerenate links.
177 *
178 * @return string returns $text with all links converted to HTML links.
179 *
180 * @see Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
181 */
182function text2clickable($text, $redirector)
183{
184 $regex = '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si';
185
186 if (empty($redirector)) {
187 return preg_replace($regex, '<a href="$1">$1</a>', $text);
188 }
189 // Redirector is set, urlencode the final URL.
190 return preg_replace_callback(
191 $regex,
192 function ($matches) use ($redirector) {
193 return '<a href="' . $redirector . urlencode($matches[1]) .'">'. $matches[1] .'</a>';
194 },
195 $text
196 );
197}
198
199/**
200 * This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
201 * even in the absence of <pre> (This is used in description to keep text formatting).
202 *
203 * @param string $text input text.
204 *
205 * @return string formatted text.
206 */
207function space2nbsp($text)
208{
209 return preg_replace('/(^| ) /m', '$1&nbsp;', $text);
210}
211
212/**
213 * Format Shaarli's description
214 * TODO: Move me to ApplicationUtils when it's ready.
215 *
216 * @param string $description shaare's description.
217 * @param string $redirector if a redirector is set, use it to gerenate links.
218 *
219 * @return string formatted description.
220 */
221function format_description($description, $redirector) {
222 return nl2br(space2nbsp(text2clickable($description, $redirector)));
223}