9918d92215b24be661fa9f5515c1ad685355298c
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
36 require_once 'HTML/QuickForm/Rule/Email.php';
39 * 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
52 * name that we could use in forms/code
54 * @param name Name of the string
56 * @param int $maxLength
58 * @return string An equivalent variable name
62 * @return string (or null)
65 static function titleToVar($title, $maxLength = 31) {
66 $variable = self
::munge($title, '_', $maxLength);
68 if (CRM_Utils_Rule
::title($variable, $maxLength)) {
72 // if longer than the maxLength lets just return a substr of the
73 // md5 to prevent errors downstream
74 return substr(md5($title), 0, $maxLength);
78 * Given a string, replace all non alpha numeric characters and
79 * spaces with the replacement character
81 * @param string $name the name to be worked on
82 * @param string $char the character to use for non-valid chars
83 * @param int $len length of valid variables
87 * @return string returns the manipulated string
90 static function munge($name, $char = '_', $len = 63) {
91 // replace all white space and non-alpha numeric with $char
92 // we only use the ascii character set since mysql does not create table names / field names otherwise
94 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
97 // lets keep variable names short
98 return substr($name, 0, $len);
106 * Convert possibly underscore separated words to camel case with special handling for 'UF'
108 * membership_payment returns MembershipPayment
109 * @param string $string
111 * @return string string
113 static function convertStringToCamel($string) {
114 $fragments = explode('_', $string);
115 foreach ($fragments as & $fragment) {
116 $fragment = ucfirst($fragment);
118 // Special case: UFGroup, UFJoin, UFMatch, UFField
119 if ($fragments[0] === 'Uf') {
120 $fragments[0] = 'UF';
122 return implode('', $fragments);
127 * Takes a variable name and munges it randomly into another variable name
129 * @param string $name Initial Variable Name
130 * @param int $len length of valid variables
132 * @return string Randomized Variable Name
136 static function rename($name, $len = 4) {
137 $rand = substr(uniqid(), 0, $len);
138 return substr_replace($name, $rand, -$len, $len);
142 * Takes a string and returns the last tuple of the string.
143 * useful while converting file names to class names etc
145 * @param string $string the input string
146 * @param \char|string $char $char the character used to demarcate the componets
150 * @return string the last component
153 static function getClassName($string, $char = '_') {
155 if (!is_array($string)) {
156 $names = explode($char, $string);
158 if (!empty($names)) {
159 return array_pop($names);
164 * Appends a name to a string and seperated by delimiter.
165 * does the right thing for an empty string
167 * @param string $str the string to be appended to
168 * @param string $delim the delimiter to use
169 * @param mixed $name the string (or array of strings) to append
175 static function append(&$str, $delim, $name) {
180 if (is_array($name)) {
181 foreach ($name as $n) {
198 $str .= $delim . $name;
204 * Determine if the string is composed only of ascii characters
206 * @param string $str input string
207 * @param boolean $utf8 attempt utf8 match on failure (default yes)
209 * @return boolean true if string is ascii
213 static function isAscii($str, $utf8 = TRUE) {
214 if (!function_exists('mb_detect_encoding')) {
215 // eliminate all white space from the string
216 $str = preg_replace('/\s+/', '', $str);
217 // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work.
219 /* match low- or high-ascii characters */
220 if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) {
221 // || // low ascii characters
222 // high ascii characters
223 // preg_match( '/[\x7F-\xFF]/', $str ) ) {
225 /* if we did match, try for utf-8, or iso8859-1 */
227 return self
::isUtf8($str);
236 $order = array('ASCII');
240 $enc = mb_detect_encoding($str, $order, TRUE);
241 return ($enc == 'ASCII' ||
$enc == 'UTF-8');
246 * Determine the string replacements for redaction
247 * on the basis of the regular expressions
249 * @param string $str input string
250 * @param array $regexRules regular expression to be matched w/ replacements
252 * @return array $match array of strings w/ corresponding redacted outputs
256 static function regex($str, $regexRules) {
257 //redact the regular expressions
258 if (!empty($regexRules) && isset($str)) {
259 static $matches, $totalMatches, $match = array();
260 foreach ($regexRules as $pattern => $replacement) {
261 preg_match_all($pattern, $str, $matches);
262 if (!empty($matches[0])) {
263 if (empty($totalMatches)) {
264 $totalMatches = $matches[0];
267 $totalMatches = array_merge($totalMatches, $matches[0]);
269 $match = array_flip($totalMatches);
274 if (!empty($match)) {
275 foreach ($match as $matchKey => & $dontCare) {
276 foreach ($regexRules as $pattern => $replacement) {
277 if (preg_match($pattern, $matchKey)) {
278 $dontCare = $replacement . substr(md5($matchKey), 0, 5);
285 return CRM_Core_DAO
::$_nullArray;
290 * @param $stringRules
294 static function redaction($str, $stringRules) {
296 if (!empty($stringRules)) {
297 foreach ($stringRules as $match => $replace) {
298 $str = str_ireplace($match, $replace, $str);
302 //return the redacted output
307 * Determine if a string is composed only of utf8 characters
309 * @param string $str input string
315 static function isUtf8($str) {
316 if (!function_exists(mb_detect_encoding
)) {
317 // eliminate all white space from the string
318 $str = preg_replace('/\s+/', '', $str);
320 /* pattern stolen from the php.net function documentation for
322 * comment by JF Sebastian, 30-Mar-2005
325 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);
327 // iconv('ISO-8859-1', 'UTF-8', $str);
330 $enc = mb_detect_encoding($str, array('UTF-8'), TRUE);
331 return ($enc !== FALSE);
336 * Determine if two href's are equivalent (fuzzy match)
338 * @param string $url1 the first url to be matched
339 * @param string $url2 the second url to be matched against
341 * @return boolean true if the urls match, else false
345 static function match($url1, $url2) {
346 $url1 = strtolower($url1);
347 $url2 = strtolower($url2);
349 $url1Str = parse_url($url1);
350 $url2Str = parse_url($url2);
352 if ($url1Str['path'] == $url2Str['path'] &&
353 self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url1Str)) == self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url2Str))
361 * Extract variable values
363 * @param mix $query this is basically url
365 * @return mix $v returns civicrm url (eg: civicrm/contact/search/...)
369 static function extractURLVarValue($query) {
370 $config = CRM_Core_Config
::singleton();
371 $urlVar = $config->userFrameworkURLVar
;
373 $params = explode('&', $query);
374 foreach ($params as $p) {
375 if (strpos($p, '=')) {
376 list($k, $v) = explode('=', $p);
386 * Translate a true/false/yes/no string to a 0 or 1 value
388 * @param string $str the string to be translated
394 static function strtobool($str) {
395 if (!is_scalar($str)) {
399 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
406 * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
408 * @param string $str the string to be translated
414 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 the string to be converted
435 * @return string the converted string
439 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 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 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 all alternatives as a long string (or some other text)
527 * @return string only the first alternative found (or the text without alternatives)
529 static function stripAlternatives($full) {
531 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
533 if (isset($matches[1]) &&
534 trim(strip_tags($matches[1])) != ''
544 * Strip leading, trailing, double spaces from string
545 * used for postal/greeting/addressee
547 * @param string $string input string to be cleaned
549 * @return string the cleaned string
553 static function stripSpaces($string) {
554 return (empty($string)) ?
$string : preg_replace("/\s{2,}/", " ", trim($string));
558 * This function is used to clean the URL 'path' variable that we use
559 * to construct CiviCRM urls by removing characters from the path variable
561 * @param string $string the input string to be sanitized
562 * @param array $search the characters to be sanitized
563 * @param string $replace the character to replace it with
565 * @return string the sanitized string
569 static function stripPathChars($string,
573 static $_searchChars = NULL;
574 static $_replaceChar = NULL;
576 if (empty($string)) {
580 if ($_searchChars == NULL) {
581 $_searchChars = array(
582 '&', ';', ',', '=', '$',
585 ' ', "\r", "\r\n", "\n", "\t",
591 if ($search == NULL) {
592 $search = $_searchChars;
595 if ($replace == NULL) {
596 $replace = $_replaceChar;
599 return str_replace($search, $replace, $string);
604 * Use HTMLPurifier to clean up a text string and remove any potential
605 * xss attacks. This is primarily used in public facing pages which
606 * accept html as the input string
608 * @param string $string the input string
610 * @return string the cleaned up string
614 static function purifyHTML($string) {
615 static $_filter = null;
617 $config = HTMLPurifier_Config
::createDefault();
618 $config->set('Core.Encoding', 'UTF-8');
620 // Disable the cache entirely
621 $config->set('Cache.DefinitionImpl', null);
623 $_filter = new HTMLPurifier($config);
626 return $_filter->purify($string);
630 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
632 * @param string $string
637 static function ellipsify($string, $maxLen) {
638 $len = strlen($string);
639 if ($len <= $maxLen) {
643 return substr($string, 0, $maxLen-3) . '...';
648 * Generate a random string
654 public static function createRandom($len, $alphabet) {
655 $alphabetSize = strlen($alphabet);
657 for ($i = 0; $i < $len; $i++
) {
658 $result .= $alphabet{rand(1, $alphabetSize) - 1};
665 * "admin foo" => array(NULL,"admin foo")
666 * "cms:admin foo" => array("cms", "admin foo")
669 * @param string $string e.g. "view all contacts". Syntax: "[prefix:]name"
670 * @param null $defaultPrefix
672 * @return array (0 => string|NULL $prefix, 1 => string $value)
674 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
675 $pos = strpos($string, $delim);
676 if ($pos === FALSE) {
677 return array($defaultPrefix, $string);
680 return array(substr($string, 0, $pos), substr($string, 1+
$pos));
685 * This function will mask part of the the user portion of an Email address (everything before the @)
687 * @param string $email the email address to be masked
688 * @param string $maskChar the character used for masking
689 * @param integer $percent the percentage of the user portion to be masked
691 * @return string returns the masked Email address
693 public static function maskEmail($email, $maskChar= '*', $percent=50) {
694 list($user, $domain) = preg_split("/@/", $email);
695 $len = strlen($user);
696 $maskCount = floor($len * $percent /100);
697 $offset = floor(($len - $maskCount) / 2);
699 $masked = substr($user, 0, $offset)
700 .str_repeat($maskChar, $maskCount)
701 .substr($user, $maskCount +
$offset);
703 return($masked.'@'.$domain);
707 * This function compares two strings
709 * @param string $strOne string one
710 * @param string $strTwo string two
711 * @param boolean $case boolean indicating whether you want the comparison to be case sensitive or not
713 * @return boolean TRUE (string are identical); FALSE (strings are not identical)
715 public static function compareStr($strOne, $strTwo, $case) {
717 // Convert to lowercase and trim white spaces
718 if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) {
719 // yes - they are identical
727 if ($case == FALSE) {
729 if (trim($strOne) == trim($strTwo)) {
730 // yes - they are identical
741 * Many parts of the codebase have a convention of internally passing around
742 * HTML-encoded URLs. This effectively means that "&" is replaced by "&"
743 * (because most other odd characters are %-escaped in URLs; and %-escaped
744 * strings don't need any extra escaping in HTML).
746 * @param string $url URL with HTML entities
747 * @return string URL without HTML entities
749 public static function unstupifyUrl($htmlUrl) {
750 return str_replace('&', '&', $htmlUrl);