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
23 public static function getRandomHex($size = 64)
25 $byte_size = ceil($size / 2);
27 $bytes = random_bytes($byte_size);
29 $return = substr(bin2hex($bytes), 0, $size);
35 * @brief This is our primary input filter.
37 * Use this on any text input where angle chars are not valid or permitted
38 * They will be replaced with safer brackets. This may be filtered further
39 * if these are not allowed either.
41 * @param string $string Input string
42 * @return string Filtered string
44 public static function escapeTags($string)
46 return str_replace(["<", ">"], ['[', ']'], $string);
50 * @brief Use this on "body" or "content" input where angle chars shouldn't be removed,
51 * and allow them to be safely displayed.
52 * @param string $string
56 public static function escapeHtml($string)
58 return htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false);
62 * @brief Generate a string that's random, but usually pronounceable. Used to generate initial passwords
64 * @param int $len length
68 public static function getRandomName($len)
74 $vowels = ['a', 'a', 'ai', 'au', 'e', 'e', 'e', 'ee', 'ea', 'i', 'ie', 'o', 'ou', 'u'];
76 if (mt_rand(0, 5) == 4) {
82 'c', 'ch', 'cl', 'cr',
85 'g', 'gh', 'gl', 'gr',
88 'k', 'kh', 'kl', 'kr',
92 'p', 'ph', 'pl', 'pr',
95 's' ,'sc', 'sh', 'sm', 'sp', 'st',
103 $midcons = ['ck', 'ct', 'gn', 'ld', 'lf', 'lm', 'lt', 'mb', 'mm', 'mn', 'mp',
104 'nd', 'ng', 'nk', 'nt', 'rn', 'rp', 'rt'];
106 $noend = ['bl', 'br', 'cl', 'cr', 'dr', 'fl', 'fr', 'gl', 'gr',
107 'kh', 'kl', 'kr', 'mn', 'pl', 'pr', 'rh', 'tr', 'qu', 'wh', 'q'];
109 $start = mt_rand(0, 2);
118 for ($x = 0; $x < $len; $x ++) {
119 $r = mt_rand(0, count($table) - 1);
122 if ($table == $vowels) {
123 $table = array_merge($cons, $midcons);
130 $word = substr($word, 0, $len);
132 foreach ($noend as $noe) {
133 $noelen = strlen($noe);
134 if ((strlen($word) > $noelen) && (substr($word, -$noelen) == $noe)) {
135 $word = self::getRandomName($len);
144 * Translate and format the network name of a contact
146 * @param string $network Network name of the contact (e.g. dfrn, rss and so on)
147 * @param string $url The contact url
149 * @return string Formatted network name
150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
152 public static function formatNetworkName($network, $url = '')
154 if ($network != '') {
156 $network_name = '<a href="' . $url .'">' . ContactSelector::networkToName($network, $url) . '</a>';
158 $network_name = ContactSelector::networkToName($network);
161 return $network_name;
166 * @brief Remove indentation from a text
168 * @param string $text String to be transformed.
169 * @param string $chr Optional. Indentation tag. Default tab (\t).
170 * @param int $count Optional. Default null.
172 * @return string Transformed string.
174 public static function deindent($text, $chr = "[\t ]", $count = NULL)
176 $lines = explode("\n", $text);
178 if (is_null($count)) {
181 while ($k < count($lines) && strlen($lines[$k]) == 0) {
184 preg_match("|^" . $chr . "*|", $lines[$k], $m);
185 $count = strlen($m[0]);
188 for ($k = 0; $k < count($lines); $k++) {
189 $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
192 return implode("\n", $lines);
196 * @brief Get byte size returned in a Data Measurement (KB, MB, GB)
198 * @param int $bytes The number of bytes to be measured
199 * @param int $precision Optional. Default 2.
201 * @return string Size with measured units.
203 public static function formatBytes($bytes, $precision = 2)
205 $units = ['B', 'KB', 'MB', 'GB', 'TB'];
206 $bytes = max($bytes, 0);
207 $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
208 $pow = min($pow, count($units) - 1);
209 $bytes /= pow(1024, $pow);
211 return round($bytes, $precision) . ' ' . $units[$pow];
215 * @brief Protect percent characters in sprintf calls
217 * @param string $s String to transform.
219 * @return string Transformed string.
221 public static function protectSprintf($s)
223 return str_replace('%', '%%', $s);
227 * @brief Base64 Encode URL and translate +/ to -_ Optionally strip padding.
229 * @param string $s URL to encode
230 * @param boolean $strip_padding Optional. Default false
232 * @return string Encoded URL
234 public static function base64UrlEncode($s, $strip_padding = false)
236 $s = strtr(base64_encode($s), '+/', '-_');
238 if ($strip_padding) {
239 $s = str_replace('=', '', $s);
246 * @brief Decode Base64 Encoded URL and translate -_ to +/
247 * @param string $s URL to decode
249 * @return string Decoded URL
252 public static function base64UrlDecode($s)
255 Logger::log('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
260 * // Placeholder for new rev of salmon which strips base64 padding.
261 * // PHP base64_decode handles the un-padded input without requiring this step
262 * // Uncomment if you find you need it.
265 * if (!strpos($s,'=')) {
275 return base64_decode(strtr($s, '-_', '+/'));
279 * @brief Normalize url
281 * @param string $url URL to be normalized.
283 * @return string Normalized URL.
285 public static function normaliseLink($url)
287 $ret = str_replace(['https:', '//www.'], ['http:', '//'], $url);
288 return rtrim($ret, '/');
292 * @brief Normalize OpenID identity
294 * @param string $s OpenID Identity
296 * @return string normalized OpenId Identity
298 public static function normaliseOpenID($s)
300 return trim(str_replace(['http://', 'https://'], ['', ''], $s), '/');
304 * @brief Compare two URLs to see if they are the same, but ignore
305 * slight but hopefully insignificant differences such as if one
306 * is https and the other isn't, or if one is www.something and
307 * the other isn't - and also ignore case differences.
309 * @param string $a first url
310 * @param string $b second url
311 * @return boolean True if the URLs match, otherwise False
314 public static function compareLink($a, $b)
316 return (strcasecmp(self::normaliseLink($a), self::normaliseLink($b)) === 0);
321 * Ensures the provided URI has its query string punctuation in order.
326 public static function ensureQueryParameter($uri)
328 if (strpos($uri, '?') === false && ($pos = strpos($uri, '&')) !== false) {
329 $uri = substr($uri, 0, $pos) . '?' . substr($uri, $pos + 1);