Merge pull request #15326 from totten/master-headfoot-2
[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 require_once 'HTML/QuickForm/Rule/Email.php';
19
20 /**
21 * This class contains string functions.
22 */
23 class CRM_Utils_String {
24 const COMMA = ",", SEMICOLON = ";", SPACE = " ", TAB = "\t", LINEFEED = "\n", CARRIAGELINE = "\r\n", LINECARRIAGE = "\n\r", CARRIAGERETURN = "\r";
25
26 /**
27 * List of all letters and numbers
28 */
29 const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
30
31 /**
32 * Convert a display name into a potential variable name.
33 *
34 * @param string $title title of the string
35 * @param int $maxLength
36 *
37 * @return string
38 * An equivalent variable name.
39 */
40 public static function titleToVar($title, $maxLength = 31) {
41 $variable = self::munge($title, '_', $maxLength);
42
43 if (CRM_Utils_Rule::title($variable, $maxLength)) {
44 return $variable;
45 }
46
47 // if longer than the maxLength lets just return a substr of the
48 // md5 to prevent errors downstream
49 return substr(md5($title), 0, $maxLength);
50 }
51
52 /**
53 * Replace all non alpha numeric characters and spaces with the replacement character.
54 *
55 * @param string $name
56 * The name to be worked on.
57 * @param string $char
58 * The character to use for non-valid chars.
59 * @param int $len
60 * Length of valid variables.
61 *
62 * @return string
63 * returns the manipulated string
64 */
65 public static function munge($name, $char = '_', $len = 63) {
66 // Replace all white space and non-alpha numeric with $char
67 // we only use the ascii character set since mysql does not create table names / field names otherwise
68 // CRM-11744
69 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
70
71 //If there are no ascii characters present.
72 if ($name == $char) {
73 $name = self::createRandom($len, self::ALPHANUMERIC);
74 }
75
76 if ($len) {
77 // lets keep variable names short
78 return substr($name, 0, $len);
79 }
80 else {
81 return $name;
82 }
83 }
84
85 /**
86 * Convert possibly underscore separated words to camel case with special handling for 'UF'
87 * e.g membership_payment returns MembershipPayment
88 *
89 * @param string $string
90 *
91 * @return string
92 */
93 public static function convertStringToCamel($string) {
94 $map = [
95 'acl' => 'Acl',
96 'ACL' => 'Acl',
97 'im' => 'Im',
98 'IM' => 'Im',
99 ];
100 if (isset($map[$string])) {
101 return $map[$string];
102 }
103
104 $fragments = explode('_', $string);
105 foreach ($fragments as & $fragment) {
106 $fragment = ucfirst($fragment);
107 // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in without underscores)
108 if (strpos($fragment, 'Uf') === 0 && strlen($string) > 2) {
109 $fragment = 'UF' . ucfirst(substr($fragment, 2));
110 }
111 }
112 // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in underscore-separated)
113 if ($fragments[0] === 'Uf') {
114 $fragments[0] = 'UF';
115 }
116 return implode('', $fragments);
117 }
118
119 /**
120 * Takes a variable name and munges it randomly into another variable name.
121 *
122 * @param string $name
123 * Initial Variable Name.
124 * @param int $len
125 * Length of valid variables.
126 *
127 * @return string
128 * Randomized Variable Name
129 */
130 public static function rename($name, $len = 4) {
131 $rand = substr(uniqid(), 0, $len);
132 return substr_replace($name, $rand, -$len, $len);
133 }
134
135 /**
136 * Takes a string and returns the last tuple of the string.
137 *
138 * Useful while converting file names to class names etc
139 *
140 * @param string $string
141 * The input string.
142 * @param string $char
143 * Character used to demarcate the components
144 *
145 * @return string
146 * The last component
147 */
148 public static function getClassName($string, $char = '_') {
149 $names = [];
150 if (!is_array($string)) {
151 $names = explode($char, $string);
152 }
153 if (!empty($names)) {
154 return array_pop($names);
155 }
156 }
157
158 /**
159 * Appends a name to a string and separated by delimiter.
160 *
161 * Does the right thing for an empty string
162 *
163 * @param string $str
164 * The string to be appended to.
165 * @param string $delim
166 * The delimiter to use.
167 * @param mixed $name
168 * The string (or array of strings) to append.
169 */
170 public static function append(&$str, $delim, $name) {
171 if (empty($name)) {
172 return;
173 }
174
175 if (is_array($name)) {
176 foreach ($name as $n) {
177 if (empty($n)) {
178 continue;
179 }
180 if (empty($str)) {
181 $str = $n;
182 }
183 else {
184 $str .= $delim . $n;
185 }
186 }
187 }
188 else {
189 if (empty($str)) {
190 $str = $name;
191 }
192 else {
193 $str .= $delim . $name;
194 }
195 }
196 }
197
198 /**
199 * Determine if the string is composed only of ascii characters.
200 *
201 * @param string $str
202 * Input string.
203 * @param bool $utf8
204 * Attempt utf8 match on failure (default yes).
205 *
206 * @return bool
207 * true if string is ascii
208 */
209 public static function isAscii($str, $utf8 = TRUE) {
210 if (!function_exists('mb_detect_encoding')) {
211 // eliminate all white space from the string
212 $str = preg_replace('/\s+/', '', $str);
213 // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work.
214
215 // match low- or high-ascii characters
216 if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) {
217 // || // low ascii characters
218 // high ascii characters
219 // preg_match( '/[\x7F-\xFF]/', $str ) ) {
220 if ($utf8) {
221 // if we did match, try for utf-8, or iso8859-1
222
223 return self::isUtf8($str);
224 }
225 else {
226 return FALSE;
227 }
228 }
229 return TRUE;
230 }
231 else {
232 $order = ['ASCII'];
233 if ($utf8) {
234 $order[] = 'UTF-8';
235 }
236 $enc = mb_detect_encoding($str, $order, TRUE);
237 return ($enc == 'ASCII' || $enc == 'UTF-8');
238 }
239 }
240
241 /**
242 * Determine the string replacements for redaction.
243 * on the basis of the regular expressions
244 *
245 * @param string $str
246 * Input string.
247 * @param array $regexRules
248 * Regular expression to be matched w/ replacements.
249 *
250 * @return array
251 * array of strings w/ corresponding redacted outputs
252 */
253 public static function regex($str, $regexRules) {
254 // redact the regular expressions
255 if (!empty($regexRules) && isset($str)) {
256 static $matches, $totalMatches, $match = [];
257 foreach ($regexRules as $pattern => $replacement) {
258 preg_match_all($pattern, $str, $matches);
259 if (!empty($matches[0])) {
260 if (empty($totalMatches)) {
261 $totalMatches = $matches[0];
262 }
263 else {
264 $totalMatches = array_merge($totalMatches, $matches[0]);
265 }
266 $match = array_flip($totalMatches);
267 }
268 }
269 }
270
271 if (!empty($match)) {
272 foreach ($match as $matchKey => & $dontCare) {
273 foreach ($regexRules as $pattern => $replacement) {
274 if (preg_match($pattern, $matchKey)) {
275 $dontCare = $replacement . substr(md5($matchKey), 0, 5);
276 break;
277 }
278 }
279 }
280 return $match;
281 }
282 return [];
283 }
284
285 /**
286 * @param $str
287 * @param $stringRules
288 *
289 * @return mixed
290 */
291 public static function redaction($str, $stringRules) {
292 // redact the strings
293 if (!empty($stringRules)) {
294 foreach ($stringRules as $match => $replace) {
295 $str = str_ireplace($match, $replace, $str);
296 }
297 }
298
299 // return the redacted output
300 return $str;
301 }
302
303 /**
304 * Determine if a string is composed only of utf8 characters
305 *
306 * @param string $str
307 * Input string.
308 *
309 * @return bool
310 */
311 public static function isUtf8($str) {
312 if (!function_exists(mb_detect_encoding)) {
313 // eliminate all white space from the string
314 $str = preg_replace('/\s+/', '', $str);
315
316 // pattern stolen from the php.net function documentation for
317 // utf8decode();
318 // comment by JF Sebastian, 30-Mar-2005
319 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);
320 // ||
321 // iconv('ISO-8859-1', 'UTF-8', $str);
322 }
323 else {
324 $enc = mb_detect_encoding($str, ['UTF-8'], TRUE);
325 return ($enc !== FALSE);
326 }
327 }
328
329 /**
330 * Determine if two hrefs are equivalent (fuzzy match)
331 *
332 * @param string $url1
333 * The first url to be matched.
334 * @param string $url2
335 * The second url to be matched against.
336 *
337 * @return bool
338 * true if the urls match, else false
339 */
340 public static function match($url1, $url2) {
341 $url1 = strtolower($url1);
342 $url2 = strtolower($url2);
343
344 $url1Str = parse_url($url1);
345 $url2Str = parse_url($url2);
346
347 if ($url1Str['path'] == $url2Str['path'] &&
348 self::extractURLVarValue(CRM_Utils_Array::value('query', $url1Str)) == self::extractURLVarValue(CRM_Utils_Array::value('query', $url2Str))
349 ) {
350 return TRUE;
351 }
352 return FALSE;
353 }
354
355 /**
356 * Extract the civicrm path from the url.
357 *
358 * @param string $query
359 * A url string.
360 *
361 * @return string|null
362 * civicrm url (eg: civicrm/contact/search)
363 */
364 public static function extractURLVarValue($query) {
365 $config = CRM_Core_Config::singleton();
366 $urlVar = $config->userFrameworkURLVar;
367
368 $params = explode('&', $query);
369 foreach ($params as $p) {
370 if (strpos($p, '=')) {
371 list($k, $v) = explode('=', $p);
372 if ($k == $urlVar) {
373 return $v;
374 }
375 }
376 }
377 return NULL;
378 }
379
380 /**
381 * Translate a true/false/yes/no string to a 0 or 1 value
382 *
383 * @param string $str
384 * The string to be translated.
385 *
386 * @return bool
387 */
388 public static function strtobool($str) {
389 if (!is_scalar($str)) {
390 return FALSE;
391 }
392
393 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
394 return TRUE;
395 }
396 return FALSE;
397 }
398
399 /**
400 * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
401 *
402 * @param string $str
403 * The string to be translated.
404 *
405 * @return bool
406 */
407 public static function strtoboolstr($str) {
408 if (!is_scalar($str)) {
409 return FALSE;
410 }
411
412 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
413 return '1';
414 }
415 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
416 return '0';
417 }
418 else {
419 return FALSE;
420 }
421 }
422
423 /**
424 * Convert a HTML string into a text one using html2text
425 *
426 * @param string $html
427 * The string to be converted.
428 *
429 * @return string
430 * the converted string
431 */
432 public static function htmlToText($html) {
433 require_once 'packages/html2text/rcube_html2text.php';
434 $token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html);
435 $converter = new rcube_html2text($token_html);
436 $token_text = $converter->get_text();
437 $text = preg_replace('!token\:\{([a-z_.]+)\}!i', '{$1}', $token_text);
438 return $text;
439 }
440
441 /**
442 * @param $string
443 * @param array $params
444 */
445 public static function extractName($string, &$params) {
446 $name = trim($string);
447 if (empty($name)) {
448 return;
449 }
450
451 // strip out quotes
452 $name = str_replace('"', '', $name);
453 $name = str_replace('\'', '', $name);
454
455 // check for comma in name
456 if (strpos($name, ',') !== FALSE) {
457
458 // name has a comma - assume lname, fname [mname]
459 $names = explode(',', $name);
460 if (count($names) > 1) {
461 $params['last_name'] = trim($names[0]);
462
463 // check for space delim
464 $fnames = explode(' ', trim($names[1]));
465 if (count($fnames) > 1) {
466 $params['first_name'] = trim($fnames[0]);
467 $params['middle_name'] = trim($fnames[1]);
468 }
469 else {
470 $params['first_name'] = trim($fnames[0]);
471 }
472 }
473 else {
474 $params['first_name'] = trim($names[0]);
475 }
476 }
477 else {
478 // name has no comma - assume fname [mname] fname
479 $names = explode(' ', $name);
480 if (count($names) == 1) {
481 $params['first_name'] = $names[0];
482 }
483 elseif (count($names) == 2) {
484 $params['first_name'] = $names[0];
485 $params['last_name'] = $names[1];
486 }
487 else {
488 $params['first_name'] = $names[0];
489 $params['middle_name'] = $names[1];
490 $params['last_name'] = $names[2];
491 }
492 }
493 }
494
495 /**
496 * @param $string
497 *
498 * @return array
499 */
500 public static function &makeArray($string) {
501 $string = trim($string);
502
503 $values = explode("\n", $string);
504 $result = [];
505 foreach ($values as $value) {
506 list($n, $v) = CRM_Utils_System::explode('=', $value, 2);
507 if (!empty($v)) {
508 $result[trim($n)] = trim($v);
509 }
510 }
511 return $result;
512 }
513
514 /**
515 * Given an ezComponents-parsed representation of
516 * a text with alternatives return only the first one
517 *
518 * @param string $full
519 * All alternatives as a long string (or some other text).
520 *
521 * @return string
522 * only the first alternative found (or the text without alternatives)
523 */
524 public static function stripAlternatives($full) {
525 $matches = [];
526 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
527
528 if (isset($matches[1]) &&
529 trim(strip_tags($matches[1])) != ''
530 ) {
531 return $matches[1];
532 }
533 else {
534 return $full;
535 }
536 }
537
538 /**
539 * Strip leading, trailing, double spaces from string
540 * used for postal/greeting/addressee
541 *
542 * @param string $string
543 * Input string to be cleaned.
544 *
545 * @return string
546 * the cleaned string
547 */
548 public static function stripSpaces($string) {
549 return (empty($string)) ? $string : preg_replace("/\s{2,}/", " ", trim($string));
550 }
551
552 /**
553 * clean the URL 'path' variable that we use
554 * to construct CiviCRM urls by removing characters from the path variable
555 *
556 * @param string $string
557 * The input string to be sanitized.
558 * @param array $search
559 * The characters to be sanitized.
560 * @param string $replace
561 * The character to replace it with.
562 *
563 * @return string
564 * the sanitized string
565 */
566 public static function stripPathChars(
567 $string,
568 $search = NULL,
569 $replace = NULL
570 ) {
571 static $_searchChars = NULL;
572 static $_replaceChar = NULL;
573
574 if (empty($string)) {
575 return $string;
576 }
577
578 if ($_searchChars == NULL) {
579 $_searchChars = [
580 '&',
581 ';',
582 ',',
583 '=',
584 '$',
585 '"',
586 "'",
587 '\\',
588 '<',
589 '>',
590 '(',
591 ')',
592 ' ',
593 "\r",
594 "\r\n",
595 "\n",
596 "\t",
597 ];
598 $_replaceChar = '_';
599 }
600
601 if ($search == NULL) {
602 $search = $_searchChars;
603 }
604
605 if ($replace == NULL) {
606 $replace = $_replaceChar;
607 }
608
609 return str_replace($search, $replace, $string);
610 }
611
612 /**
613 * Use HTMLPurifier to clean up a text string and remove any potential
614 * xss attacks. This is primarily used in public facing pages which
615 * accept html as the input string
616 *
617 * @param string $string
618 * The input string.
619 *
620 * @return string
621 * the cleaned up string
622 */
623 public static function purifyHTML($string) {
624 static $_filter = NULL;
625 if (!$_filter) {
626 $config = HTMLPurifier_Config::createDefault();
627 $config->set('Core.Encoding', 'UTF-8');
628 $config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']);
629
630 // Disable the cache entirely
631 $config->set('Cache.DefinitionImpl', NULL);
632
633 $_filter = new HTMLPurifier($config);
634 }
635
636 return $_filter->purify($string);
637 }
638
639 /**
640 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
641 *
642 * @param string $string
643 * @param int $maxLen
644 *
645 * @return string
646 */
647 public static function ellipsify($string, $maxLen) {
648 if (mb_strlen($string, 'UTF-8') <= $maxLen) {
649 return $string;
650 }
651 return mb_substr($string, 0, $maxLen - 3, 'UTF-8') . '...';
652 }
653
654 /**
655 * Generate a random string.
656 *
657 * @param $len
658 * @param $alphabet
659 * @return string
660 */
661 public static function createRandom($len, $alphabet) {
662 $alphabetSize = strlen($alphabet);
663 $result = '';
664 for ($i = 0; $i < $len; $i++) {
665 $result .= $alphabet{rand(1, $alphabetSize) - 1};
666 }
667 return $result;
668 }
669
670 /**
671 * Examples:
672 * "admin foo" => array(NULL,"admin foo")
673 * "cms:admin foo" => array("cms", "admin foo")
674 *
675 * @param $delim
676 * @param string $string
677 * E.g. "view all contacts". Syntax: "[prefix:]name".
678 * @param null $defaultPrefix
679 *
680 * @return array
681 * (0 => string|NULL $prefix, 1 => string $value)
682 */
683 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
684 $pos = strpos($string, $delim);
685 if ($pos === FALSE) {
686 return [$defaultPrefix, $string];
687 }
688 else {
689 return [substr($string, 0, $pos), substr($string, 1 + $pos)];
690 }
691 }
692
693 /**
694 * This function will mask part of the the user portion of an Email address (everything before the @)
695 *
696 * @param string $email
697 * The email address to be masked.
698 * @param string $maskChar
699 * The character used for masking.
700 * @param int $percent
701 * The percentage of the user portion to be masked.
702 *
703 * @return string
704 * returns the masked Email address
705 */
706 public static function maskEmail($email, $maskChar = '*', $percent = 50) {
707 list($user, $domain) = preg_split("/@/", $email);
708 $len = strlen($user);
709 $maskCount = floor($len * $percent / 100);
710 $offset = floor(($len - $maskCount) / 2);
711
712 $masked = substr($user, 0, $offset)
713 . str_repeat($maskChar, $maskCount)
714 . substr($user, $maskCount + $offset);
715
716 return ($masked . '@' . $domain);
717 }
718
719 /**
720 * This function compares two strings.
721 *
722 * @param string $strOne
723 * String one.
724 * @param string $strTwo
725 * String two.
726 * @param bool $case
727 * Boolean indicating whether you want the comparison to be case sensitive or not.
728 *
729 * @return bool
730 * TRUE (string are identical); FALSE (strings are not identical)
731 */
732 public static function compareStr($strOne, $strTwo, $case) {
733 if ($case == TRUE) {
734 // Convert to lowercase and trim white spaces
735 if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) {
736 // yes - they are identical
737 return TRUE;
738 }
739 else {
740 // not identical
741 return FALSE;
742 }
743 }
744 if ($case == FALSE) {
745 // Trim white spaces
746 if (trim($strOne) == trim($strTwo)) {
747 // yes - they are identical
748 return TRUE;
749 }
750 else {
751 // not identical
752 return FALSE;
753 }
754 }
755 }
756
757 /**
758 * Many parts of the codebase have a convention of internally passing around
759 * HTML-encoded URLs. This effectively means that "&" is replaced by "&amp;"
760 * (because most other odd characters are %-escaped in URLs; and %-escaped
761 * strings don't need any extra escaping in HTML).
762 *
763 * @param string $htmlUrl
764 * URL with HTML entities.
765 * @return string
766 * URL without HTML entities
767 */
768 public static function unstupifyUrl($htmlUrl) {
769 return str_replace('&amp;', '&', $htmlUrl);
770 }
771
772 /**
773 * When a user supplies a URL (e.g. to an image), we'd like to:
774 * - Remove the protocol and domain name if the URL points to the current
775 * site.
776 * - Keep the domain name for remote URLs.
777 * - Optionally, force remote URLs to use https instead of http (which is
778 * useful for images)
779 *
780 * @param string $url
781 * The URL to simplify. Examples:
782 * "https://example.org/sites/default/files/coffee-mug.jpg"
783 * "sites/default/files/coffee-mug.jpg"
784 * "http://i.stack.imgur.com/9jb2ial01b.png"
785 * @param bool $forceHttps = FALSE
786 * If TRUE, ensure that remote URLs use https. If a URL with
787 * http is supplied, then we'll change it to https.
788 * This is useful for situations like showing a premium product on a
789 * contribution, because (as reported in CRM-14283) if the user gets a
790 * browser warning like "page contains insecure elements" on a contribution
791 * page, that's a very bad thing. Thus, even if changing http to https
792 * breaks the image, that's better than leaving http content in a
793 * contribution page.
794 *
795 * @return string
796 * The simplified URL. Examples:
797 * "/sites/default/files/coffee-mug.jpg"
798 * "https://i.stack.imgur.com/9jb2ial01b.png"
799 */
800 public static function simplifyURL($url, $forceHttps = FALSE) {
801 $config = CRM_Core_Config::singleton();
802 $siteURLParts = self::simpleParseUrl($config->userFrameworkBaseURL);
803 $urlParts = self::simpleParseUrl($url);
804
805 // If the image is locally hosted, then only give the path to the image
806 $urlIsLocal
807 = ($urlParts['host+port'] == '')
808 | ($urlParts['host+port'] == $siteURLParts['host+port']);
809 if ($urlIsLocal) {
810 // and make sure it begins with one forward slash
811 return preg_replace('_^/*(?=.)_', '/', $urlParts['path+query']);
812 }
813
814 // If the URL is external, then keep the full URL as supplied
815 else {
816 return $forceHttps ? preg_replace('_^http://_', 'https://', $url) : $url;
817 }
818 }
819
820 /**
821 * A simplified version of PHP's parse_url() function.
822 *
823 * @param string $url
824 * e.g. "https://example.com:8000/foo/bar/?id=1#fragment"
825 *
826 * @return array
827 * Will always contain keys 'host+port' and 'path+query', even if they're
828 * empty strings. Example:
829 * [
830 * 'host+port' => "example.com:8000",
831 * 'path+query' => "/foo/bar/?id=1",
832 * ]
833 */
834 public static function simpleParseUrl($url) {
835 $parts = parse_url($url);
836 $host = isset($parts['host']) ? $parts['host'] : '';
837 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
838 $path = isset($parts['path']) ? $parts['path'] : '';
839 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
840 return [
841 'host+port' => "$host$port",
842 'path+query' => "$path$query",
843 ];
844 }
845
846 /**
847 * Formats a string of attributes for insertion in an html tag.
848 *
849 * @param array $attributes
850 *
851 * @return string
852 */
853 public static function htmlAttributes($attributes) {
854 $output = '';
855 foreach ($attributes as $name => $vals) {
856 $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"';
857 }
858 return ltrim($output);
859 }
860
861 /**
862 * Determine if $string starts with $fragment.
863 *
864 * @param string $string
865 * The long string.
866 * @param string $fragment
867 * The fragment to look for.
868 * @return bool
869 */
870 public static function startsWith($string, $fragment) {
871 if ($fragment === '') {
872 return TRUE;
873 }
874 $len = strlen($fragment);
875 return substr($string, 0, $len) === $fragment;
876 }
877
878 /**
879 * Determine if $string ends with $fragment.
880 *
881 * @param string $string
882 * The long string.
883 * @param string $fragment
884 * The fragment to look for.
885 * @return bool
886 */
887 public static function endsWith($string, $fragment) {
888 if ($fragment === '') {
889 return TRUE;
890 }
891 $len = strlen($fragment);
892 return substr($string, -1 * $len) === $fragment;
893 }
894
895 /**
896 * @param string|array $patterns
897 * @param array $allStrings
898 * @param bool $allowNew
899 * Whether to return new, unrecognized names.
900 * @return array
901 */
902 public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) {
903 $patterns = (array) $patterns;
904 $result = [];
905 foreach ($patterns as $pattern) {
906 if (!\CRM_Utils_String::endsWith($pattern, '*')) {
907 if ($allowNew || in_array($pattern, $allStrings)) {
908 $result[] = $pattern;
909 }
910 }
911 else {
912 $prefix = rtrim($pattern, '*');
913 foreach ($allStrings as $key) {
914 if (\CRM_Utils_String::startsWith($key, $prefix)) {
915 $result[] = $key;
916 }
917 }
918 }
919 }
920 return array_values(array_unique($result));
921 }
922
923 }