Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
fe482240 | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | ||
f24846d5 SL |
18 | use function xKerman\Restricted\unserialize; |
19 | use xKerman\Restricted\UnserializeFailedException; | |
20 | ||
6a488035 TO |
21 | require_once 'HTML/QuickForm/Rule/Email.php'; |
22 | ||
23 | /** | |
fe482240 | 24 | * This class contains string functions. |
6a488035 TO |
25 | */ |
26 | class CRM_Utils_String { | |
7da04cde | 27 | const COMMA = ",", SEMICOLON = ";", SPACE = " ", TAB = "\t", LINEFEED = "\n", CARRIAGELINE = "\r\n", LINECARRIAGE = "\n\r", CARRIAGERETURN = "\r"; |
6a488035 TO |
28 | |
29 | /** | |
30 | * List of all letters and numbers | |
31 | */ | |
32 | const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; | |
33 | ||
34 | /** | |
fe482240 | 35 | * Convert a display name into a potential variable name. |
6a488035 | 36 | * |
5ab8fe4a | 37 | * @param string $title title of the string |
f4aaa82a EM |
38 | * @param int $maxLength |
39 | * | |
c866eb5f TO |
40 | * @return string |
41 | * An equivalent variable name. | |
6a488035 | 42 | */ |
00be9182 | 43 | public static function titleToVar($title, $maxLength = 31) { |
6a488035 TO |
44 | $variable = self::munge($title, '_', $maxLength); |
45 | ||
46 | if (CRM_Utils_Rule::title($variable, $maxLength)) { | |
47 | return $variable; | |
48 | } | |
49 | ||
50 | // if longer than the maxLength lets just return a substr of the | |
51 | // md5 to prevent errors downstream | |
52 | return substr(md5($title), 0, $maxLength); | |
53 | } | |
54 | ||
55 | /** | |
fe482240 | 56 | * Replace all non alpha numeric characters and spaces with the replacement character. |
6a488035 | 57 | * |
77855840 TO |
58 | * @param string $name |
59 | * The name to be worked on. | |
60 | * @param string $char | |
61 | * The character to use for non-valid chars. | |
62 | * @param int $len | |
63 | * Length of valid variables. | |
6a488035 | 64 | * |
a6c01b45 CW |
65 | * @return string |
66 | * returns the manipulated string | |
6a488035 | 67 | */ |
00be9182 | 68 | public static function munge($name, $char = '_', $len = 63) { |
fe482240 | 69 | // Replace all white space and non-alpha numeric with $char |
6a488035 TO |
70 | // we only use the ascii character set since mysql does not create table names / field names otherwise |
71 | // CRM-11744 | |
72 | $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name)); | |
755a3caf AA |
73 | |
74 | //If there are no ascii characters present. | |
75 | if ($name == $char) { | |
76 | $name = self::createRandom($len, self::ALPHANUMERIC); | |
77 | } | |
78 | ||
6a488035 TO |
79 | if ($len) { |
80 | // lets keep variable names short | |
81 | return substr($name, 0, $len); | |
82 | } | |
83 | else { | |
84 | return $name; | |
85 | } | |
86 | } | |
87 | ||
dc913073 | 88 | /** |
74c303ca | 89 | * Convert possibly underscore separated words to camel case. |
dc913073 | 90 | * |
74c303ca | 91 | * @param string $str |
92 | * @param bool $ucFirst | |
93 | * Should the first letter be capitalized like `CamelCase` or lower like `camelCase` | |
a6c01b45 | 94 | * @return string |
dc913073 | 95 | */ |
74c303ca | 96 | public static function convertStringToCamel($str, $ucFirst = TRUE) { |
97 | $fragments = explode('_', $str); | |
98 | $camel = implode('', array_map('ucfirst', $fragments)); | |
99 | return $ucFirst ? $camel : lcfirst($camel); | |
dc913073 EM |
100 | } |
101 | ||
6a488035 | 102 | /** |
fe482240 | 103 | * Takes a variable name and munges it randomly into another variable name. |
6a488035 | 104 | * |
77855840 TO |
105 | * @param string $name |
106 | * Initial Variable Name. | |
107 | * @param int $len | |
108 | * Length of valid variables. | |
6a488035 | 109 | * |
a6c01b45 CW |
110 | * @return string |
111 | * Randomized Variable Name | |
6a488035 | 112 | */ |
00be9182 | 113 | public static function rename($name, $len = 4) { |
6a488035 TO |
114 | $rand = substr(uniqid(), 0, $len); |
115 | return substr_replace($name, $rand, -$len, $len); | |
116 | } | |
117 | ||
118 | /** | |
100fef9d | 119 | * Takes a string and returns the last tuple of the string. |
fe482240 EM |
120 | * |
121 | * Useful while converting file names to class names etc | |
6a488035 | 122 | * |
77855840 TO |
123 | * @param string $string |
124 | * The input string. | |
f3258574 CW |
125 | * @param string $char |
126 | * Character used to demarcate the components | |
6a488035 | 127 | * |
a6c01b45 | 128 | * @return string |
f3258574 | 129 | * The last component |
6a488035 | 130 | */ |
00be9182 | 131 | public static function getClassName($string, $char = '_') { |
be2fb01f | 132 | $names = []; |
6a488035 TO |
133 | if (!is_array($string)) { |
134 | $names = explode($char, $string); | |
135 | } | |
136 | if (!empty($names)) { | |
137 | return array_pop($names); | |
138 | } | |
139 | } | |
140 | ||
141 | /** | |
f3258574 | 142 | * Appends a name to a string and separated by delimiter. |
fe482240 EM |
143 | * |
144 | * Does the right thing for an empty string | |
6a488035 | 145 | * |
77855840 TO |
146 | * @param string $str |
147 | * The string to be appended to. | |
148 | * @param string $delim | |
149 | * The delimiter to use. | |
150 | * @param mixed $name | |
151 | * The string (or array of strings) to append. | |
6a488035 | 152 | */ |
00be9182 | 153 | public static function append(&$str, $delim, $name) { |
6a488035 TO |
154 | if (empty($name)) { |
155 | return; | |
156 | } | |
157 | ||
158 | if (is_array($name)) { | |
159 | foreach ($name as $n) { | |
160 | if (empty($n)) { | |
161 | continue; | |
162 | } | |
163 | if (empty($str)) { | |
164 | $str = $n; | |
165 | } | |
166 | else { | |
167 | $str .= $delim . $n; | |
168 | } | |
169 | } | |
170 | } | |
171 | else { | |
172 | if (empty($str)) { | |
173 | $str = $name; | |
174 | } | |
175 | else { | |
176 | $str .= $delim . $name; | |
177 | } | |
178 | } | |
179 | } | |
180 | ||
181 | /** | |
fe482240 | 182 | * Determine if the string is composed only of ascii characters. |
6a488035 | 183 | * |
77855840 TO |
184 | * @param string $str |
185 | * Input string. | |
186 | * @param bool $utf8 | |
187 | * Attempt utf8 match on failure (default yes). | |
6a488035 | 188 | * |
608e6658 | 189 | * @return bool |
a6c01b45 | 190 | * true if string is ascii |
6a488035 | 191 | */ |
00be9182 | 192 | public static function isAscii($str, $utf8 = TRUE) { |
6a488035 TO |
193 | if (!function_exists('mb_detect_encoding')) { |
194 | // eliminate all white space from the string | |
195 | $str = preg_replace('/\s+/', '', $str); | |
196 | // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work. | |
197 | ||
50bfb460 | 198 | // match low- or high-ascii characters |
6a488035 TO |
199 | if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) { |
200 | // || // low ascii characters | |
201 | // high ascii characters | |
202 | // preg_match( '/[\x7F-\xFF]/', $str ) ) { | |
203 | if ($utf8) { | |
50bfb460 | 204 | // if we did match, try for utf-8, or iso8859-1 |
6a488035 TO |
205 | |
206 | return self::isUtf8($str); | |
207 | } | |
208 | else { | |
209 | return FALSE; | |
210 | } | |
211 | } | |
212 | return TRUE; | |
213 | } | |
214 | else { | |
be2fb01f | 215 | $order = ['ASCII']; |
6a488035 TO |
216 | if ($utf8) { |
217 | $order[] = 'UTF-8'; | |
218 | } | |
219 | $enc = mb_detect_encoding($str, $order, TRUE); | |
220 | return ($enc == 'ASCII' || $enc == 'UTF-8'); | |
221 | } | |
222 | } | |
223 | ||
08b2ba0c TO |
224 | /** |
225 | * Encode string using URL-safe Base64. | |
226 | * | |
227 | * @param string $v | |
228 | * | |
229 | * @return string | |
230 | * @see https://tools.ietf.org/html/rfc4648#section-5 | |
231 | */ | |
232 | public static function base64UrlEncode($v) { | |
233 | return rtrim(str_replace(['+', '/'], ['-', '_'], base64_encode($v)), '='); | |
234 | } | |
235 | ||
236 | /** | |
237 | * Decode string using URL-safe Base64. | |
238 | * | |
239 | * @param string $v | |
240 | * | |
241 | * @return false|string | |
242 | * @see https://tools.ietf.org/html/rfc4648#section-5 | |
243 | */ | |
244 | public static function base64UrlDecode($v) { | |
245 | // PHP base64_decode() is already forgiving about padding ("="). | |
246 | return base64_decode(str_replace(['-', '_'], ['+', '/'], $v)); | |
247 | } | |
248 | ||
6a488035 | 249 | /** |
fe482240 | 250 | * Determine the string replacements for redaction. |
6a488035 TO |
251 | * on the basis of the regular expressions |
252 | * | |
77855840 TO |
253 | * @param string $str |
254 | * Input string. | |
255 | * @param array $regexRules | |
256 | * Regular expression to be matched w/ replacements. | |
6a488035 | 257 | * |
a6c01b45 CW |
258 | * @return array |
259 | * array of strings w/ corresponding redacted outputs | |
6a488035 | 260 | */ |
00be9182 | 261 | public static function regex($str, $regexRules) { |
50bfb460 | 262 | // redact the regular expressions |
6a488035 | 263 | if (!empty($regexRules) && isset($str)) { |
be2fb01f | 264 | static $matches, $totalMatches, $match = []; |
6a488035 TO |
265 | foreach ($regexRules as $pattern => $replacement) { |
266 | preg_match_all($pattern, $str, $matches); | |
267 | if (!empty($matches[0])) { | |
268 | if (empty($totalMatches)) { | |
269 | $totalMatches = $matches[0]; | |
270 | } | |
271 | else { | |
272 | $totalMatches = array_merge($totalMatches, $matches[0]); | |
273 | } | |
274 | $match = array_flip($totalMatches); | |
275 | } | |
276 | } | |
277 | } | |
278 | ||
279 | if (!empty($match)) { | |
280 | foreach ($match as $matchKey => & $dontCare) { | |
281 | foreach ($regexRules as $pattern => $replacement) { | |
282 | if (preg_match($pattern, $matchKey)) { | |
283 | $dontCare = $replacement . substr(md5($matchKey), 0, 5); | |
284 | break; | |
285 | } | |
286 | } | |
287 | } | |
288 | return $match; | |
289 | } | |
db62d3a5 | 290 | return []; |
6a488035 TO |
291 | } |
292 | ||
5bc392e6 EM |
293 | /** |
294 | * @param $str | |
295 | * @param $stringRules | |
296 | * | |
297 | * @return mixed | |
298 | */ | |
00be9182 | 299 | public static function redaction($str, $stringRules) { |
50bfb460 | 300 | // redact the strings |
6a488035 TO |
301 | if (!empty($stringRules)) { |
302 | foreach ($stringRules as $match => $replace) { | |
303 | $str = str_ireplace($match, $replace, $str); | |
304 | } | |
305 | } | |
306 | ||
50bfb460 | 307 | // return the redacted output |
6a488035 TO |
308 | return $str; |
309 | } | |
310 | ||
311 | /** | |
312 | * Determine if a string is composed only of utf8 characters | |
313 | * | |
77855840 TO |
314 | * @param string $str |
315 | * Input string. | |
6a488035 | 316 | * |
608e6658 | 317 | * @return bool |
6a488035 | 318 | */ |
00be9182 | 319 | public static function isUtf8($str) { |
6a488035 TO |
320 | if (!function_exists(mb_detect_encoding)) { |
321 | // eliminate all white space from the string | |
322 | $str = preg_replace('/\s+/', '', $str); | |
323 | ||
50bfb460 SB |
324 | // pattern stolen from the php.net function documentation for |
325 | // utf8decode(); | |
326 | // comment by JF Sebastian, 30-Mar-2005 | |
6a488035 TO |
327 | return preg_match('/^([\x00-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xec][\x80-\xbf]{2}|\xed[\x80-\x9f][\x80-\xbf]|[\xee-\xef][\x80-\xbf]{2}|f0[\x90-\xbf][\x80-\xbf]{2}|[\xf1-\xf3][\x80-\xbf]{3}|\xf4[\x80-\x8f][\x80-\xbf]{2})*$/', $str); |
328 | // || | |
329 | // iconv('ISO-8859-1', 'UTF-8', $str); | |
330 | } | |
331 | else { | |
be2fb01f | 332 | $enc = mb_detect_encoding($str, ['UTF-8'], TRUE); |
6a488035 TO |
333 | return ($enc !== FALSE); |
334 | } | |
335 | } | |
336 | ||
337 | /** | |
50bfb460 | 338 | * Determine if two hrefs are equivalent (fuzzy match) |
6a488035 | 339 | * |
77855840 TO |
340 | * @param string $url1 |
341 | * The first url to be matched. | |
342 | * @param string $url2 | |
343 | * The second url to be matched against. | |
6a488035 | 344 | * |
608e6658 | 345 | * @return bool |
a6c01b45 | 346 | * true if the urls match, else false |
6a488035 | 347 | */ |
00be9182 | 348 | public static function match($url1, $url2) { |
6a488035 TO |
349 | $url1 = strtolower($url1); |
350 | $url2 = strtolower($url2); | |
351 | ||
352 | $url1Str = parse_url($url1); | |
353 | $url2Str = parse_url($url2); | |
354 | ||
355 | if ($url1Str['path'] == $url2Str['path'] && | |
356 | self::extractURLVarValue(CRM_Utils_Array::value('query', $url1Str)) == self::extractURLVarValue(CRM_Utils_Array::value('query', $url2Str)) | |
357 | ) { | |
358 | return TRUE; | |
359 | } | |
360 | return FALSE; | |
361 | } | |
362 | ||
363 | /** | |
fe482240 | 364 | * Extract the civicrm path from the url. |
6a488035 | 365 | * |
f3258574 CW |
366 | * @param string $query |
367 | * A url string. | |
6a488035 | 368 | * |
f3258574 CW |
369 | * @return string|null |
370 | * civicrm url (eg: civicrm/contact/search) | |
6a488035 | 371 | */ |
00be9182 | 372 | public static function extractURLVarValue($query) { |
6a488035 TO |
373 | $config = CRM_Core_Config::singleton(); |
374 | $urlVar = $config->userFrameworkURLVar; | |
375 | ||
376 | $params = explode('&', $query); | |
377 | foreach ($params as $p) { | |
378 | if (strpos($p, '=')) { | |
379 | list($k, $v) = explode('=', $p); | |
380 | if ($k == $urlVar) { | |
381 | return $v; | |
382 | } | |
383 | } | |
384 | } | |
385 | return NULL; | |
386 | } | |
387 | ||
388 | /** | |
100fef9d | 389 | * Translate a true/false/yes/no string to a 0 or 1 value |
6a488035 | 390 | * |
77855840 TO |
391 | * @param string $str |
392 | * The string to be translated. | |
6a488035 | 393 | * |
608e6658 | 394 | * @return bool |
6a488035 | 395 | */ |
00be9182 | 396 | public static function strtobool($str) { |
6a488035 TO |
397 | if (!is_scalar($str)) { |
398 | return FALSE; | |
399 | } | |
400 | ||
401 | if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) { | |
402 | return TRUE; | |
403 | } | |
404 | return FALSE; | |
405 | } | |
406 | ||
407 | /** | |
100fef9d | 408 | * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false |
6a488035 | 409 | * |
77855840 TO |
410 | * @param string $str |
411 | * The string to be translated. | |
6a488035 | 412 | * |
608e6658 | 413 | * @return bool |
6a488035 | 414 | */ |
00be9182 | 415 | public static function strtoboolstr($str) { |
6a488035 TO |
416 | if (!is_scalar($str)) { |
417 | return FALSE; | |
418 | } | |
419 | ||
420 | if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) { | |
421 | return '1'; | |
422 | } | |
423 | elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) { | |
424 | return '0'; | |
425 | } | |
426 | else { | |
427 | return FALSE; | |
428 | } | |
429 | } | |
430 | ||
431 | /** | |
432 | * Convert a HTML string into a text one using html2text | |
433 | * | |
77855840 TO |
434 | * @param string $html |
435 | * The string to be converted. | |
6a488035 | 436 | * |
a6c01b45 CW |
437 | * @return string |
438 | * the converted string | |
6a488035 | 439 | */ |
00be9182 | 440 | public static function htmlToText($html) { |
05bfb88f | 441 | require_once 'html2text/rcube_html2text.php'; |
bfef4c7e KW |
442 | $token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html); |
443 | $converter = new rcube_html2text($token_html); | |
444 | $token_text = $converter->get_text(); | |
445 | $text = preg_replace('!token\:\{([a-z_.]+)\}!i', '{$1}', $token_text); | |
446 | return $text; | |
6a488035 TO |
447 | } |
448 | ||
5bc392e6 EM |
449 | /** |
450 | * @param $string | |
c490a46a | 451 | * @param array $params |
5bc392e6 | 452 | */ |
00be9182 | 453 | public static function extractName($string, &$params) { |
6a488035 TO |
454 | $name = trim($string); |
455 | if (empty($name)) { | |
456 | return; | |
457 | } | |
458 | ||
459 | // strip out quotes | |
460 | $name = str_replace('"', '', $name); | |
461 | $name = str_replace('\'', '', $name); | |
462 | ||
463 | // check for comma in name | |
464 | if (strpos($name, ',') !== FALSE) { | |
465 | ||
466 | // name has a comma - assume lname, fname [mname] | |
467 | $names = explode(',', $name); | |
468 | if (count($names) > 1) { | |
469 | $params['last_name'] = trim($names[0]); | |
470 | ||
471 | // check for space delim | |
472 | $fnames = explode(' ', trim($names[1])); | |
473 | if (count($fnames) > 1) { | |
474 | $params['first_name'] = trim($fnames[0]); | |
475 | $params['middle_name'] = trim($fnames[1]); | |
476 | } | |
477 | else { | |
478 | $params['first_name'] = trim($fnames[0]); | |
479 | } | |
480 | } | |
481 | else { | |
482 | $params['first_name'] = trim($names[0]); | |
483 | } | |
484 | } | |
485 | else { | |
486 | // name has no comma - assume fname [mname] fname | |
487 | $names = explode(' ', $name); | |
488 | if (count($names) == 1) { | |
489 | $params['first_name'] = $names[0]; | |
490 | } | |
491 | elseif (count($names) == 2) { | |
492 | $params['first_name'] = $names[0]; | |
493 | $params['last_name'] = $names[1]; | |
494 | } | |
495 | else { | |
496 | $params['first_name'] = $names[0]; | |
497 | $params['middle_name'] = $names[1]; | |
498 | $params['last_name'] = $names[2]; | |
499 | } | |
500 | } | |
501 | } | |
502 | ||
5bc392e6 EM |
503 | /** |
504 | * @param $string | |
505 | * | |
506 | * @return array | |
507 | */ | |
00be9182 | 508 | public static function &makeArray($string) { |
6a488035 TO |
509 | $string = trim($string); |
510 | ||
511 | $values = explode("\n", $string); | |
be2fb01f | 512 | $result = []; |
6a488035 TO |
513 | foreach ($values as $value) { |
514 | list($n, $v) = CRM_Utils_System::explode('=', $value, 2); | |
515 | if (!empty($v)) { | |
516 | $result[trim($n)] = trim($v); | |
517 | } | |
518 | } | |
519 | return $result; | |
520 | } | |
521 | ||
6a488035 TO |
522 | /** |
523 | * Given an ezComponents-parsed representation of | |
524 | * a text with alternatives return only the first one | |
525 | * | |
77855840 TO |
526 | * @param string $full |
527 | * All alternatives as a long string (or some other text). | |
6a488035 | 528 | * |
a6c01b45 CW |
529 | * @return string |
530 | * only the first alternative found (or the text without alternatives) | |
6a488035 | 531 | */ |
00be9182 | 532 | public static function stripAlternatives($full) { |
be2fb01f | 533 | $matches = []; |
6a488035 TO |
534 | preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches); |
535 | ||
536 | if (isset($matches[1]) && | |
537 | trim(strip_tags($matches[1])) != '' | |
538 | ) { | |
539 | return $matches[1]; | |
540 | } | |
541 | else { | |
542 | return $full; | |
543 | } | |
544 | } | |
545 | ||
546 | /** | |
100fef9d | 547 | * Strip leading, trailing, double spaces from string |
6a488035 TO |
548 | * used for postal/greeting/addressee |
549 | * | |
77855840 TO |
550 | * @param string $string |
551 | * Input string to be cleaned. | |
6a488035 | 552 | * |
a6c01b45 CW |
553 | * @return string |
554 | * the cleaned string | |
6a488035 | 555 | */ |
00be9182 | 556 | public static function stripSpaces($string) { |
6a488035 TO |
557 | return (empty($string)) ? $string : preg_replace("/\s{2,}/", " ", trim($string)); |
558 | } | |
559 | ||
560 | /** | |
dc195289 | 561 | * clean the URL 'path' variable that we use |
6a488035 TO |
562 | * to construct CiviCRM urls by removing characters from the path variable |
563 | * | |
77855840 TO |
564 | * @param string $string |
565 | * The input string to be sanitized. | |
566 | * @param array $search | |
567 | * The characters to be sanitized. | |
568 | * @param string $replace | |
569 | * The character to replace it with. | |
6a488035 | 570 | * |
a6c01b45 CW |
571 | * @return string |
572 | * the sanitized string | |
6a488035 | 573 | */ |
608e6658 | 574 | public static function stripPathChars( |
a3e55d9c | 575 | $string, |
6a488035 TO |
576 | $search = NULL, |
577 | $replace = NULL | |
578 | ) { | |
579 | static $_searchChars = NULL; | |
580 | static $_replaceChar = NULL; | |
581 | ||
582 | if (empty($string)) { | |
583 | return $string; | |
584 | } | |
585 | ||
586 | if ($_searchChars == NULL) { | |
be2fb01f | 587 | $_searchChars = [ |
353ffa53 TO |
588 | '&', |
589 | ';', | |
590 | ',', | |
591 | '=', | |
592 | '$', | |
593 | '"', | |
594 | "'", | |
595 | '\\', | |
596 | '<', | |
597 | '>', | |
598 | '(', | |
599 | ')', | |
600 | ' ', | |
601 | "\r", | |
602 | "\r\n", | |
603 | "\n", | |
604 | "\t", | |
be2fb01f | 605 | ]; |
6a488035 TO |
606 | $_replaceChar = '_'; |
607 | } | |
608 | ||
6a488035 TO |
609 | if ($search == NULL) { |
610 | $search = $_searchChars; | |
611 | } | |
612 | ||
613 | if ($replace == NULL) { | |
614 | $replace = $_replaceChar; | |
615 | } | |
616 | ||
617 | return str_replace($search, $replace, $string); | |
618 | } | |
619 | ||
6a488035 TO |
620 | /** |
621 | * Use HTMLPurifier to clean up a text string and remove any potential | |
622 | * xss attacks. This is primarily used in public facing pages which | |
623 | * accept html as the input string | |
624 | * | |
77855840 TO |
625 | * @param string $string |
626 | * The input string. | |
6a488035 | 627 | * |
a6c01b45 CW |
628 | * @return string |
629 | * the cleaned up string | |
6a488035 | 630 | */ |
00be9182 | 631 | public static function purifyHTML($string) { |
e7292422 | 632 | static $_filter = NULL; |
6a488035 TO |
633 | if (!$_filter) { |
634 | $config = HTMLPurifier_Config::createDefault(); | |
635 | $config->set('Core.Encoding', 'UTF-8'); | |
7652022e | 636 | $config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']); |
6a488035 TO |
637 | |
638 | // Disable the cache entirely | |
e7292422 | 639 | $config->set('Cache.DefinitionImpl', NULL); |
6a488035 TO |
640 | |
641 | $_filter = new HTMLPurifier($config); | |
642 | } | |
643 | ||
644 | return $_filter->purify($string); | |
645 | } | |
646 | ||
647 | /** | |
648 | * Truncate $string; if $string exceeds $maxLen, place "..." at the end | |
649 | * | |
650 | * @param string $string | |
651 | * @param int $maxLen | |
f4aaa82a EM |
652 | * |
653 | * @return string | |
6a488035 | 654 | */ |
00be9182 | 655 | public static function ellipsify($string, $maxLen) { |
47f49a22 | 656 | if (mb_strlen($string, 'UTF-8') <= $maxLen) { |
6a488035 TO |
657 | return $string; |
658 | } | |
47f49a22 | 659 | return mb_substr($string, 0, $maxLen - 3, 'UTF-8') . '...'; |
6a488035 TO |
660 | } |
661 | ||
662 | /** | |
fe482240 | 663 | * Generate a random string. |
6a488035 TO |
664 | * |
665 | * @param $len | |
666 | * @param $alphabet | |
667 | * @return string | |
668 | */ | |
669 | public static function createRandom($len, $alphabet) { | |
670 | $alphabetSize = strlen($alphabet); | |
671 | $result = ''; | |
672 | for ($i = 0; $i < $len; $i++) { | |
20fd9f37 | 673 | $result .= $alphabet[rand(1, $alphabetSize) - 1]; |
6a488035 TO |
674 | } |
675 | return $result; | |
676 | } | |
677 | ||
fc7a0aee TO |
678 | /** |
679 | * Examples: | |
680 | * "admin foo" => array(NULL,"admin foo") | |
681 | * "cms:admin foo" => array("cms", "admin foo") | |
682 | * | |
f4aaa82a | 683 | * @param $delim |
77855840 TO |
684 | * @param string $string |
685 | * E.g. "view all contacts". Syntax: "[prefix:]name". | |
f4aaa82a EM |
686 | * @param null $defaultPrefix |
687 | * | |
a6c01b45 CW |
688 | * @return array |
689 | * (0 => string|NULL $prefix, 1 => string $value) | |
fc7a0aee TO |
690 | */ |
691 | public static function parsePrefix($delim, $string, $defaultPrefix = NULL) { | |
692 | $pos = strpos($string, $delim); | |
693 | if ($pos === FALSE) { | |
be2fb01f | 694 | return [$defaultPrefix, $string]; |
fc7a0aee TO |
695 | } |
696 | else { | |
be2fb01f | 697 | return [substr($string, 0, $pos), substr($string, 1 + $pos)]; |
fc7a0aee TO |
698 | } |
699 | } | |
700 | ||
87b48098 | 701 | /** |
100fef9d | 702 | * This function will mask part of the the user portion of an Email address (everything before the @) |
87b48098 | 703 | * |
77855840 TO |
704 | * @param string $email |
705 | * The email address to be masked. | |
706 | * @param string $maskChar | |
707 | * The character used for masking. | |
708 | * @param int $percent | |
709 | * The percentage of the user portion to be masked. | |
87b48098 | 710 | * |
a6c01b45 CW |
711 | * @return string |
712 | * returns the masked Email address | |
87b48098 | 713 | */ |
e7292422 | 714 | public static function maskEmail($email, $maskChar = '*', $percent = 50) { |
87b48098 K |
715 | list($user, $domain) = preg_split("/@/", $email); |
716 | $len = strlen($user); | |
e7292422 | 717 | $maskCount = floor($len * $percent / 100); |
87b48098 K |
718 | $offset = floor(($len - $maskCount) / 2); |
719 | ||
720 | $masked = substr($user, 0, $offset) | |
353ffa53 TO |
721 | . str_repeat($maskChar, $maskCount) |
722 | . substr($user, $maskCount + $offset); | |
87b48098 | 723 | |
92fcb95f | 724 | return ($masked . '@' . $domain); |
87b48098 K |
725 | } |
726 | ||
727 | /** | |
fe482240 | 728 | * This function compares two strings. |
87b48098 | 729 | * |
77855840 TO |
730 | * @param string $strOne |
731 | * String one. | |
732 | * @param string $strTwo | |
733 | * String two. | |
734 | * @param bool $case | |
735 | * Boolean indicating whether you want the comparison to be case sensitive or not. | |
87b48098 | 736 | * |
608e6658 | 737 | * @return bool |
a6c01b45 | 738 | * TRUE (string are identical); FALSE (strings are not identical) |
87b48098 K |
739 | */ |
740 | public static function compareStr($strOne, $strTwo, $case) { | |
741 | if ($case == TRUE) { | |
dca9da6e | 742 | // Convert to lowercase and trim white spaces |
87b48098 K |
743 | if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) { |
744 | // yes - they are identical | |
745 | return TRUE; | |
746 | } | |
747 | else { | |
748 | // not identical | |
749 | return FALSE; | |
750 | } | |
751 | } | |
752 | if ($case == FALSE) { | |
dca9da6e | 753 | // Trim white spaces |
87b48098 K |
754 | if (trim($strOne) == trim($strTwo)) { |
755 | // yes - they are identical | |
756 | return TRUE; | |
757 | } | |
758 | else { | |
759 | // not identical | |
760 | return FALSE; | |
761 | } | |
762 | } | |
763 | } | |
fc7a0aee | 764 | |
77d45291 TO |
765 | /** |
766 | * Many parts of the codebase have a convention of internally passing around | |
767 | * HTML-encoded URLs. This effectively means that "&" is replaced by "&" | |
768 | * (because most other odd characters are %-escaped in URLs; and %-escaped | |
769 | * strings don't need any extra escaping in HTML). | |
770 | * | |
608e6658 | 771 | * @param string $htmlUrl |
77855840 | 772 | * URL with HTML entities. |
a6c01b45 CW |
773 | * @return string |
774 | * URL without HTML entities | |
77d45291 TO |
775 | */ |
776 | public static function unstupifyUrl($htmlUrl) { | |
777 | return str_replace('&', '&', $htmlUrl); | |
778 | } | |
96025800 | 779 | |
6c094ca6 SM |
780 | /** |
781 | * When a user supplies a URL (e.g. to an image), we'd like to: | |
782 | * - Remove the protocol and domain name if the URL points to the current | |
783 | * site. | |
784 | * - Keep the domain name for remote URLs. | |
785 | * - Optionally, force remote URLs to use https instead of http (which is | |
786 | * useful for images) | |
787 | * | |
788 | * @param string $url | |
789 | * The URL to simplify. Examples: | |
790 | * "https://example.org/sites/default/files/coffee-mug.jpg" | |
791 | * "sites/default/files/coffee-mug.jpg" | |
792 | * "http://i.stack.imgur.com/9jb2ial01b.png" | |
793 | * @param bool $forceHttps = FALSE | |
794 | * If TRUE, ensure that remote URLs use https. If a URL with | |
795 | * http is supplied, then we'll change it to https. | |
796 | * This is useful for situations like showing a premium product on a | |
797 | * contribution, because (as reported in CRM-14283) if the user gets a | |
798 | * browser warning like "page contains insecure elements" on a contribution | |
799 | * page, that's a very bad thing. Thus, even if changing http to https | |
800 | * breaks the image, that's better than leaving http content in a | |
801 | * contribution page. | |
802 | * | |
803 | * @return string | |
804 | * The simplified URL. Examples: | |
805 | * "/sites/default/files/coffee-mug.jpg" | |
806 | * "https://i.stack.imgur.com/9jb2ial01b.png" | |
807 | */ | |
808 | public static function simplifyURL($url, $forceHttps = FALSE) { | |
809 | $config = CRM_Core_Config::singleton(); | |
810 | $siteURLParts = self::simpleParseUrl($config->userFrameworkBaseURL); | |
811 | $urlParts = self::simpleParseUrl($url); | |
812 | ||
813 | // If the image is locally hosted, then only give the path to the image | |
814 | $urlIsLocal | |
815 | = ($urlParts['host+port'] == '') | |
816 | | ($urlParts['host+port'] == $siteURLParts['host+port']); | |
817 | if ($urlIsLocal) { | |
818 | // and make sure it begins with one forward slash | |
819 | return preg_replace('_^/*(?=.)_', '/', $urlParts['path+query']); | |
820 | } | |
821 | ||
822 | // If the URL is external, then keep the full URL as supplied | |
823 | else { | |
824 | return $forceHttps ? preg_replace('_^http://_', 'https://', $url) : $url; | |
825 | } | |
826 | } | |
827 | ||
828 | /** | |
829 | * A simplified version of PHP's parse_url() function. | |
830 | * | |
831 | * @param string $url | |
832 | * e.g. "https://example.com:8000/foo/bar/?id=1#fragment" | |
833 | * | |
834 | * @return array | |
835 | * Will always contain keys 'host+port' and 'path+query', even if they're | |
836 | * empty strings. Example: | |
837 | * [ | |
838 | * 'host+port' => "example.com:8000", | |
839 | * 'path+query' => "/foo/bar/?id=1", | |
840 | * ] | |
841 | */ | |
842 | public static function simpleParseUrl($url) { | |
843 | $parts = parse_url($url); | |
2e1f50d6 | 844 | $host = $parts['host'] ?? ''; |
6c094ca6 | 845 | $port = isset($parts['port']) ? ':' . $parts['port'] : ''; |
2e1f50d6 | 846 | $path = $parts['path'] ?? ''; |
6c094ca6 | 847 | $query = isset($parts['query']) ? '?' . $parts['query'] : ''; |
be2fb01f | 848 | return [ |
6c094ca6 SM |
849 | 'host+port' => "$host$port", |
850 | 'path+query' => "$path$query", | |
be2fb01f | 851 | ]; |
6c094ca6 SM |
852 | } |
853 | ||
79a18c21 | 854 | /** |
fe482240 | 855 | * Formats a string of attributes for insertion in an html tag. |
79a18c21 CW |
856 | * |
857 | * @param array $attributes | |
858 | * | |
859 | * @return string | |
860 | */ | |
861 | public static function htmlAttributes($attributes) { | |
862 | $output = ''; | |
863 | foreach ($attributes as $name => $vals) { | |
864 | $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"'; | |
865 | } | |
866 | return ltrim($output); | |
867 | } | |
868 | ||
83d511e6 TO |
869 | /** |
870 | * Determine if $string starts with $fragment. | |
871 | * | |
872 | * @param string $string | |
873 | * The long string. | |
874 | * @param string $fragment | |
875 | * The fragment to look for. | |
876 | * @return bool | |
877 | */ | |
878 | public static function startsWith($string, $fragment) { | |
879 | if ($fragment === '') { | |
880 | return TRUE; | |
881 | } | |
882 | $len = strlen($fragment); | |
883 | return substr($string, 0, $len) === $fragment; | |
884 | } | |
885 | ||
886 | /** | |
887 | * Determine if $string ends with $fragment. | |
888 | * | |
889 | * @param string $string | |
890 | * The long string. | |
891 | * @param string $fragment | |
892 | * The fragment to look for. | |
893 | * @return bool | |
894 | */ | |
895 | public static function endsWith($string, $fragment) { | |
896 | if ($fragment === '') { | |
897 | return TRUE; | |
898 | } | |
899 | $len = strlen($fragment); | |
900 | return substr($string, -1 * $len) === $fragment; | |
901 | } | |
902 | ||
903 | /** | |
904 | * @param string|array $patterns | |
905 | * @param array $allStrings | |
906 | * @param bool $allowNew | |
907 | * Whether to return new, unrecognized names. | |
908 | * @return array | |
909 | */ | |
910 | public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) { | |
911 | $patterns = (array) $patterns; | |
be2fb01f | 912 | $result = []; |
83d511e6 TO |
913 | foreach ($patterns as $pattern) { |
914 | if (!\CRM_Utils_String::endsWith($pattern, '*')) { | |
915 | if ($allowNew || in_array($pattern, $allStrings)) { | |
916 | $result[] = $pattern; | |
917 | } | |
918 | } | |
919 | else { | |
920 | $prefix = rtrim($pattern, '*'); | |
921 | foreach ($allStrings as $key) { | |
922 | if (\CRM_Utils_String::startsWith($key, $prefix)) { | |
923 | $result[] = $key; | |
924 | } | |
925 | } | |
926 | } | |
927 | } | |
928 | return array_values(array_unique($result)); | |
929 | } | |
930 | ||
f24846d5 | 931 | /** |
dc7c2d3e SL |
932 | * Safely unserialize a string of scalar or array values (but not objects!) |
933 | * | |
934 | * Use `xkerman/restricted-unserialize` to unserialize strings using PHP's | |
935 | * serialization format. `restricted-unserialize` works like PHP's built-in | |
936 | * `unserialize` function except that it does not deserialize object instances, | |
937 | * making it immune to PHP Object Injection {@see https://www.owasp.org/index.php/PHP_Object_Injection} | |
938 | * vulnerabilities. | |
939 | * | |
940 | * Note: When dealing with user inputs, it is generally recommended to use | |
941 | * safe, standard data interchange formats such as JSON rather than PHP's | |
942 | * serialization format when dealing with user input. | |
943 | * | |
f24846d5 SL |
944 | * @param string|NULL $string |
945 | * | |
946 | * @return mixed | |
f24846d5 SL |
947 | */ |
948 | public static function unserialize($string) { | |
949 | if (!is_string($string)) { | |
950 | return FALSE; | |
951 | } | |
952 | try { | |
953 | return unserialize($string); | |
954 | } | |
955 | catch (UnserializeFailedException $e) { | |
079546f5 | 956 | return FALSE; |
f24846d5 | 957 | } |
dc7c2d3e | 958 | } |
f24846d5 | 959 | |
e3c6d5ff CW |
960 | /** |
961 | * Returns the plural form of an English word. | |
962 | * | |
963 | * @param string $str | |
964 | * @return string | |
965 | */ | |
966 | public static function pluralize($str) { | |
449c4e6b CW |
967 | $lastLetter = substr($str, -1); |
968 | $lastTwo = substr($str, -2); | |
e8b2a714 | 969 | if ($lastLetter == 's' || $lastLetter == 'x' || $lastTwo == 'ch') { |
449c4e6b CW |
970 | return $str . 'es'; |
971 | } | |
fb5d5e8a | 972 | if ($lastLetter == 'y' && !in_array($lastTwo, ['ay', 'ey', 'iy', 'oy', 'uy'])) { |
449c4e6b | 973 | return substr($str, 0, -1) . 'ies'; |
e3c6d5ff | 974 | } |
449c4e6b | 975 | return $str . 's'; |
e3c6d5ff CW |
976 | } |
977 | ||
1441a378 | 978 | /** |
979 | * Generic check as to whether any tokens are in the given string. | |
980 | * | |
981 | * It might be a smarty token OR a CiviCRM token. In both cases the | |
982 | * absence of a '{' indicates no token is present. | |
983 | * | |
984 | * @param string $string | |
985 | * | |
986 | * @return bool | |
987 | */ | |
988 | public static function stringContainsTokens(string $string) { | |
989 | return strpos($string, '{') !== FALSE; | |
990 | } | |
991 | ||
ab46cf18 | 992 | /** |
993 | * Parse a string through smarty without creating a smarty template file per string. | |
994 | * | |
995 | * This function is for swapping out any smarty tokens that appear in a string | |
996 | * and are not re-used much if at all. For example parsing a contact's greeting | |
997 | * does not need to be cached are there are some minor security / data privacy benefits | |
998 | * to not caching them per file. We also save disk space, reduce I/O and disk clearing time. | |
999 | * | |
1000 | * Doing this is cleaning in Smarty3 which we are alas not using | |
1001 | * https://www.smarty.net/docs/en/resources.string.tpl | |
1002 | * | |
1003 | * However, it highlights that smarty-eval is not evil-eval and still have the security applied. | |
1004 | * | |
1005 | * In order to replicate that in Smarty2 I'm using {eval} per | |
1006 | * https://www.smarty.net/docsv2/en/language.function.eval.tpl#id2820446 | |
1007 | * From the above: | |
1008 | * - Evaluated variables are treated the same as templates. They follow the same escapement and security features just as if they were templates. | |
1009 | * - Evaluated variables are compiled on every invocation, the compiled versions are not saved! However if you have caching enabled, the output | |
1010 | * will be cached with the rest of the template. | |
1011 | * | |
1012 | * Our set up does not have caching enabled and my testing suggests this still works fine with it | |
1013 | * enabled so turning it off before running this is out of caution based on the above. | |
1014 | * | |
1015 | * When this function is run only one template file is created (for the eval) tag no matter how | |
1016 | * many times it is run. This compares to it otherwise creating one file for every parsed string. | |
1017 | * | |
1018 | * @param string $templateString | |
1019 | * | |
1020 | * @return string | |
1021 | */ | |
1022 | public static function parseOneOffStringThroughSmarty($templateString) { | |
1023 | if (!CRM_Utils_String::stringContainsTokens($templateString)) { | |
1024 | // Skip expensive smarty processing. | |
1025 | return $templateString; | |
1026 | } | |
1027 | $smarty = CRM_Core_Smarty::singleton(); | |
1028 | $cachingValue = $smarty->caching; | |
1029 | $smarty->caching = 0; | |
1030 | $smarty->assign('smartySingleUseString', $templateString); | |
1031 | $templateString = $smarty->fetch('string:{eval var=$smartySingleUseString}'); | |
1032 | $smarty->caching = $cachingValue; | |
1033 | $smarty->assign('smartySingleUseString', NULL); | |
1034 | return $templateString; | |
1035 | } | |
1036 | ||
6a488035 | 1037 | } |