]> git.mxchange.org Git - friendica.git/blob - src/Util/Strings.php
Split text.php to Strings class
[friendica.git] / src / Util / Strings.php
1 <?php
2 /**
3  * @file src/Util/Strings.php
4  */
5
6 namespace Friendica\Util;
7
8 /**
9  * @brief This class handles string functions
10  */
11 class Strings
12 {
13     /**
14      * @brief Generates a pseudo-random string of hexadecimal characters
15      *
16      * @param int $size
17      * @return string
18      */
19     public static function getRandomHex($size = 64) // random_string()
20     {
21         $byte_size = ceil($size / 2);
22
23         $bytes = random_bytes($byte_size);
24
25         $return = substr(bin2hex($bytes), 0, $size);
26
27         return $return;
28     }
29
30     /**
31      * This is our primary input filter.
32      *
33      * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
34      * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
35      * after cleansing, and angle chars with the high bit set could get through as markup.
36      *
37      * This is now disabled because it was interfering with some legitimate unicode sequences
38      * and hopefully there aren't a lot of those browsers left.
39      *
40      * Use this on any text input where angle chars are not valid or permitted
41      * They will be replaced with safer brackets. This may be filtered further
42      * if these are not allowed either.
43      *
44      * @param string $string Input string
45      * @return string Filtered string
46      */
47     public static function removeTags($string) // notags()
48     {
49         return str_replace(["<", ">"], ['[', ']'], $string);
50     }
51
52     /**
53      * @brief Use this on "body" or "content" input where angle chars shouldn't be removed,
54      * and allow them to be safely displayed.
55      * @param string $string
56      * 
57      * @return string
58      */
59     public static function escapeTags($string) // escape_tags()
60     {
61         return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
62     }
63
64     /**
65      * @brief Generate a string that's random, but usually pronounceable. Used to generate initial passwords
66      * 
67      * @param int $len  length
68      * 
69      * @return string
70      */
71     public static function getRandomName($len) // autoname()
72     {
73         if ($len <= 0) {
74             return '';
75         }
76
77         $vowels = ['a', 'a', 'ai', 'au', 'e', 'e', 'e', 'ee', 'ea', 'i', 'ie', 'o', 'ou', 'u'];
78
79         if (mt_rand(0, 5) == 4) {
80             $vowels[] = 'y';
81         }
82
83         $cons = [
84                 'b', 'bl', 'br',
85                 'c', 'ch', 'cl', 'cr',
86                 'd', 'dr',
87                 'f', 'fl', 'fr',
88                 'g', 'gh', 'gl', 'gr',
89                 'h',
90                 'j',
91                 'k', 'kh', 'kl', 'kr',
92                 'l',
93                 'm',
94                 'n',
95                 'p', 'ph', 'pl', 'pr',
96                 'qu',
97                 'r', 'rh',
98                 's' ,'sc', 'sh', 'sm', 'sp', 'st',
99                 't', 'th', 'tr',
100                 'v',
101                 'w', 'wh',
102                 'x',
103                 'z', 'zh'
104             ];
105
106         $midcons = ['ck', 'ct', 'gn', 'ld', 'lf', 'lm', 'lt', 'mb', 'mm', 'mn', 'mp',
107                     'nd', 'ng', 'nk', 'nt', 'rn', 'rp', 'rt'];
108
109         $noend = ['bl', 'br', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gr',
110                     'kh', 'kl', 'kr', 'mn', 'pl', 'pr', 'rh', 'tr', 'qu', 'wh', 'q'];
111
112         $start = mt_rand(0, 2);
113         if ($start == 0) {
114             $table = $vowels;
115         } else {
116             $table = $cons;
117         }
118
119         $word = '';
120
121         for ($x = 0; $x < $len; $x ++) {
122             $r = mt_rand(0, count($table) - 1);
123             $word .= $table[$r];
124
125             if ($table == $vowels) {
126                 $table = array_merge($cons, $midcons);
127             } else {
128                 $table = $vowels;
129             }
130
131         }
132
133         $word = substr($word, 0, $len);
134
135         foreach ($noend as $noe) {
136             $noelen = strlen($noe);
137             if ((strlen($word) > $noelen) && (substr($word, -$noelen) == $noe)) {
138                 $word = self::getRandomName($len);
139                 break;
140             }
141         }
142
143         return $word;
144     }
145
146     /**
147      * @brief translate and format the networkname of a contact
148      *
149      * @param string $network   Networkname of the contact (e.g. dfrn, rss and so on)
150      * @param string $url       The contact url
151      * 
152      * @return string   Formatted network name
153      */
154     public static function formatNetworkName($network, $url = 0) // format_network_name()
155     {
156         if ($network != "") {
157             if ($url != "") {
158                 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
159             } else {
160                 $network_name = ContactSelector::networkToName($network);
161             }
162
163             return $network_name;
164         }
165     }
166
167     /**
168      * @brief Remove intentation from a text
169      * 
170      * @param string $text  String to be transformed.
171      * @param string $chr   Optional. Indentation tag. Default tab (\t).
172      * @param int    $count Optional. Default null.
173      * 
174      * @return string       Transformed string.
175      */
176     public static function deindent($text, $chr = "[\t ]", $count = NULL)
177     {
178         $lines = explode("\n", $text);
179
180         if (is_null($count)) {
181             $m = [];
182             $k = 0;
183             while ($k < count($lines) && strlen($lines[$k]) == 0) {
184                 $k++;
185             }
186             preg_match("|^" . $chr . "*|", $lines[$k], $m);
187             $count = strlen($m[0]);
188         }
189
190         for ($k = 0; $k < count($lines); $k++) {
191             $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
192         }
193
194         return implode("\n", $lines);
195     }
196
197     /**
198      * @brief Get byte size returned in a Data Measurement (KB, MB, GB)
199      * 
200      * @param int $bytes    The number of bytes to be measured
201      * @param int $precision    Optional. Default 2.
202      * 
203      * @return string   Size with measured units.
204      */
205     public static function formatBytes($bytes, $precision = 2)
206     {
207         $units = ['B', 'KB', 'MB', 'GB', 'TB'];
208         $bytes = max($bytes, 0);
209         $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
210         $pow = min($pow, count($units) - 1);
211         $bytes /= pow(1024, $pow);
212
213         return round($bytes, $precision) . ' ' . $units[$pow];
214     }
215
216     /**
217      * @brief Protect percent characters in sprintf calls
218      * 
219      * @param string $s String to transform.
220      * 
221      * @return string   Transformed string.
222      */
223     public static function protectSprintf($s) // protect_sprintf()
224     {
225         return str_replace('%', '%%', $s);
226     }
227
228     /**
229      * @brief Base64 Encode URL and translate +/ to -_ Optionally strip padding.
230      * 
231      * @param string $s                 URL to encode
232      * @param boolean $strip_padding    Optional. Default false
233      * 
234      * @return string   Encoded URL
235      */
236     public static function base64UrlEncode($s, $strip_padding = false) //base64url_encode()
237     {
238         $s = strtr(base64_encode($s), '+/', '-_');
239
240         if ($strip_padding) {
241             $s = str_replace('=', '', $s);
242         }
243
244         return $s;
245     }
246
247     /**
248      * @brief Decode Base64 Encoded URL and translate -_ to +/
249      * @param string $s URL to decode
250      * 
251      * @return string   Decoded URL
252      */
253     public static function base64url_decode($s) // base64url_decode()
254     {
255         if (is_array($s)) {
256             Logger::log('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
257             return $s;
258         }
259
260         /*
261         *  // Placeholder for new rev of salmon which strips base64 padding.
262         *  // PHP base64_decode handles the un-padded input without requiring this step
263         *  // Uncomment if you find you need it.
264         *
265         *       $l = strlen($s);
266         *       if (!strpos($s,'=')) {
267         *               $m = $l % 4;
268         *               if ($m == 2)
269         *                       $s .= '==';
270         *               if ($m == 3)
271         *                       $s .= '=';
272         *       }
273         *
274         */
275
276         return base64_decode(strtr($s, '-_', '+/'));
277     }
278
279     /**
280      * @brief Pull out all #hashtags and @person tags from $string.
281      *
282      * We also get @person@domain.com - which would make
283      * the regex quite complicated as tags can also
284      * end a sentence. So we'll run through our results
285      * and strip the period from any tags which end with one.
286      * Returns array of tags found, or empty array.
287      *
288      * @param string $string Post content
289      * 
290      * @return array List of tag and person names
291      */
292     public static function getTags($string) // get_tags()
293     {
294         $ret = [];
295
296         // Convert hashtag links to hashtags
297         $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
298
299         // ignore anything in a code block
300         $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
301
302         // Force line feeds at bbtags
303         $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
304
305         // ignore anything in a bbtag
306         $string = preg_replace('/\[(.*?)\]/sm', '', $string);
307
308         // Match full names against @tags including the space between first and last
309         // We will look these up afterward to see if they are full names or not recognisable.
310
311         if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
312             foreach ($matches[1] as $match) {
313                 if (strstr($match, ']')) {
314                     // we might be inside a bbcode color tag - leave it alone
315                     continue;
316                 }
317
318                 if (substr($match, -1, 1) === '.') {
319                     $ret[] = substr($match, 0, -1);
320                 } else {
321                     $ret[] = $match;
322                 }
323             }
324         }
325
326         // Otherwise pull out single word tags. These can be @nickname, @first_last
327         // and #hash tags.
328
329         if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/', $string, $matches)) {
330             foreach ($matches[1] as $match) {
331                 if (strstr($match, ']')) {
332                     // we might be inside a bbcode color tag - leave it alone
333                     continue;
334                 }
335                 if (substr($match, -1, 1) === '.') {
336                     $match = substr($match,0,-1);
337                 }
338                 // ignore strictly numeric tags like #1
339                 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
340                     continue;
341                 }
342                 // try not to catch url fragments
343                 if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
344                     continue;
345                 }
346                 $ret[] = $match;
347             }
348         }
349
350         return $ret;
351     }
352
353     /**
354      * @brief Check for a valid email string
355      *
356      * @param string $email_address Email address to be evaluated.
357      * 
358      * @return boolean  Value indicating whether or not the string is a valid email address.
359      */
360     public static function isValidEmail($email_address) // valid_email()
361     {
362         return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
363     }
364
365     /**
366      * @brief Normalize url
367      *
368      * @param string $url   URL to be normalized.
369      * 
370      * @return string   Normalized URL.
371      */
372     public static function normaliseLink($url) // normalise_link()
373     {
374         $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
375         return rtrim($ret, '/');
376     }
377
378     /**
379      * @brief Normalize OpenID identity
380      * 
381      * @param string $s OpenID Identity
382      * 
383      * @return string   normalized OpenId Identity
384      */
385     function normaliseOpenID($s) // normalize_openid()
386     {
387         return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
388     }
389
390     /**
391      * @brief Compare two URLs to see if they are the same, but ignore
392      * slight but hopefully insignificant differences such as if one
393      * is https and the other isn't, or if one is www.something and
394      * the other isn't - and also ignore case differences.
395      *
396      * @param string $a first url
397      * @param string $b second url
398      * @return boolean True if the URLs match, otherwise False
399      *
400      */
401     public static function compareLink($a, $b) // link_compare()
402     {
403         return (strcasecmp(normalise_link($a), normalise_link($b)) === 0);
404     }
405 }