3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
34 require_once 'HTML/QuickForm/Rule/Email.php';
37 * This class contains string functions.
39 class CRM_Utils_String
{
40 const COMMA
= ",", SEMICOLON
= ";", SPACE
= " ", TAB
= "\t", LINEFEED
= "\n", CARRIAGELINE
= "\r\n", LINECARRIAGE
= "\n\r", CARRIAGERETURN
= "\r";
43 * List of all letters and numbers
45 const ALPHANUMERIC
= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
48 * Convert a display name into a potential variable name.
50 * @param string $title title of the string
51 * @param int $maxLength
54 * An equivalent variable name.
56 public static function titleToVar($title, $maxLength = 31) {
57 $variable = self
::munge($title, '_', $maxLength);
59 if (CRM_Utils_Rule
::title($variable, $maxLength)) {
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);
69 * Replace all non alpha numeric characters and spaces with the replacement character.
72 * The name to be worked on.
74 * The character to use for non-valid chars.
76 * Length of valid variables.
79 * returns the manipulated string
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
85 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
87 //If there are no ascii characters present.
89 $name = self
::createRandom($len, self
::ALPHANUMERIC
);
93 // lets keep variable names short
94 return substr($name, 0, $len);
102 * Convert possibly underscore separated words to camel case with special handling for 'UF'
103 * e.g membership_payment returns MembershipPayment
105 * @param string $string
109 public static function convertStringToCamel($string) {
116 if (isset($map[$string])) {
117 return $map[$string];
120 $fragments = explode('_', $string);
121 foreach ($fragments as & $fragment) {
122 $fragment = ucfirst($fragment);
124 // Special case: UFGroup, UFJoin, UFMatch, UFField
125 if ($fragments[0] === 'Uf') {
126 $fragments[0] = 'UF';
128 return implode('', $fragments);
132 * Takes a variable name and munges it randomly into another variable name.
134 * @param string $name
135 * Initial Variable Name.
137 * Length of valid variables.
140 * Randomized Variable Name
142 public static function rename($name, $len = 4) {
143 $rand = substr(uniqid(), 0, $len);
144 return substr_replace($name, $rand, -$len, $len);
148 * Takes a string and returns the last tuple of the string.
150 * Useful while converting file names to class names etc
152 * @param string $string
154 * @param string $char
155 * Character used to demarcate the components
160 public static function getClassName($string, $char = '_') {
162 if (!is_array($string)) {
163 $names = explode($char, $string);
165 if (!empty($names)) {
166 return array_pop($names);
171 * Appends a name to a string and separated by delimiter.
173 * Does the right thing for an empty string
176 * The string to be appended to.
177 * @param string $delim
178 * The delimiter to use.
180 * The string (or array of strings) to append.
182 public static function append(&$str, $delim, $name) {
187 if (is_array($name)) {
188 foreach ($name as $n) {
205 $str .= $delim . $name;
211 * Determine if the string is composed only of ascii characters.
216 * Attempt utf8 match on failure (default yes).
219 * true if string is ascii
221 public static function isAscii($str, $utf8 = TRUE) {
222 if (!function_exists('mb_detect_encoding')) {
223 // eliminate all white space from the string
224 $str = preg_replace('/\s+/', '', $str);
225 // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work.
227 // match low- or high-ascii characters
228 if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) {
229 // || // low ascii characters
230 // high ascii characters
231 // preg_match( '/[\x7F-\xFF]/', $str ) ) {
233 // if we did match, try for utf-8, or iso8859-1
235 return self
::isUtf8($str);
244 $order = array('ASCII');
248 $enc = mb_detect_encoding($str, $order, TRUE);
249 return ($enc == 'ASCII' ||
$enc == 'UTF-8');
254 * Determine the string replacements for redaction.
255 * on the basis of the regular expressions
259 * @param array $regexRules
260 * Regular expression to be matched w/ replacements.
263 * array of strings w/ corresponding redacted outputs
265 public static function regex($str, $regexRules) {
266 // redact the regular expressions
267 if (!empty($regexRules) && isset($str)) {
268 static $matches, $totalMatches, $match = array();
269 foreach ($regexRules as $pattern => $replacement) {
270 preg_match_all($pattern, $str, $matches);
271 if (!empty($matches[0])) {
272 if (empty($totalMatches)) {
273 $totalMatches = $matches[0];
276 $totalMatches = array_merge($totalMatches, $matches[0]);
278 $match = array_flip($totalMatches);
283 if (!empty($match)) {
284 foreach ($match as $matchKey => & $dontCare) {
285 foreach ($regexRules as $pattern => $replacement) {
286 if (preg_match($pattern, $matchKey)) {
287 $dontCare = $replacement . substr(md5($matchKey), 0, 5);
294 return CRM_Core_DAO
::$_nullArray;
299 * @param $stringRules
303 public static function redaction($str, $stringRules) {
304 // redact the strings
305 if (!empty($stringRules)) {
306 foreach ($stringRules as $match => $replace) {
307 $str = str_ireplace($match, $replace, $str);
311 // return the redacted output
316 * Determine if a string is composed only of utf8 characters
323 public static function isUtf8($str) {
324 if (!function_exists(mb_detect_encoding
)) {
325 // eliminate all white space from the string
326 $str = preg_replace('/\s+/', '', $str);
328 // pattern stolen from the php.net function documentation for
330 // comment by JF Sebastian, 30-Mar-2005
331 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);
333 // iconv('ISO-8859-1', 'UTF-8', $str);
336 $enc = mb_detect_encoding($str, array('UTF-8'), TRUE);
337 return ($enc !== FALSE);
342 * Determine if two hrefs are equivalent (fuzzy match)
344 * @param string $url1
345 * The first url to be matched.
346 * @param string $url2
347 * The second url to be matched against.
350 * true if the urls match, else false
352 public static function match($url1, $url2) {
353 $url1 = strtolower($url1);
354 $url2 = strtolower($url2);
356 $url1Str = parse_url($url1);
357 $url2Str = parse_url($url2);
359 if ($url1Str['path'] == $url2Str['path'] &&
360 self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url1Str)) == self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url2Str))
368 * Extract the civicrm path from the url.
370 * @param string $query
373 * @return string|null
374 * civicrm url (eg: civicrm/contact/search)
376 public static function extractURLVarValue($query) {
377 $config = CRM_Core_Config
::singleton();
378 $urlVar = $config->userFrameworkURLVar
;
380 $params = explode('&', $query);
381 foreach ($params as $p) {
382 if (strpos($p, '=')) {
383 list($k, $v) = explode('=', $p);
393 * Translate a true/false/yes/no string to a 0 or 1 value
396 * The string to be translated.
400 public static function strtobool($str) {
401 if (!is_scalar($str)) {
405 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
412 * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
415 * The string to be translated.
419 public static function strtoboolstr($str) {
420 if (!is_scalar($str)) {
424 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
427 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
436 * Convert a HTML string into a text one using html2text
438 * @param string $html
439 * The string to be converted.
442 * the converted string
444 public static function htmlToText($html) {
445 require_once 'packages/html2text/rcube_html2text.php';
446 $token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html);
447 $converter = new rcube_html2text($token_html);
448 $token_text = $converter->get_text();
449 $text = preg_replace('!token\:\{([a-z_.]+)\}!i', '{$1}', $token_text);
455 * @param array $params
457 public static function extractName($string, &$params) {
458 $name = trim($string);
464 $name = str_replace('"', '', $name);
465 $name = str_replace('\'', '', $name);
467 // check for comma in name
468 if (strpos($name, ',') !== FALSE) {
470 // name has a comma - assume lname, fname [mname]
471 $names = explode(',', $name);
472 if (count($names) > 1) {
473 $params['last_name'] = trim($names[0]);
475 // check for space delim
476 $fnames = explode(' ', trim($names[1]));
477 if (count($fnames) > 1) {
478 $params['first_name'] = trim($fnames[0]);
479 $params['middle_name'] = trim($fnames[1]);
482 $params['first_name'] = trim($fnames[0]);
486 $params['first_name'] = trim($names[0]);
490 // name has no comma - assume fname [mname] fname
491 $names = explode(' ', $name);
492 if (count($names) == 1) {
493 $params['first_name'] = $names[0];
495 elseif (count($names) == 2) {
496 $params['first_name'] = $names[0];
497 $params['last_name'] = $names[1];
500 $params['first_name'] = $names[0];
501 $params['middle_name'] = $names[1];
502 $params['last_name'] = $names[2];
512 public static function &makeArray($string) {
513 $string = trim($string);
515 $values = explode("\n", $string);
517 foreach ($values as $value) {
518 list($n, $v) = CRM_Utils_System
::explode('=', $value, 2);
520 $result[trim($n)] = trim($v);
527 * Given an ezComponents-parsed representation of
528 * a text with alternatives return only the first one
530 * @param string $full
531 * All alternatives as a long string (or some other text).
534 * only the first alternative found (or the text without alternatives)
536 public static function stripAlternatives($full) {
538 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
540 if (isset($matches[1]) &&
541 trim(strip_tags($matches[1])) != ''
551 * Strip leading, trailing, double spaces from string
552 * used for postal/greeting/addressee
554 * @param string $string
555 * Input string to be cleaned.
560 public static function stripSpaces($string) {
561 return (empty($string)) ?
$string : preg_replace("/\s{2,}/", " ", trim($string));
565 * clean the URL 'path' variable that we use
566 * to construct CiviCRM urls by removing characters from the path variable
568 * @param string $string
569 * The input string to be sanitized.
570 * @param array $search
571 * The characters to be sanitized.
572 * @param string $replace
573 * The character to replace it with.
576 * the sanitized string
578 public static function stripPathChars(
583 static $_searchChars = NULL;
584 static $_replaceChar = NULL;
586 if (empty($string)) {
590 if ($_searchChars == NULL) {
591 $_searchChars = array(
613 if ($search == NULL) {
614 $search = $_searchChars;
617 if ($replace == NULL) {
618 $replace = $_replaceChar;
621 return str_replace($search, $replace, $string);
626 * Use HTMLPurifier to clean up a text string and remove any potential
627 * xss attacks. This is primarily used in public facing pages which
628 * accept html as the input string
630 * @param string $string
634 * the cleaned up string
636 public static function purifyHTML($string) {
637 static $_filter = NULL;
639 $config = HTMLPurifier_Config
::createDefault();
640 $config->set('Core.Encoding', 'UTF-8');
642 // Disable the cache entirely
643 $config->set('Cache.DefinitionImpl', NULL);
645 $_filter = new HTMLPurifier($config);
648 return $_filter->purify($string);
652 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
654 * @param string $string
659 public static function ellipsify($string, $maxLen) {
660 $len = mb_strlen($string, 'UTF-8');
661 if ($len <= $maxLen) {
666 while (mb_strlen($string, 'UTF-8') > $maxLen - 3) {
667 $string = mb_substr($string, 0, $end, 'UTF-8');
670 return $string . '...';
675 * Generate a random string.
681 public static function createRandom($len, $alphabet) {
682 $alphabetSize = strlen($alphabet);
684 for ($i = 0; $i < $len; $i++
) {
685 $result .= $alphabet{rand(1, $alphabetSize) - 1};
692 * "admin foo" => array(NULL,"admin foo")
693 * "cms:admin foo" => array("cms", "admin foo")
696 * @param string $string
697 * E.g. "view all contacts". Syntax: "[prefix:]name".
698 * @param null $defaultPrefix
701 * (0 => string|NULL $prefix, 1 => string $value)
703 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
704 $pos = strpos($string, $delim);
705 if ($pos === FALSE) {
706 return array($defaultPrefix, $string);
709 return array(substr($string, 0, $pos), substr($string, 1 +
$pos));
714 * This function will mask part of the the user portion of an Email address (everything before the @)
716 * @param string $email
717 * The email address to be masked.
718 * @param string $maskChar
719 * The character used for masking.
720 * @param int $percent
721 * The percentage of the user portion to be masked.
724 * returns the masked Email address
726 public static function maskEmail($email, $maskChar = '*', $percent = 50) {
727 list($user, $domain) = preg_split("/@/", $email);
728 $len = strlen($user);
729 $maskCount = floor($len * $percent / 100);
730 $offset = floor(($len - $maskCount) / 2);
732 $masked = substr($user, 0, $offset)
733 . str_repeat($maskChar, $maskCount)
734 . substr($user, $maskCount +
$offset);
736 return ($masked . '@' . $domain);
740 * This function compares two strings.
742 * @param string $strOne
744 * @param string $strTwo
747 * Boolean indicating whether you want the comparison to be case sensitive or not.
750 * TRUE (string are identical); FALSE (strings are not identical)
752 public static function compareStr($strOne, $strTwo, $case) {
754 // Convert to lowercase and trim white spaces
755 if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) {
756 // yes - they are identical
764 if ($case == FALSE) {
766 if (trim($strOne) == trim($strTwo)) {
767 // yes - they are identical
778 * Many parts of the codebase have a convention of internally passing around
779 * HTML-encoded URLs. This effectively means that "&" is replaced by "&"
780 * (because most other odd characters are %-escaped in URLs; and %-escaped
781 * strings don't need any extra escaping in HTML).
783 * @param string $htmlUrl
784 * URL with HTML entities.
786 * URL without HTML entities
788 public static function unstupifyUrl($htmlUrl) {
789 return str_replace('&', '&', $htmlUrl);
793 * When a user supplies a URL (e.g. to an image), we'd like to:
794 * - Remove the protocol and domain name if the URL points to the current
796 * - Keep the domain name for remote URLs.
797 * - Optionally, force remote URLs to use https instead of http (which is
801 * The URL to simplify. Examples:
802 * "https://example.org/sites/default/files/coffee-mug.jpg"
803 * "sites/default/files/coffee-mug.jpg"
804 * "http://i.stack.imgur.com/9jb2ial01b.png"
805 * @param bool $forceHttps = FALSE
806 * If TRUE, ensure that remote URLs use https. If a URL with
807 * http is supplied, then we'll change it to https.
808 * This is useful for situations like showing a premium product on a
809 * contribution, because (as reported in CRM-14283) if the user gets a
810 * browser warning like "page contains insecure elements" on a contribution
811 * page, that's a very bad thing. Thus, even if changing http to https
812 * breaks the image, that's better than leaving http content in a
816 * The simplified URL. Examples:
817 * "/sites/default/files/coffee-mug.jpg"
818 * "https://i.stack.imgur.com/9jb2ial01b.png"
820 public static function simplifyURL($url, $forceHttps = FALSE) {
821 $config = CRM_Core_Config
::singleton();
822 $siteURLParts = self
::simpleParseUrl($config->userFrameworkBaseURL
);
823 $urlParts = self
::simpleParseUrl($url);
825 // If the image is locally hosted, then only give the path to the image
827 = ($urlParts['host+port'] == '')
828 |
($urlParts['host+port'] == $siteURLParts['host+port']);
830 // and make sure it begins with one forward slash
831 return preg_replace('_^/*(?=.)_', '/', $urlParts['path+query']);
834 // If the URL is external, then keep the full URL as supplied
836 return $forceHttps ?
preg_replace('_^http://_', 'https://', $url) : $url;
841 * A simplified version of PHP's parse_url() function.
844 * e.g. "https://example.com:8000/foo/bar/?id=1#fragment"
847 * Will always contain keys 'host+port' and 'path+query', even if they're
848 * empty strings. Example:
850 * 'host+port' => "example.com:8000",
851 * 'path+query' => "/foo/bar/?id=1",
854 public static function simpleParseUrl($url) {
855 $parts = parse_url($url);
856 $host = isset($parts['host']) ?
$parts['host'] : '';
857 $port = isset($parts['port']) ?
':' . $parts['port'] : '';
858 $path = isset($parts['path']) ?
$parts['path'] : '';
859 $query = isset($parts['query']) ?
'?' . $parts['query'] : '';
861 'host+port' => "$host$port",
862 'path+query' => "$path$query",
867 * Formats a string of attributes for insertion in an html tag.
869 * @param array $attributes
873 public static function htmlAttributes($attributes) {
875 foreach ($attributes as $name => $vals) {
876 $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"';
878 return ltrim($output);
882 * Determine if $string starts with $fragment.
884 * @param string $string
886 * @param string $fragment
887 * The fragment to look for.
890 public static function startsWith($string, $fragment) {
891 if ($fragment === '') {
894 $len = strlen($fragment);
895 return substr($string, 0, $len) === $fragment;
899 * Determine if $string ends with $fragment.
901 * @param string $string
903 * @param string $fragment
904 * The fragment to look for.
907 public static function endsWith($string, $fragment) {
908 if ($fragment === '') {
911 $len = strlen($fragment);
912 return substr($string, -1 * $len) === $fragment;
916 * @param string|array $patterns
917 * @param array $allStrings
918 * @param bool $allowNew
919 * Whether to return new, unrecognized names.
922 public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) {
923 $patterns = (array) $patterns;
925 foreach ($patterns as $pattern) {
926 if (!\CRM_Utils_String
::endsWith($pattern, '*')) {
927 if ($allowNew ||
in_array($pattern, $allStrings)) {
928 $result[] = $pattern;
932 $prefix = rtrim($pattern, '*');
933 foreach ($allStrings as $key) {
934 if (\CRM_Utils_String
::startsWith($key, $prefix)) {
940 return array_values(array_unique($result));