3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 $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));
88 // lets keep variable names short
89 return substr($name, 0, $len);
97 * Convert possibly underscore separated words to camel case with special handling for 'UF'
98 * e.g membership_payment returns MembershipPayment
100 * @param string $string
104 public static function convertStringToCamel($string) {
111 if (isset($map[$string])) {
112 return $map[$string];
115 $fragments = explode('_', $string);
116 foreach ($fragments as & $fragment) {
117 $fragment = ucfirst($fragment);
119 // Special case: UFGroup, UFJoin, UFMatch, UFField
120 if ($fragments[0] === 'Uf') {
121 $fragments[0] = 'UF';
123 return implode('', $fragments);
127 * Takes a variable name and munges it randomly into another variable name.
129 * @param string $name
130 * Initial Variable Name.
132 * Length of valid variables.
135 * Randomized Variable Name
137 public static function rename($name, $len = 4) {
138 $rand = substr(uniqid(), 0, $len);
139 return substr_replace($name, $rand, -$len, $len);
143 * Takes a string and returns the last tuple of the string.
145 * Useful while converting file names to class names etc
147 * @param string $string
149 * @param string $char
150 * Character used to demarcate the components
155 public static function getClassName($string, $char = '_') {
157 if (!is_array($string)) {
158 $names = explode($char, $string);
160 if (!empty($names)) {
161 return array_pop($names);
166 * Appends a name to a string and separated by delimiter.
168 * Does the right thing for an empty string
171 * The string to be appended to.
172 * @param string $delim
173 * The delimiter to use.
175 * The string (or array of strings) to append.
177 public static function append(&$str, $delim, $name) {
182 if (is_array($name)) {
183 foreach ($name as $n) {
200 $str .= $delim . $name;
206 * Determine if the string is composed only of ascii characters.
211 * Attempt utf8 match on failure (default yes).
214 * true if string is ascii
216 public static function isAscii($str, $utf8 = TRUE) {
217 if (!function_exists('mb_detect_encoding')) {
218 // eliminate all white space from the string
219 $str = preg_replace('/\s+/', '', $str);
220 // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work.
222 // match low- or high-ascii characters
223 if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) {
224 // || // low ascii characters
225 // high ascii characters
226 // preg_match( '/[\x7F-\xFF]/', $str ) ) {
228 // if we did match, try for utf-8, or iso8859-1
230 return self
::isUtf8($str);
239 $order = array('ASCII');
243 $enc = mb_detect_encoding($str, $order, TRUE);
244 return ($enc == 'ASCII' ||
$enc == 'UTF-8');
249 * Determine the string replacements for redaction.
250 * on the basis of the regular expressions
254 * @param array $regexRules
255 * Regular expression to be matched w/ replacements.
258 * array of strings w/ corresponding redacted outputs
260 public static function regex($str, $regexRules) {
261 // redact the regular expressions
262 if (!empty($regexRules) && isset($str)) {
263 static $matches, $totalMatches, $match = array();
264 foreach ($regexRules as $pattern => $replacement) {
265 preg_match_all($pattern, $str, $matches);
266 if (!empty($matches[0])) {
267 if (empty($totalMatches)) {
268 $totalMatches = $matches[0];
271 $totalMatches = array_merge($totalMatches, $matches[0]);
273 $match = array_flip($totalMatches);
278 if (!empty($match)) {
279 foreach ($match as $matchKey => & $dontCare) {
280 foreach ($regexRules as $pattern => $replacement) {
281 if (preg_match($pattern, $matchKey)) {
282 $dontCare = $replacement . substr(md5($matchKey), 0, 5);
289 return CRM_Core_DAO
::$_nullArray;
294 * @param $stringRules
298 public static function redaction($str, $stringRules) {
299 // redact the strings
300 if (!empty($stringRules)) {
301 foreach ($stringRules as $match => $replace) {
302 $str = str_ireplace($match, $replace, $str);
306 // return the redacted output
311 * Determine if a string is composed only of utf8 characters
318 public static function isUtf8($str) {
319 if (!function_exists(mb_detect_encoding
)) {
320 // eliminate all white space from the string
321 $str = preg_replace('/\s+/', '', $str);
323 // pattern stolen from the php.net function documentation for
325 // comment by JF Sebastian, 30-Mar-2005
326 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);
328 // iconv('ISO-8859-1', 'UTF-8', $str);
331 $enc = mb_detect_encoding($str, array('UTF-8'), TRUE);
332 return ($enc !== FALSE);
337 * Determine if two hrefs are equivalent (fuzzy match)
339 * @param string $url1
340 * The first url to be matched.
341 * @param string $url2
342 * The second url to be matched against.
345 * true if the urls match, else false
347 public static function match($url1, $url2) {
348 $url1 = strtolower($url1);
349 $url2 = strtolower($url2);
351 $url1Str = parse_url($url1);
352 $url2Str = parse_url($url2);
354 if ($url1Str['path'] == $url2Str['path'] &&
355 self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url1Str)) == self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url2Str))
363 * Extract the civicrm path from the url.
365 * @param string $query
368 * @return string|null
369 * civicrm url (eg: civicrm/contact/search)
371 public static function extractURLVarValue($query) {
372 $config = CRM_Core_Config
::singleton();
373 $urlVar = $config->userFrameworkURLVar
;
375 $params = explode('&', $query);
376 foreach ($params as $p) {
377 if (strpos($p, '=')) {
378 list($k, $v) = explode('=', $p);
388 * Translate a true/false/yes/no string to a 0 or 1 value
391 * The string to be translated.
395 public static function strtobool($str) {
396 if (!is_scalar($str)) {
400 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
407 * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
410 * The string to be translated.
414 public static function strtoboolstr($str) {
415 if (!is_scalar($str)) {
419 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
422 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
431 * Convert a HTML string into a text one using html2text
433 * @param string $html
434 * The string to be converted.
437 * the converted string
439 public static function htmlToText($html) {
440 require_once 'packages/html2text/rcube_html2text.php';
441 $token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html);
442 $converter = new rcube_html2text($token_html);
443 $token_text = $converter->get_text();
444 $text = preg_replace('!token\:\{([a-z_.]+)\}!i', '{$1}', $token_text);
450 * @param array $params
452 public static function extractName($string, &$params) {
453 $name = trim($string);
459 $name = str_replace('"', '', $name);
460 $name = str_replace('\'', '', $name);
462 // check for comma in name
463 if (strpos($name, ',') !== FALSE) {
465 // name has a comma - assume lname, fname [mname]
466 $names = explode(',', $name);
467 if (count($names) > 1) {
468 $params['last_name'] = trim($names[0]);
470 // check for space delim
471 $fnames = explode(' ', trim($names[1]));
472 if (count($fnames) > 1) {
473 $params['first_name'] = trim($fnames[0]);
474 $params['middle_name'] = trim($fnames[1]);
477 $params['first_name'] = trim($fnames[0]);
481 $params['first_name'] = trim($names[0]);
485 // name has no comma - assume fname [mname] fname
486 $names = explode(' ', $name);
487 if (count($names) == 1) {
488 $params['first_name'] = $names[0];
490 elseif (count($names) == 2) {
491 $params['first_name'] = $names[0];
492 $params['last_name'] = $names[1];
495 $params['first_name'] = $names[0];
496 $params['middle_name'] = $names[1];
497 $params['last_name'] = $names[2];
507 public static function &makeArray($string) {
508 $string = trim($string);
510 $values = explode("\n", $string);
512 foreach ($values as $value) {
513 list($n, $v) = CRM_Utils_System
::explode('=', $value, 2);
515 $result[trim($n)] = trim($v);
522 * Given an ezComponents-parsed representation of
523 * a text with alternatives return only the first one
525 * @param string $full
526 * All alternatives as a long string (or some other text).
529 * only the first alternative found (or the text without alternatives)
531 public static function stripAlternatives($full) {
533 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
535 if (isset($matches[1]) &&
536 trim(strip_tags($matches[1])) != ''
546 * Strip leading, trailing, double spaces from string
547 * used for postal/greeting/addressee
549 * @param string $string
550 * Input string to be cleaned.
555 public static function stripSpaces($string) {
556 return (empty($string)) ?
$string : preg_replace("/\s{2,}/", " ", trim($string));
560 * clean the URL 'path' variable that we use
561 * to construct CiviCRM urls by removing characters from the path variable
563 * @param string $string
564 * The input string to be sanitized.
565 * @param array $search
566 * The characters to be sanitized.
567 * @param string $replace
568 * The character to replace it with.
571 * the sanitized string
573 public static function stripPathChars(
578 static $_searchChars = NULL;
579 static $_replaceChar = NULL;
581 if (empty($string)) {
585 if ($_searchChars == NULL) {
586 $_searchChars = array(
608 if ($search == NULL) {
609 $search = $_searchChars;
612 if ($replace == NULL) {
613 $replace = $_replaceChar;
616 return str_replace($search, $replace, $string);
621 * Use HTMLPurifier to clean up a text string and remove any potential
622 * xss attacks. This is primarily used in public facing pages which
623 * accept html as the input string
625 * @param string $string
629 * the cleaned up string
631 public static function purifyHTML($string) {
632 static $_filter = NULL;
634 $config = HTMLPurifier_Config
::createDefault();
635 $config->set('Core.Encoding', 'UTF-8');
637 // Disable the cache entirely
638 $config->set('Cache.DefinitionImpl', NULL);
640 $_filter = new HTMLPurifier($config);
643 return $_filter->purify($string);
647 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
649 * @param string $string
654 public static function ellipsify($string, $maxLen) {
655 $len = strlen($string);
656 if ($len <= $maxLen) {
661 while (strlen($string) > $maxLen - 3) {
662 $string = mb_substr($string, 0, $end, 'UTF-8');
665 return $string . '...';
670 * Generate a random string.
676 public static function createRandom($len, $alphabet) {
677 $alphabetSize = strlen($alphabet);
679 for ($i = 0; $i < $len; $i++
) {
680 $result .= $alphabet{rand(1, $alphabetSize) - 1};
687 * "admin foo" => array(NULL,"admin foo")
688 * "cms:admin foo" => array("cms", "admin foo")
691 * @param string $string
692 * E.g. "view all contacts". Syntax: "[prefix:]name".
693 * @param null $defaultPrefix
696 * (0 => string|NULL $prefix, 1 => string $value)
698 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
699 $pos = strpos($string, $delim);
700 if ($pos === FALSE) {
701 return array($defaultPrefix, $string);
704 return array(substr($string, 0, $pos), substr($string, 1 +
$pos));
709 * This function will mask part of the the user portion of an Email address (everything before the @)
711 * @param string $email
712 * The email address to be masked.
713 * @param string $maskChar
714 * The character used for masking.
715 * @param int $percent
716 * The percentage of the user portion to be masked.
719 * returns the masked Email address
721 public static function maskEmail($email, $maskChar = '*', $percent = 50) {
722 list($user, $domain) = preg_split("/@/", $email);
723 $len = strlen($user);
724 $maskCount = floor($len * $percent / 100);
725 $offset = floor(($len - $maskCount) / 2);
727 $masked = substr($user, 0, $offset)
728 . str_repeat($maskChar, $maskCount)
729 . substr($user, $maskCount +
$offset);
731 return ($masked . '@' . $domain);
735 * This function compares two strings.
737 * @param string $strOne
739 * @param string $strTwo
742 * Boolean indicating whether you want the comparison to be case sensitive or not.
745 * TRUE (string are identical); FALSE (strings are not identical)
747 public static function compareStr($strOne, $strTwo, $case) {
749 // Convert to lowercase and trim white spaces
750 if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) {
751 // yes - they are identical
759 if ($case == FALSE) {
761 if (trim($strOne) == trim($strTwo)) {
762 // yes - they are identical
773 * Many parts of the codebase have a convention of internally passing around
774 * HTML-encoded URLs. This effectively means that "&" is replaced by "&"
775 * (because most other odd characters are %-escaped in URLs; and %-escaped
776 * strings don't need any extra escaping in HTML).
778 * @param string $htmlUrl
779 * URL with HTML entities.
781 * URL without HTML entities
783 public static function unstupifyUrl($htmlUrl) {
784 return str_replace('&', '&', $htmlUrl);
788 * Formats a string of attributes for insertion in an html tag.
790 * @param array $attributes
794 public static function htmlAttributes($attributes) {
796 foreach ($attributes as $name => $vals) {
797 $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"';
799 return ltrim($output);
803 * Determine if $string starts with $fragment.
805 * @param string $string
807 * @param string $fragment
808 * The fragment to look for.
811 public static function startsWith($string, $fragment) {
812 if ($fragment === '') {
815 $len = strlen($fragment);
816 return substr($string, 0, $len) === $fragment;
820 * Determine if $string ends with $fragment.
822 * @param string $string
824 * @param string $fragment
825 * The fragment to look for.
828 public static function endsWith($string, $fragment) {
829 if ($fragment === '') {
832 $len = strlen($fragment);
833 return substr($string, -1 * $len) === $fragment;
837 * @param string|array $patterns
838 * @param array $allStrings
839 * @param bool $allowNew
840 * Whether to return new, unrecognized names.
843 public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) {
844 $patterns = (array) $patterns;
846 foreach ($patterns as $pattern) {
847 if (!\CRM_Utils_String
::endsWith($pattern, '*')) {
848 if ($allowNew ||
in_array($pattern, $allStrings)) {
849 $result[] = $pattern;
853 $prefix = rtrim($pattern, '*');
854 foreach ($allStrings as $key) {
855 if (\CRM_Utils_String
::startsWith($key, $prefix)) {
861 return array_values(array_unique($result));