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 escapeHtml($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 Normalize url
285 * @param string $url URL to be normalized.
287 * @return string Normalized URL.
289 public static function normaliseLink($url)
291 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
292 return rtrim($ret, '/');
296 * @brief Normalize OpenID identity
298 * @param string $s OpenID Identity
300 * @return string normalized OpenId Identity
302 function normaliseOpenID($s)
304 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
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.
313 * @param string $a first url
314 * @param string $b second url
315 * @return boolean True if the URLs match, otherwise False
318 public static function compareLink($a, $b)
320 return (strcasecmp(self::normaliseLink($a), self::normaliseLink($b)) === 0);