]> git.mxchange.org Git - friendica.git/blob - src/Util/Strings.php
5636a5ca024a65906dd5ea187cf33abf99672ce9
[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 escapeTags($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 Pull out all #hashtags and @person tags from $string.
284      *
285      * We also get @person@domain.com - which would make
286      * the regex quite complicated as tags can also
287      * end a sentence. So we'll run through our results
288      * and strip the period from any tags which end with one.
289      * Returns array of tags found, or empty array.
290      *
291      * @param string $string Post content
292      * 
293      * @return array List of tag and person names
294      */
295     public static function getTags($string)
296     {
297         $ret = [];
298
299         // Convert hashtag links to hashtags
300         $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
301
302         // ignore anything in a code block
303         $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
304
305         // Force line feeds at bbtags
306         $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
307
308         // ignore anything in a bbtag
309         $string = preg_replace('/\[(.*?)\]/sm', '', $string);
310
311         // Match full names against @tags including the space between first and last
312         // We will look these up afterward to see if they are full names or not recognisable.
313
314         if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
315             foreach ($matches[1] as $match) {
316                 if (strstr($match, ']')) {
317                     // we might be inside a bbcode color tag - leave it alone
318                     continue;
319                 }
320
321                 if (substr($match, -1, 1) === '.') {
322                     $ret[] = substr($match, 0, -1);
323                 } else {
324                     $ret[] = $match;
325                 }
326             }
327         }
328
329         // Otherwise pull out single word tags. These can be @nickname, @first_last
330         // and #hash tags.
331
332         if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
333             foreach ($matches[1] as $match) {
334                 if (strstr($match, ']')) {
335                     // we might be inside a bbcode color tag - leave it alone
336                     continue;
337                 }
338                 if (substr($match, -1, 1) === '.') {
339                     $match = substr($match,0,-1);
340                 }
341                 // ignore strictly numeric tags like #1
342                 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
343                     continue;
344                 }
345                 // try not to catch url fragments
346                 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
347                     continue;
348                 }
349                 $ret[] = $match;
350             }
351         }
352
353         return $ret;
354     }
355
356     /**
357      * @brief Check for a valid email string
358      *
359      * @param string $email_address Email address to be evaluated.
360      * 
361      * @return boolean  Value indicating whether or not the string is a valid email address.
362      */
363     public static function isValidEmail($email_address)
364     {
365         return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
366     }
367
368     /**
369      * @brief Normalize url
370      *
371      * @param string $url   URL to be normalized.
372      * 
373      * @return string   Normalized URL.
374      */
375     public static function normaliseLink($url)
376     {
377         $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
378         return rtrim($ret, '/');
379     }
380
381     /**
382      * @brief Normalize OpenID identity
383      * 
384      * @param string $s OpenID Identity
385      * 
386      * @return string   normalized OpenId Identity
387      */
388     function normaliseOpenID($s)
389     {
390         return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
391     }
392
393     /**
394      * @brief Compare two URLs to see if they are the same, but ignore
395      * slight but hopefully insignificant differences such as if one
396      * is https and the other isn't, or if one is www.something and
397      * the other isn't - and also ignore case differences.
398      *
399      * @param string $a first url
400      * @param string $b second url
401      * @return boolean True if the URLs match, otherwise False
402      *
403      */
404     public static function compareLink($a, $b)
405     {
406         return (strcasecmp(self::normaliseLink($a), self::normaliseLink($b)) === 0);
407     }
408 }