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