3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 require_once 'HTML/QuickForm/Rule/Email.php';
21 * This class contains string functions.
23 class CRM_Utils_String
{
24 const COMMA
= ",", SEMICOLON
= ";", SPACE
= " ", TAB
= "\t", LINEFEED
= "\n", CARRIAGELINE
= "\r\n", LINECARRIAGE
= "\n\r", CARRIAGERETURN
= "\r";
27 * List of all letters and numbers
29 const ALPHANUMERIC
= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
32 * Convert a display name into a potential variable name.
34 * @param string $title title of the string
35 * @param int $maxLength
38 * An equivalent variable name.
40 public static function titleToVar($title, $maxLength = 31) {
41 $variable = self
::munge($title, '_', $maxLength);
43 if (CRM_Utils_Rule
::title($variable, $maxLength)) {
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);
53 * Replace all non alpha numeric characters and spaces with the replacement character.
56 * The name to be worked on.
58 * The character to use for non-valid chars.
60 * Length of valid variables.
63 * returns the manipulated string
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
69 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
71 //If there are no ascii characters present.
73 $name = self
::createRandom($len, self
::ALPHANUMERIC
);
77 // lets keep variable names short
78 return substr($name, 0, $len);
86 * Convert possibly underscore separated words to camel case with special handling for 'UF'
87 * e.g membership_payment returns MembershipPayment
89 * @param string $string
93 public static function convertStringToCamel($string) {
100 if (isset($map[$string])) {
101 return $map[$string];
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));
112 // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in underscore-separated)
113 if ($fragments[0] === 'Uf') {
114 $fragments[0] = 'UF';
116 return implode('', $fragments);
120 * Takes a variable name and munges it randomly into another variable name.
122 * @param string $name
123 * Initial Variable Name.
125 * Length of valid variables.
128 * Randomized Variable Name
130 public static function rename($name, $len = 4) {
131 $rand = substr(uniqid(), 0, $len);
132 return substr_replace($name, $rand, -$len, $len);
136 * Takes a string and returns the last tuple of the string.
138 * Useful while converting file names to class names etc
140 * @param string $string
142 * @param string $char
143 * Character used to demarcate the components
148 public static function getClassName($string, $char = '_') {
150 if (!is_array($string)) {
151 $names = explode($char, $string);
153 if (!empty($names)) {
154 return array_pop($names);
159 * Appends a name to a string and separated by delimiter.
161 * Does the right thing for an empty string
164 * The string to be appended to.
165 * @param string $delim
166 * The delimiter to use.
168 * The string (or array of strings) to append.
170 public static function append(&$str, $delim, $name) {
175 if (is_array($name)) {
176 foreach ($name as $n) {
193 $str .= $delim . $name;
199 * Determine if the string is composed only of ascii characters.
204 * Attempt utf8 match on failure (default yes).
207 * true if string is ascii
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.
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 ) ) {
221 // if we did match, try for utf-8, or iso8859-1
223 return self
::isUtf8($str);
236 $enc = mb_detect_encoding($str, $order, TRUE);
237 return ($enc == 'ASCII' ||
$enc == 'UTF-8');
242 * Determine the string replacements for redaction.
243 * on the basis of the regular expressions
247 * @param array $regexRules
248 * Regular expression to be matched w/ replacements.
251 * array of strings w/ corresponding redacted outputs
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];
264 $totalMatches = array_merge($totalMatches, $matches[0]);
266 $match = array_flip($totalMatches);
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);
287 * @param $stringRules
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);
299 // return the redacted output
304 * Determine if a string is composed only of utf8 characters
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);
316 // pattern stolen from the php.net function documentation for
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);
321 // iconv('ISO-8859-1', 'UTF-8', $str);
324 $enc = mb_detect_encoding($str, ['UTF-8'], TRUE);
325 return ($enc !== FALSE);
330 * Determine if two hrefs are equivalent (fuzzy match)
332 * @param string $url1
333 * The first url to be matched.
334 * @param string $url2
335 * The second url to be matched against.
338 * true if the urls match, else false
340 public static function match($url1, $url2) {
341 $url1 = strtolower($url1);
342 $url2 = strtolower($url2);
344 $url1Str = parse_url($url1);
345 $url2Str = parse_url($url2);
347 if ($url1Str['path'] == $url2Str['path'] &&
348 self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url1Str)) == self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url2Str))
356 * Extract the civicrm path from the url.
358 * @param string $query
361 * @return string|null
362 * civicrm url (eg: civicrm/contact/search)
364 public static function extractURLVarValue($query) {
365 $config = CRM_Core_Config
::singleton();
366 $urlVar = $config->userFrameworkURLVar
;
368 $params = explode('&', $query);
369 foreach ($params as $p) {
370 if (strpos($p, '=')) {
371 list($k, $v) = explode('=', $p);
381 * Translate a true/false/yes/no string to a 0 or 1 value
384 * The string to be translated.
388 public static function strtobool($str) {
389 if (!is_scalar($str)) {
393 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
400 * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
403 * The string to be translated.
407 public static function strtoboolstr($str) {
408 if (!is_scalar($str)) {
412 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
415 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
424 * Convert a HTML string into a text one using html2text
426 * @param string $html
427 * The string to be converted.
430 * the converted string
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);
443 * @param array $params
445 public static function extractName($string, &$params) {
446 $name = trim($string);
452 $name = str_replace('"', '', $name);
453 $name = str_replace('\'', '', $name);
455 // check for comma in name
456 if (strpos($name, ',') !== FALSE) {
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]);
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]);
470 $params['first_name'] = trim($fnames[0]);
474 $params['first_name'] = trim($names[0]);
478 // name has no comma - assume fname [mname] fname
479 $names = explode(' ', $name);
480 if (count($names) == 1) {
481 $params['first_name'] = $names[0];
483 elseif (count($names) == 2) {
484 $params['first_name'] = $names[0];
485 $params['last_name'] = $names[1];
488 $params['first_name'] = $names[0];
489 $params['middle_name'] = $names[1];
490 $params['last_name'] = $names[2];
500 public static function &makeArray($string) {
501 $string = trim($string);
503 $values = explode("\n", $string);
505 foreach ($values as $value) {
506 list($n, $v) = CRM_Utils_System
::explode('=', $value, 2);
508 $result[trim($n)] = trim($v);
515 * Given an ezComponents-parsed representation of
516 * a text with alternatives return only the first one
518 * @param string $full
519 * All alternatives as a long string (or some other text).
522 * only the first alternative found (or the text without alternatives)
524 public static function stripAlternatives($full) {
526 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
528 if (isset($matches[1]) &&
529 trim(strip_tags($matches[1])) != ''
539 * Strip leading, trailing, double spaces from string
540 * used for postal/greeting/addressee
542 * @param string $string
543 * Input string to be cleaned.
548 public static function stripSpaces($string) {
549 return (empty($string)) ?
$string : preg_replace("/\s{2,}/", " ", trim($string));
553 * clean the URL 'path' variable that we use
554 * to construct CiviCRM urls by removing characters from the path variable
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.
564 * the sanitized string
566 public static function stripPathChars(
571 static $_searchChars = NULL;
572 static $_replaceChar = NULL;
574 if (empty($string)) {
578 if ($_searchChars == NULL) {
601 if ($search == NULL) {
602 $search = $_searchChars;
605 if ($replace == NULL) {
606 $replace = $_replaceChar;
609 return str_replace($search, $replace, $string);
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
617 * @param string $string
621 * the cleaned up string
623 public static function purifyHTML($string) {
624 static $_filter = NULL;
626 $config = HTMLPurifier_Config
::createDefault();
627 $config->set('Core.Encoding', 'UTF-8');
628 $config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']);
630 // Disable the cache entirely
631 $config->set('Cache.DefinitionImpl', NULL);
633 $_filter = new HTMLPurifier($config);
636 return $_filter->purify($string);
640 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
642 * @param string $string
647 public static function ellipsify($string, $maxLen) {
648 if (mb_strlen($string, 'UTF-8') <= $maxLen) {
651 return mb_substr($string, 0, $maxLen - 3, 'UTF-8') . '...';
655 * Generate a random string.
661 public static function createRandom($len, $alphabet) {
662 $alphabetSize = strlen($alphabet);
664 for ($i = 0; $i < $len; $i++
) {
665 $result .= $alphabet{rand(1, $alphabetSize) - 1};
672 * "admin foo" => array(NULL,"admin foo")
673 * "cms:admin foo" => array("cms", "admin foo")
676 * @param string $string
677 * E.g. "view all contacts". Syntax: "[prefix:]name".
678 * @param null $defaultPrefix
681 * (0 => string|NULL $prefix, 1 => string $value)
683 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
684 $pos = strpos($string, $delim);
685 if ($pos === FALSE) {
686 return [$defaultPrefix, $string];
689 return [substr($string, 0, $pos), substr($string, 1 +
$pos)];
694 * This function will mask part of the the user portion of an Email address (everything before the @)
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.
704 * returns the masked Email address
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);
712 $masked = substr($user, 0, $offset)
713 . str_repeat($maskChar, $maskCount)
714 . substr($user, $maskCount +
$offset);
716 return ($masked . '@' . $domain);
720 * This function compares two strings.
722 * @param string $strOne
724 * @param string $strTwo
727 * Boolean indicating whether you want the comparison to be case sensitive or not.
730 * TRUE (string are identical); FALSE (strings are not identical)
732 public static function compareStr($strOne, $strTwo, $case) {
734 // Convert to lowercase and trim white spaces
735 if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) {
736 // yes - they are identical
744 if ($case == FALSE) {
746 if (trim($strOne) == trim($strTwo)) {
747 // yes - they are identical
758 * Many parts of the codebase have a convention of internally passing around
759 * HTML-encoded URLs. This effectively means that "&" is replaced by "&"
760 * (because most other odd characters are %-escaped in URLs; and %-escaped
761 * strings don't need any extra escaping in HTML).
763 * @param string $htmlUrl
764 * URL with HTML entities.
766 * URL without HTML entities
768 public static function unstupifyUrl($htmlUrl) {
769 return str_replace('&', '&', $htmlUrl);
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
776 * - Keep the domain name for remote URLs.
777 * - Optionally, force remote URLs to use https instead of http (which is
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
796 * The simplified URL. Examples:
797 * "/sites/default/files/coffee-mug.jpg"
798 * "https://i.stack.imgur.com/9jb2ial01b.png"
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);
805 // If the image is locally hosted, then only give the path to the image
807 = ($urlParts['host+port'] == '')
808 |
($urlParts['host+port'] == $siteURLParts['host+port']);
810 // and make sure it begins with one forward slash
811 return preg_replace('_^/*(?=.)_', '/', $urlParts['path+query']);
814 // If the URL is external, then keep the full URL as supplied
816 return $forceHttps ?
preg_replace('_^http://_', 'https://', $url) : $url;
821 * A simplified version of PHP's parse_url() function.
824 * e.g. "https://example.com:8000/foo/bar/?id=1#fragment"
827 * Will always contain keys 'host+port' and 'path+query', even if they're
828 * empty strings. Example:
830 * 'host+port' => "example.com:8000",
831 * 'path+query' => "/foo/bar/?id=1",
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'] : '';
841 'host+port' => "$host$port",
842 'path+query' => "$path$query",
847 * Formats a string of attributes for insertion in an html tag.
849 * @param array $attributes
853 public static function htmlAttributes($attributes) {
855 foreach ($attributes as $name => $vals) {
856 $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"';
858 return ltrim($output);
862 * Determine if $string starts with $fragment.
864 * @param string $string
866 * @param string $fragment
867 * The fragment to look for.
870 public static function startsWith($string, $fragment) {
871 if ($fragment === '') {
874 $len = strlen($fragment);
875 return substr($string, 0, $len) === $fragment;
879 * Determine if $string ends with $fragment.
881 * @param string $string
883 * @param string $fragment
884 * The fragment to look for.
887 public static function endsWith($string, $fragment) {
888 if ($fragment === '') {
891 $len = strlen($fragment);
892 return substr($string, -1 * $len) === $fragment;
896 * @param string|array $patterns
897 * @param array $allStrings
898 * @param bool $allowNew
899 * Whether to return new, unrecognized names.
902 public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) {
903 $patterns = (array) $patterns;
905 foreach ($patterns as $pattern) {
906 if (!\CRM_Utils_String
::endsWith($pattern, '*')) {
907 if ($allowNew ||
in_array($pattern, $allStrings)) {
908 $result[] = $pattern;
912 $prefix = rtrim($pattern, '*');
913 foreach ($allStrings as $key) {
914 if (\CRM_Utils_String
::startsWith($key, $prefix)) {
920 return array_values(array_unique($result));