3 * @file src/Util/Strings.php
6 namespace Friendica\Util;
8 use Friendica\Content\ContactSelector;
9 use Friendica\Core\Logger;
12 * @brief This class handles string functions
17 * @brief Generates a pseudo-random string of hexadecimal characters
22 public static function getRandomHex($size = 64)
24 $byte_size = ceil($size / 2);
26 $bytes = random_bytes($byte_size);
28 $return = substr(bin2hex($bytes), 0, $size);
34 * This is our primary input filter.
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.
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.
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.
47 * @param string $string Input string
48 * @return string Filtered string
50 public static function removeTags($string)
52 return str_replace(["<", ">"], ['[', ']'], $string);
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
62 public static function escapeTags($string)
64 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
68 * @brief Generate a string that's random, but usually pronounceable. Used to generate initial passwords
70 * @param int $len length
74 public static function getRandomName($len)
80 $vowels = ['a', 'a', 'ai', 'au', 'e', 'e', 'e', 'ee', 'ea', 'i', 'ie', 'o', 'ou', 'u'];
82 if (mt_rand(0, 5) == 4) {
88 'c', 'ch', 'cl', 'cr',
91 'g', 'gh', 'gl', 'gr',
94 'k', 'kh', 'kl', 'kr',
98 'p', 'ph', 'pl', 'pr',
101 's' ,'sc', 'sh', 'sm', 'sp', 'st',
109 $midcons = ['ck', 'ct', 'gn', 'ld', 'lf', 'lm', 'lt', 'mb', 'mm', 'mn', 'mp',
110 'nd', 'ng', 'nk', 'nt', 'rn', 'rp', 'rt'];
112 $noend = ['bl', 'br', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gr',
113 'kh', 'kl', 'kr', 'mn', 'pl', 'pr', 'rh', 'tr', 'qu', 'wh', 'q'];
115 $start = mt_rand(0, 2);
124 for ($x = 0; $x < $len; $x ++) {
125 $r = mt_rand(0, count($table) - 1);
128 if ($table == $vowels) {
129 $table = array_merge($cons, $midcons);
136 $word = substr($word, 0, $len);
138 foreach ($noend as $noe) {
139 $noelen = strlen($noe);
140 if ((strlen($word) > $noelen) && (substr($word, -$noelen) == $noe)) {
141 $word = self::getRandomName($len);
150 * @brief translate and format the networkname of a contact
152 * @param string $network Networkname of the contact (e.g. dfrn, rss and so on)
153 * @param string $url The contact url
155 * @return string Formatted network name
157 public static function formatNetworkName($network, $url = 0)
159 if ($network != "") {
161 $network_name = '<a href="'.$url.'">'.ContactSelector::networkToName($network, $url)."</a>";
163 $network_name = ContactSelector::networkToName($network);
166 return $network_name;
171 * @brief Remove intentation from a text
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.
177 * @return string Transformed string.
179 public static function deindent($text, $chr = "[\t ]", $count = NULL)
181 $lines = explode("\n", $text);
183 if (is_null($count)) {
186 while ($k < count($lines) && strlen($lines[$k]) == 0) {
189 preg_match("|^" . $chr . "*|", $lines[$k], $m);
190 $count = strlen($m[0]);
193 for ($k = 0; $k < count($lines); $k++) {
194 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
197 return implode("\n", $lines);
201 * @brief Get byte size returned in a Data Measurement (KB, MB, GB)
203 * @param int $bytes The number of bytes to be measured
204 * @param int $precision Optional. Default 2.
206 * @return string Size with measured units.
208 public static function formatBytes($bytes, $precision = 2)
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);
216 return round($bytes, $precision) . ' ' . $units[$pow];
220 * @brief Protect percent characters in sprintf calls
222 * @param string $s String to transform.
224 * @return string Transformed string.
226 public static function protectSprintf($s)
228 return str_replace('%', '%%', $s);
232 * @brief Base64 Encode URL and translate +/ to -_ Optionally strip padding.
234 * @param string $s URL to encode
235 * @param boolean $strip_padding Optional. Default false
237 * @return string Encoded URL
239 public static function base64UrlEncode($s, $strip_padding = false)
241 $s = strtr(base64_encode($s), '+/', '-_');
243 if ($strip_padding) {
244 $s = str_replace('=', '', $s);
251 * @brief Decode Base64 Encoded URL and translate -_ to +/
252 * @param string $s URL to decode
254 * @return string Decoded URL
256 public static function base64UrlDecode($s)
259 Logger::log('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
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.
269 * if (!strpos($s,'=')) {
279 return base64_decode(strtr($s, '-_', '+/'));
283 * @brief Pull out all #hashtags and @person tags from $string.
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.
291 * @param string $string Post content
293 * @return array List of tag and person names
295 public static function getTags($string)
299 // Convert hashtag links to hashtags
300 $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2', $string);
302 // ignore anything in a code block
303 $string = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $string);
305 // Force line feeds at bbtags
306 $string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
308 // ignore anything in a bbtag
309 $string = preg_replace('/\[(.*?)\]/sm', '', $string);
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.
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
321 if (substr($match, -1, 1) === '.') {
322 $ret[] = substr($match, 0, -1);
329 // Otherwise pull out single word tags. These can be @nickname, @first_last
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
338 if (substr($match, -1, 1) === '.') {
339 $match = substr($match,0,-1);
341 // ignore strictly numeric tags like #1
342 if ((strpos($match, '#') === 0) && ctype_digit(substr($match, 1))) {
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))) {
357 * @brief Check for a valid email string
359 * @param string $email_address Email address to be evaluated.
361 * @return boolean Value indicating whether or not the string is a valid email address.
363 public static function isValidEmail($email_address)
365 return preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $email_address);
369 * @brief Normalize url
371 * @param string $url URL to be normalized.
373 * @return string Normalized URL.
375 public static function normaliseLink($url)
377 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
378 return rtrim($ret, '/');
382 * @brief Normalize OpenID identity
384 * @param string $s OpenID Identity
386 * @return string normalized OpenId Identity
388 function normaliseOpenID($s)
390 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
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.
399 * @param string $a first url
400 * @param string $b second url
401 * @return boolean True if the URLs match, otherwise False
404 public static function compareLink($a, $b)
406 return (strcasecmp(self::normaliseLink($a), self::normaliseLink($b)) === 0);