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