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 * @brief This is our primary input filter.
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.
40 * @param string $string Input string
41 * @return string Filtered string
43 public static function escapeTags($string)
45 return str_replace(["<", ">"], ['[', ']'], $string);
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
55 public static function escapeHtml($string)
57 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
61 * @brief Generate a string that's random, but usually pronounceable. Used to generate initial passwords
63 * @param int $len length
67 public static function getRandomName($len)
73 $vowels = ['a', 'a', 'ai', 'au', 'e', 'e', 'e', 'ee', 'ea', 'i', 'ie', 'o', 'ou', 'u'];
75 if (mt_rand(0, 5) == 4) {
81 'c', 'ch', 'cl', 'cr',
84 'g', 'gh', 'gl', 'gr',
87 'k', 'kh', 'kl', 'kr',
91 'p', 'ph', 'pl', 'pr',
94 's' ,'sc', 'sh', 'sm', 'sp', 'st',
102 $midcons = ['ck', 'ct', 'gn', 'ld', 'lf', 'lm', 'lt', 'mb', 'mm', 'mn', 'mp',
103 'nd', 'ng', 'nk', 'nt', 'rn', 'rp', 'rt'];
105 $noend = ['bl', 'br', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gr',
106 'kh', 'kl', 'kr', 'mn', 'pl', 'pr', 'rh', 'tr', 'qu', 'wh', 'q'];
108 $start = mt_rand(0, 2);
117 for ($x = 0; $x < $len; $x ++) {
118 $r = mt_rand(0, count($table) - 1);
121 if ($table == $vowels) {
122 $table = array_merge($cons, $midcons);
129 $word = substr($word, 0, $len);
131 foreach ($noend as $noe) {
132 $noelen = strlen($noe);
133 if ((strlen($word) > $noelen) && (substr($word, -$noelen) == $noe)) {
134 $word = self::getRandomName($len);
143 * @brief Translate and format the network name of a contact
145 * @param string $network Network name of the contact (e.g. dfrn, rss and so on)
146 * @param string $url The contact url
148 * @return string Formatted network name
150 public static function formatNetworkName($network, $url = '')
152 if ($network != '') {
154 $network_name = '<a href="' . $url .'">' . ContactSelector::networkToName($network, $url) . '</a>';
156 $network_name = ContactSelector::networkToName($network);
159 return $network_name;
164 * @brief Remove indentation from a text
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.
170 * @return string Transformed string.
172 public static function deindent($text, $chr = "[\t ]", $count = NULL)
174 $lines = explode("\n", $text);
176 if (is_null($count)) {
179 while ($k < count($lines) && strlen($lines[$k]) == 0) {
182 preg_match("|^" . $chr . "*|", $lines[$k], $m);
183 $count = strlen($m[0]);
186 for ($k = 0; $k < count($lines); $k++) {
187 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
190 return implode("\n", $lines);
194 * @brief Get byte size returned in a Data Measurement (KB, MB, GB)
196 * @param int $bytes The number of bytes to be measured
197 * @param int $precision Optional. Default 2.
199 * @return string Size with measured units.
201 public static function formatBytes($bytes, $precision = 2)
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);
209 return round($bytes, $precision) . ' ' . $units[$pow];
213 * @brief Protect percent characters in sprintf calls
215 * @param string $s String to transform.
217 * @return string Transformed string.
219 public static function protectSprintf($s)
221 return str_replace('%', '%%', $s);
225 * @brief Base64 Encode URL and translate +/ to -_ Optionally strip padding.
227 * @param string $s URL to encode
228 * @param boolean $strip_padding Optional. Default false
230 * @return string Encoded URL
232 public static function base64UrlEncode($s, $strip_padding = false)
234 $s = strtr(base64_encode($s), '+/', '-_');
236 if ($strip_padding) {
237 $s = str_replace('=', '', $s);
244 * @brief Decode Base64 Encoded URL and translate -_ to +/
245 * @param string $s URL to decode
247 * @return string Decoded URL
249 public static function base64UrlDecode($s)
252 Logger::log('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
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.
262 * if (!strpos($s,'=')) {
272 return base64_decode(strtr($s, '-_', '+/'));
276 * @brief Normalize url
278 * @param string $url URL to be normalized.
280 * @return string Normalized URL.
282 public static function normaliseLink($url)
284 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
285 return rtrim($ret, '/');
289 * @brief Normalize OpenID identity
291 * @param string $s OpenID Identity
293 * @return string normalized OpenId Identity
295 function normaliseOpenID($s)
297 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
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.
306 * @param string $a first url
307 * @param string $b second url
308 * @return boolean True if the URLs match, otherwise False
311 public static function compareLink($a, $b)
313 return (strcasecmp(self::normaliseLink($a), self::normaliseLink($b)) === 0);
318 * Ensures the provided URI has its query string punctuation in order.
323 public static function ensureQueryParameter($uri)
325 if (strpos($uri, '?') === false && ($pos = strpos($uri, '&')) !== false) {
326 $uri = substr($uri, 0, $pos) . '?' . substr($uri, $pos + 1);