]> git.mxchange.org Git - friendica.git/blob - src/Util/Strings.php
Rename escapeTags to escapeHtml
[friendica.git] / src / Util / Strings.php
1 <?php
2 /**
3  * @file src/Util/Strings.php
4  */
5
6 namespace Friendica\Util;
7
8 use Friendica\Content\ContactSelector;
9 use Friendica\Core\Logger;
10
11 /**
12  * @brief This class handles string functions
13  */
14 class Strings
15 {
16     /**
17      * @brief Generates a pseudo-random string of hexadecimal characters
18      *
19      * @param int $size
20      * @return string
21      */
22     public static function getRandomHex($size = 64)
23     {
24         $byte_size = ceil($size / 2);
25
26         $bytes = random_bytes($byte_size);
27
28         $return = substr(bin2hex($bytes), 0, $size);
29
30         return $return;
31     }
32
33     /**
34      * This is our primary input filter.
35      *
36      * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
37      * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
38      * after cleansing, and angle chars with the high bit set could get through as markup.
39      *
40      * This is now disabled because it was interfering with some legitimate unicode sequences
41      * and hopefully there aren't a lot of those browsers left.
42      *
43      * Use this on any text input where angle chars are not valid or permitted
44      * They will be replaced with safer brackets. This may be filtered further
45      * if these are not allowed either.
46      *
47      * @param string $string Input string
48      * @return string Filtered string
49      */
50     public static function removeTags($string)
51     {
52         return str_replace(["<", ">"], ['[', ']'], $string);
53     }
54
55     /**
56      * @brief Use this on "body" or "content" input where angle chars shouldn't be removed,
57      * and allow them to be safely displayed.
58      * @param string $string
59      * 
60      * @return string
61      */
62     public static function escapeHtml($string)
63     {
64         return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
65     }
66
67     /**
68      * @brief Generate a string that's random, but usually pronounceable. Used to generate initial passwords
69      * 
70      * @param int $len  length
71      * 
72      * @return string
73      */
74     public static function getRandomName($len)
75     {
76         if ($len <= 0) {
77             return '';
78         }
79
80         $vowels = ['a', 'a', 'ai', 'au', 'e', 'e', 'e', 'ee', 'ea', 'i', 'ie', 'o', 'ou', 'u'];
81
82         if (mt_rand(0, 5) == 4) {
83             $vowels[] = 'y';
84         }
85
86         $cons = [
87                 'b', 'bl', 'br',
88                 'c', 'ch', 'cl', 'cr',
89                 'd', 'dr',
90                 'f', 'fl', 'fr',
91                 'g', 'gh', 'gl', 'gr',
92                 'h',
93                 'j',
94                 'k', 'kh', 'kl', 'kr',
95                 'l',
96                 'm',
97                 'n',
98                 'p', 'ph', 'pl', 'pr',
99                 'qu',
100                 'r', 'rh',
101                 's' ,'sc', 'sh', 'sm', 'sp', 'st',
102                 't', 'th', 'tr',
103                 'v',
104                 'w', 'wh',
105                 'x',
106                 'z', 'zh'
107             ];
108
109         $midcons = ['ck', 'ct', 'gn', 'ld', 'lf', 'lm', 'lt', 'mb', 'mm', 'mn', 'mp',
110                     'nd', 'ng', 'nk', 'nt', 'rn', 'rp', 'rt'];
111
112         $noend = ['bl', 'br', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gr',
113                     'kh', 'kl', 'kr', 'mn', 'pl', 'pr', 'rh', 'tr', 'qu', 'wh', 'q'];
114
115         $start = mt_rand(0, 2);
116         if ($start == 0) {
117             $table = $vowels;
118         } else {
119             $table = $cons;
120         }
121
122         $word = '';
123
124         for ($x = 0; $x < $len; $x ++) {
125             $r = mt_rand(0, count($table) - 1);
126             $word .= $table[$r];
127
128             if ($table == $vowels) {
129                 $table = array_merge($cons, $midcons);
130             } else {
131                 $table = $vowels;
132             }
133
134         }
135
136         $word = substr($word, 0, $len);
137
138         foreach ($noend as $noe) {
139             $noelen = strlen($noe);
140             if ((strlen($word) > $noelen) && (substr($word, -$noelen) == $noe)) {
141                 $word = self::getRandomName($len);
142                 break;
143             }
144         }
145
146         return $word;
147     }
148
149     /**
150      * @brief translate and format the networkname of a contact
151      *
152      * @param string $network   Networkname of the contact (e.g. dfrn, rss and so on)
153      * @param string $url       The contact url
154      * 
155      * @return string   Formatted network name
156      */
157     public static function formatNetworkName($network, $url = 0)
158     {
159         if ($network != "") {
160             if ($url != "") {
161                 $network_name = '<a href="' . $url  .'">' . ContactSelector::networkToName($network, $url) . "</a>";
162             } else {
163                 $network_name = ContactSelector::networkToName($network);
164             }
165
166             return $network_name;
167         }
168     }
169
170     /**
171      * @brief Remove intentation from a text
172      * 
173      * @param string $text  String to be transformed.
174      * @param string $chr   Optional. Indentation tag. Default tab (\t).
175      * @param int    $count Optional. Default null.
176      * 
177      * @return string       Transformed string.
178      */
179     public static function deindent($text, $chr = "[\t ]", $count = NULL)
180     {
181         $lines = explode("\n", $text);
182
183         if (is_null($count)) {
184             $m = [];
185             $k = 0;
186             while ($k < count($lines) && strlen($lines[$k]) == 0) {
187                 $k++;
188             }
189             preg_match("|^" . $chr . "*|", $lines[$k], $m);
190             $count = strlen($m[0]);
191         }
192
193         for ($k = 0; $k < count($lines); $k++) {
194             $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
195         }
196
197         return implode("\n", $lines);
198     }
199
200     /**
201      * @brief Get byte size returned in a Data Measurement (KB, MB, GB)
202      * 
203      * @param int $bytes    The number of bytes to be measured
204      * @param int $precision    Optional. Default 2.
205      * 
206      * @return string   Size with measured units.
207      */
208     public static function formatBytes($bytes, $precision = 2)
209     {
210         $units = ['B', 'KB', 'MB', 'GB', 'TB'];
211         $bytes = max($bytes, 0);
212         $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
213         $pow = min($pow, count($units) - 1);
214         $bytes /= pow(1024, $pow);
215
216         return round($bytes, $precision) . ' ' . $units[$pow];
217     }
218
219     /**
220      * @brief Protect percent characters in sprintf calls
221      * 
222      * @param string $s String to transform.
223      * 
224      * @return string   Transformed string.
225      */
226     public static function protectSprintf($s)
227     {
228         return str_replace('%', '%%', $s);
229     }
230
231     /**
232      * @brief Base64 Encode URL and translate +/ to -_ Optionally strip padding.
233      * 
234      * @param string $s                 URL to encode
235      * @param boolean $strip_padding    Optional. Default false
236      * 
237      * @return string   Encoded URL
238      */
239     public static function base64UrlEncode($s, $strip_padding = false)
240     {
241         $s = strtr(base64_encode($s), '+/', '-_');
242
243         if ($strip_padding) {
244             $s = str_replace('=', '', $s);
245         }
246
247         return $s;
248     }
249
250     /**
251      * @brief Decode Base64 Encoded URL and translate -_ to +/
252      * @param string $s URL to decode
253      * 
254      * @return string   Decoded URL
255      */
256     public static function base64UrlDecode($s)
257     {
258         if (is_array($s)) {
259             Logger::log('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
260             return $s;
261         }
262
263         /*
264         *  // Placeholder for new rev of salmon which strips base64 padding.
265         *  // PHP base64_decode handles the un-padded input without requiring this step
266         *  // Uncomment if you find you need it.
267         *
268         *       $l = strlen($s);
269         *       if (!strpos($s,'=')) {
270         *               $m = $l % 4;
271         *               if ($m == 2)
272         *                       $s .= '==';
273         *               if ($m == 3)
274         *                       $s .= '=';
275         *       }
276         *
277         */
278
279         return base64_decode(strtr($s, '-_', '+/'));
280     }
281
282     /**
283      * @brief Normalize url
284      *
285      * @param string $url   URL to be normalized.
286      * 
287      * @return string   Normalized URL.
288      */
289     public static function normaliseLink($url)
290     {
291         $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
292         return rtrim($ret, '/');
293     }
294
295     /**
296      * @brief Normalize OpenID identity
297      * 
298      * @param string $s OpenID Identity
299      * 
300      * @return string   normalized OpenId Identity
301      */
302     function normaliseOpenID($s)
303     {
304         return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
305     }
306
307     /**
308      * @brief Compare two URLs to see if they are the same, but ignore
309      * slight but hopefully insignificant differences such as if one
310      * is https and the other isn't, or if one is www.something and
311      * the other isn't - and also ignore case differences.
312      *
313      * @param string $a first url
314      * @param string $b second url
315      * @return boolean True if the URLs match, otherwise False
316      *
317      */
318     public static function compareLink($a, $b)
319     {
320         return (strcasecmp(self::normaliseLink($a), self::normaliseLink($b)) === 0);
321     }
322 }