3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
34 use function xKerman\Restricted\unserialize
;
35 use xKerman\Restricted\UnserializeFailedException
;
37 require_once 'HTML/QuickForm/Rule/Email.php';
40 * This class contains string functions.
42 class CRM_Utils_String
{
43 const COMMA
= ",", SEMICOLON
= ";", SPACE
= " ", TAB
= "\t", LINEFEED
= "\n", CARRIAGELINE
= "\r\n", LINECARRIAGE
= "\n\r", CARRIAGERETURN
= "\r";
46 * List of all letters and numbers
48 const ALPHANUMERIC
= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
51 * Convert a display name into a potential variable name.
53 * @param string $title title of the string
54 * @param int $maxLength
57 * An equivalent variable name.
59 public static function titleToVar($title, $maxLength = 31) {
60 $variable = self
::munge($title, '_', $maxLength);
62 if (CRM_Utils_Rule
::title($variable, $maxLength)) {
66 // if longer than the maxLength lets just return a substr of the
67 // md5 to prevent errors downstream
68 return substr(md5($title), 0, $maxLength);
72 * Replace all non alpha numeric characters and spaces with the replacement character.
75 * The name to be worked on.
77 * The character to use for non-valid chars.
79 * Length of valid variables.
82 * returns the manipulated string
84 public static function munge($name, $char = '_', $len = 63) {
85 // Replace all white space and non-alpha numeric with $char
86 // we only use the ascii character set since mysql does not create table names / field names otherwise
88 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
90 //If there are no ascii characters present.
92 $name = self
::createRandom($len, self
::ALPHANUMERIC
);
96 // lets keep variable names short
97 return substr($name, 0, $len);
105 * Convert possibly underscore separated words to camel case with special handling for 'UF'
106 * e.g membership_payment returns MembershipPayment
108 * @param string $string
112 public static function convertStringToCamel($string) {
119 if (isset($map[$string])) {
120 return $map[$string];
123 $fragments = explode('_', $string);
124 foreach ($fragments as & $fragment) {
125 $fragment = ucfirst($fragment);
126 // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in without underscores)
127 if (strpos($fragment, 'Uf') === 0 && strlen($string) > 2) {
128 $fragment = 'UF' . ucfirst(substr($fragment, 2));
131 // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in underscore-separated)
132 if ($fragments[0] === 'Uf') {
133 $fragments[0] = 'UF';
135 return implode('', $fragments);
139 * Takes a variable name and munges it randomly into another variable name.
141 * @param string $name
142 * Initial Variable Name.
144 * Length of valid variables.
147 * Randomized Variable Name
149 public static function rename($name, $len = 4) {
150 $rand = substr(uniqid(), 0, $len);
151 return substr_replace($name, $rand, -$len, $len);
155 * Takes a string and returns the last tuple of the string.
157 * Useful while converting file names to class names etc
159 * @param string $string
161 * @param string $char
162 * Character used to demarcate the components
167 public static function getClassName($string, $char = '_') {
169 if (!is_array($string)) {
170 $names = explode($char, $string);
172 if (!empty($names)) {
173 return array_pop($names);
178 * Appends a name to a string and separated by delimiter.
180 * Does the right thing for an empty string
183 * The string to be appended to.
184 * @param string $delim
185 * The delimiter to use.
187 * The string (or array of strings) to append.
189 public static function append(&$str, $delim, $name) {
194 if (is_array($name)) {
195 foreach ($name as $n) {
212 $str .= $delim . $name;
218 * Determine if the string is composed only of ascii characters.
223 * Attempt utf8 match on failure (default yes).
226 * true if string is ascii
228 public static function isAscii($str, $utf8 = TRUE) {
229 if (!function_exists('mb_detect_encoding')) {
230 // eliminate all white space from the string
231 $str = preg_replace('/\s+/', '', $str);
232 // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work.
234 // match low- or high-ascii characters
235 if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) {
236 // || // low ascii characters
237 // high ascii characters
238 // preg_match( '/[\x7F-\xFF]/', $str ) ) {
240 // if we did match, try for utf-8, or iso8859-1
242 return self
::isUtf8($str);
255 $enc = mb_detect_encoding($str, $order, TRUE);
256 return ($enc == 'ASCII' ||
$enc == 'UTF-8');
261 * Determine the string replacements for redaction.
262 * on the basis of the regular expressions
266 * @param array $regexRules
267 * Regular expression to be matched w/ replacements.
270 * array of strings w/ corresponding redacted outputs
272 public static function regex($str, $regexRules) {
273 // redact the regular expressions
274 if (!empty($regexRules) && isset($str)) {
275 static $matches, $totalMatches, $match = [];
276 foreach ($regexRules as $pattern => $replacement) {
277 preg_match_all($pattern, $str, $matches);
278 if (!empty($matches[0])) {
279 if (empty($totalMatches)) {
280 $totalMatches = $matches[0];
283 $totalMatches = array_merge($totalMatches, $matches[0]);
285 $match = array_flip($totalMatches);
290 if (!empty($match)) {
291 foreach ($match as $matchKey => & $dontCare) {
292 foreach ($regexRules as $pattern => $replacement) {
293 if (preg_match($pattern, $matchKey)) {
294 $dontCare = $replacement . substr(md5($matchKey), 0, 5);
306 * @param $stringRules
310 public static function redaction($str, $stringRules) {
311 // redact the strings
312 if (!empty($stringRules)) {
313 foreach ($stringRules as $match => $replace) {
314 $str = str_ireplace($match, $replace, $str);
318 // return the redacted output
323 * Determine if a string is composed only of utf8 characters
330 public static function isUtf8($str) {
331 if (!function_exists(mb_detect_encoding
)) {
332 // eliminate all white space from the string
333 $str = preg_replace('/\s+/', '', $str);
335 // pattern stolen from the php.net function documentation for
337 // comment by JF Sebastian, 30-Mar-2005
338 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);
340 // iconv('ISO-8859-1', 'UTF-8', $str);
343 $enc = mb_detect_encoding($str, ['UTF-8'], TRUE);
344 return ($enc !== FALSE);
349 * Determine if two hrefs are equivalent (fuzzy match)
351 * @param string $url1
352 * The first url to be matched.
353 * @param string $url2
354 * The second url to be matched against.
357 * true if the urls match, else false
359 public static function match($url1, $url2) {
360 $url1 = strtolower($url1);
361 $url2 = strtolower($url2);
363 $url1Str = parse_url($url1);
364 $url2Str = parse_url($url2);
366 if ($url1Str['path'] == $url2Str['path'] &&
367 self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url1Str)) == self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url2Str))
375 * Extract the civicrm path from the url.
377 * @param string $query
380 * @return string|null
381 * civicrm url (eg: civicrm/contact/search)
383 public static function extractURLVarValue($query) {
384 $config = CRM_Core_Config
::singleton();
385 $urlVar = $config->userFrameworkURLVar
;
387 $params = explode('&', $query);
388 foreach ($params as $p) {
389 if (strpos($p, '=')) {
390 list($k, $v) = explode('=', $p);
400 * Translate a true/false/yes/no string to a 0 or 1 value
403 * The string to be translated.
407 public static function strtobool($str) {
408 if (!is_scalar($str)) {
412 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
419 * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
422 * The string to be translated.
426 public static function strtoboolstr($str) {
427 if (!is_scalar($str)) {
431 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
434 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
443 * Convert a HTML string into a text one using html2text
445 * @param string $html
446 * The string to be converted.
449 * the converted string
451 public static function htmlToText($html) {
452 require_once 'packages/html2text/rcube_html2text.php';
453 $token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html);
454 $converter = new rcube_html2text($token_html);
455 $token_text = $converter->get_text();
456 $text = preg_replace('!token\:\{([a-z_.]+)\}!i', '{$1}', $token_text);
462 * @param array $params
464 public static function extractName($string, &$params) {
465 $name = trim($string);
471 $name = str_replace('"', '', $name);
472 $name = str_replace('\'', '', $name);
474 // check for comma in name
475 if (strpos($name, ',') !== FALSE) {
477 // name has a comma - assume lname, fname [mname]
478 $names = explode(',', $name);
479 if (count($names) > 1) {
480 $params['last_name'] = trim($names[0]);
482 // check for space delim
483 $fnames = explode(' ', trim($names[1]));
484 if (count($fnames) > 1) {
485 $params['first_name'] = trim($fnames[0]);
486 $params['middle_name'] = trim($fnames[1]);
489 $params['first_name'] = trim($fnames[0]);
493 $params['first_name'] = trim($names[0]);
497 // name has no comma - assume fname [mname] fname
498 $names = explode(' ', $name);
499 if (count($names) == 1) {
500 $params['first_name'] = $names[0];
502 elseif (count($names) == 2) {
503 $params['first_name'] = $names[0];
504 $params['last_name'] = $names[1];
507 $params['first_name'] = $names[0];
508 $params['middle_name'] = $names[1];
509 $params['last_name'] = $names[2];
519 public static function &makeArray($string) {
520 $string = trim($string);
522 $values = explode("\n", $string);
524 foreach ($values as $value) {
525 list($n, $v) = CRM_Utils_System
::explode('=', $value, 2);
527 $result[trim($n)] = trim($v);
534 * Given an ezComponents-parsed representation of
535 * a text with alternatives return only the first one
537 * @param string $full
538 * All alternatives as a long string (or some other text).
541 * only the first alternative found (or the text without alternatives)
543 public static function stripAlternatives($full) {
545 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
547 if (isset($matches[1]) &&
548 trim(strip_tags($matches[1])) != ''
558 * Strip leading, trailing, double spaces from string
559 * used for postal/greeting/addressee
561 * @param string $string
562 * Input string to be cleaned.
567 public static function stripSpaces($string) {
568 return (empty($string)) ?
$string : preg_replace("/\s{2,}/", " ", trim($string));
572 * clean the URL 'path' variable that we use
573 * to construct CiviCRM urls by removing characters from the path variable
575 * @param string $string
576 * The input string to be sanitized.
577 * @param array $search
578 * The characters to be sanitized.
579 * @param string $replace
580 * The character to replace it with.
583 * the sanitized string
585 public static function stripPathChars(
590 static $_searchChars = NULL;
591 static $_replaceChar = NULL;
593 if (empty($string)) {
597 if ($_searchChars == NULL) {
620 if ($search == NULL) {
621 $search = $_searchChars;
624 if ($replace == NULL) {
625 $replace = $_replaceChar;
628 return str_replace($search, $replace, $string);
632 * Use HTMLPurifier to clean up a text string and remove any potential
633 * xss attacks. This is primarily used in public facing pages which
634 * accept html as the input string
636 * @param string $string
640 * the cleaned up string
642 public static function purifyHTML($string) {
643 static $_filter = NULL;
645 $config = HTMLPurifier_Config
::createDefault();
646 $config->set('Core.Encoding', 'UTF-8');
647 $config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']);
649 // Disable the cache entirely
650 $config->set('Cache.DefinitionImpl', NULL);
652 $_filter = new HTMLPurifier($config);
655 return $_filter->purify($string);
659 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
661 * @param string $string
666 public static function ellipsify($string, $maxLen) {
667 if (mb_strlen($string, 'UTF-8') <= $maxLen) {
670 return mb_substr($string, 0, $maxLen - 3, 'UTF-8') . '...';
674 * Generate a random string.
680 public static function createRandom($len, $alphabet) {
681 $alphabetSize = strlen($alphabet);
683 for ($i = 0; $i < $len; $i++
) {
684 $result .= $alphabet{rand(1, $alphabetSize) - 1};
691 * "admin foo" => array(NULL,"admin foo")
692 * "cms:admin foo" => array("cms", "admin foo")
695 * @param string $string
696 * E.g. "view all contacts". Syntax: "[prefix:]name".
697 * @param null $defaultPrefix
700 * (0 => string|NULL $prefix, 1 => string $value)
702 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
703 $pos = strpos($string, $delim);
704 if ($pos === FALSE) {
705 return [$defaultPrefix, $string];
708 return [substr($string, 0, $pos), substr($string, 1 +
$pos)];
713 * This function will mask part of the the user portion of an Email address (everything before the @)
715 * @param string $email
716 * The email address to be masked.
717 * @param string $maskChar
718 * The character used for masking.
719 * @param int $percent
720 * The percentage of the user portion to be masked.
723 * returns the masked Email address
725 public static function maskEmail($email, $maskChar = '*', $percent = 50) {
726 list($user, $domain) = preg_split("/@/", $email);
727 $len = strlen($user);
728 $maskCount = floor($len * $percent / 100);
729 $offset = floor(($len - $maskCount) / 2);
731 $masked = substr($user, 0, $offset)
732 . str_repeat($maskChar, $maskCount)
733 . substr($user, $maskCount +
$offset);
735 return ($masked . '@' . $domain);
739 * This function compares two strings.
741 * @param string $strOne
743 * @param string $strTwo
746 * Boolean indicating whether you want the comparison to be case sensitive or not.
749 * TRUE (string are identical); FALSE (strings are not identical)
751 public static function compareStr($strOne, $strTwo, $case) {
753 // Convert to lowercase and trim white spaces
754 if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) {
755 // yes - they are identical
763 if ($case == FALSE) {
765 if (trim($strOne) == trim($strTwo)) {
766 // yes - they are identical
777 * Many parts of the codebase have a convention of internally passing around
778 * HTML-encoded URLs. This effectively means that "&" is replaced by "&"
779 * (because most other odd characters are %-escaped in URLs; and %-escaped
780 * strings don't need any extra escaping in HTML).
782 * @param string $htmlUrl
783 * URL with HTML entities.
785 * URL without HTML entities
787 public static function unstupifyUrl($htmlUrl) {
788 return str_replace('&', '&', $htmlUrl);
792 * When a user supplies a URL (e.g. to an image), we'd like to:
793 * - Remove the protocol and domain name if the URL points to the current
795 * - Keep the domain name for remote URLs.
796 * - Optionally, force remote URLs to use https instead of http (which is
800 * The URL to simplify. Examples:
801 * "https://example.org/sites/default/files/coffee-mug.jpg"
802 * "sites/default/files/coffee-mug.jpg"
803 * "http://i.stack.imgur.com/9jb2ial01b.png"
804 * @param bool $forceHttps = FALSE
805 * If TRUE, ensure that remote URLs use https. If a URL with
806 * http is supplied, then we'll change it to https.
807 * This is useful for situations like showing a premium product on a
808 * contribution, because (as reported in CRM-14283) if the user gets a
809 * browser warning like "page contains insecure elements" on a contribution
810 * page, that's a very bad thing. Thus, even if changing http to https
811 * breaks the image, that's better than leaving http content in a
815 * The simplified URL. Examples:
816 * "/sites/default/files/coffee-mug.jpg"
817 * "https://i.stack.imgur.com/9jb2ial01b.png"
819 public static function simplifyURL($url, $forceHttps = FALSE) {
820 $config = CRM_Core_Config
::singleton();
821 $siteURLParts = self
::simpleParseUrl($config->userFrameworkBaseURL
);
822 $urlParts = self
::simpleParseUrl($url);
824 // If the image is locally hosted, then only give the path to the image
826 = ($urlParts['host+port'] == '')
827 |
($urlParts['host+port'] == $siteURLParts['host+port']);
829 // and make sure it begins with one forward slash
830 return preg_replace('_^/*(?=.)_', '/', $urlParts['path+query']);
833 // If the URL is external, then keep the full URL as supplied
835 return $forceHttps ?
preg_replace('_^http://_', 'https://', $url) : $url;
840 * A simplified version of PHP's parse_url() function.
843 * e.g. "https://example.com:8000/foo/bar/?id=1#fragment"
846 * Will always contain keys 'host+port' and 'path+query', even if they're
847 * empty strings. Example:
849 * 'host+port' => "example.com:8000",
850 * 'path+query' => "/foo/bar/?id=1",
853 public static function simpleParseUrl($url) {
854 $parts = parse_url($url);
855 $host = isset($parts['host']) ?
$parts['host'] : '';
856 $port = isset($parts['port']) ?
':' . $parts['port'] : '';
857 $path = isset($parts['path']) ?
$parts['path'] : '';
858 $query = isset($parts['query']) ?
'?' . $parts['query'] : '';
860 'host+port' => "$host$port",
861 'path+query' => "$path$query",
866 * Formats a string of attributes for insertion in an html tag.
868 * @param array $attributes
872 public static function htmlAttributes($attributes) {
874 foreach ($attributes as $name => $vals) {
875 $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"';
877 return ltrim($output);
881 * Determine if $string starts with $fragment.
883 * @param string $string
885 * @param string $fragment
886 * The fragment to look for.
889 public static function startsWith($string, $fragment) {
890 if ($fragment === '') {
893 $len = strlen($fragment);
894 return substr($string, 0, $len) === $fragment;
898 * Determine if $string ends with $fragment.
900 * @param string $string
902 * @param string $fragment
903 * The fragment to look for.
906 public static function endsWith($string, $fragment) {
907 if ($fragment === '') {
910 $len = strlen($fragment);
911 return substr($string, -1 * $len) === $fragment;
915 * @param string|array $patterns
916 * @param array $allStrings
917 * @param bool $allowNew
918 * Whether to return new, unrecognized names.
921 public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) {
922 $patterns = (array) $patterns;
924 foreach ($patterns as $pattern) {
925 if (!\CRM_Utils_String
::endsWith($pattern, '*')) {
926 if ($allowNew ||
in_array($pattern, $allStrings)) {
927 $result[] = $pattern;
931 $prefix = rtrim($pattern, '*');
932 foreach ($allStrings as $key) {
933 if (\CRM_Utils_String
::startsWith($key, $prefix)) {
939 return array_values(array_unique($result));
943 * Use xkerman/restricted-unserialize to unserialize a string of data.
944 * @param string|NULL $string
947 * @throws CRM_Core_Exception
949 public static function unserialize($string) {
950 if (!is_string($string)) {
954 return unserialize($string);
956 catch (UnserializeFailedException
$e) {