]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/Utils.php
move escape() and sanitizeLink() to application/Utils.php
[github/shaarli/Shaarli.git] / application / Utils.php
1 <?php
2 /**
3 * Shaarli utilities
4 */
5
6 /**
7 * Returns the small hash of a string, using RFC 4648 base64url format
8 *
9 * Small hashes:
10 * - are unique (well, as unique as crc32, at last)
11 * - are always 6 characters long.
12 * - only use the following characters: a-z A-Z 0-9 - _ @
13 * - are NOT cryptographically secure (they CAN be forged)
14 *
15 * In Shaarli, they are used as a tinyurl-like link to individual entries,
16 * e.g. smallHash('20111006_131924') --> yZH23w
17 */
18 function smallHash($text)
19 {
20 $t = rtrim(base64_encode(hash('crc32', $text, true)), '=');
21 return strtr($t, '+/', '-_');
22 }
23
24 /**
25 * Tells if a string start with a substring
26 */
27 function startsWith($haystack, $needle, $case=true)
28 {
29 if ($case) {
30 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
31 }
32 return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
33 }
34
35 /**
36 * Tells if a string ends with a substring
37 */
38 function endsWith($haystack, $needle, $case=true)
39 {
40 if ($case) {
41 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
42 }
43 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
44 }
45
46 /**
47 * Same as nl2br(), but escapes < and >
48 */
49 function nl2br_escaped($html)
50 {
51 return str_replace('>','&gt;',str_replace('<','&lt;',nl2br($html)));
52 }
53
54 /**
55 * htmlspecialchars wrapper
56 */
57 function escape($str)
58 {
59 return htmlspecialchars($str, ENT_COMPAT, 'UTF-8', false);
60 }
61
62 /**
63 * Link sanitization before templating
64 */
65 function sanitizeLink(&$link)
66 {
67 $link['url'] = escape($link['url']); // useful?
68 $link['title'] = escape($link['title']);
69 $link['description'] = escape($link['description']);
70 $link['tags'] = escape($link['tags']);
71 }
72 ?>