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