3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 * @return string An equivalent variable name
60 * @return string (or null)
63 static function titleToVar($title, $maxLength = 31) {
64 $variable = self
::munge($title, '_', $maxLength);
66 if (CRM_Utils_Rule
::title($variable, $maxLength)) {
70 // if longer than the maxLength lets just return a substr of the
71 // md5 to prevent errors downstream
72 return substr(md5($title), 0, $maxLength);
76 * given a string, replace all non alpha numeric characters and
77 * spaces with the replacement character
79 * @param string $name the name to be worked on
80 * @param string $char the character to use for non-valid chars
81 * @param int $len length of valid variables
85 * @return string returns the manipulated string
88 static function munge($name, $char = '_', $len = 63) {
89 // replace all white space and non-alpha numeric with $char
90 // we only use the ascii character set since mysql does not create table names / field names otherwise
92 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
95 // lets keep variable names short
96 return substr($name, 0, $len);
105 * Takes a variable name and munges it randomly into another variable name
107 * @param string $name Initial Variable Name
108 * @param int $len length of valid variables
110 * @return string Randomized Variable Name
114 static function rename($name, $len = 4) {
115 $rand = substr(uniqid(), 0, $len);
116 return substr_replace($name, $rand, -$len, $len);
120 * takes a string and returns the last tuple of the string.
121 * useful while converting file names to class names etc
123 * @param string $string the input string
124 * @param char $char the character used to demarcate the componets
128 * @return string the last component
131 static function getClassName($string, $char = '_') {
133 if (!is_array($string)) {
134 $names = explode($char, $string);
136 if (!empty($names)) {
137 return array_pop($names);
142 * appends a name to a string and seperated by delimiter.
143 * does the right thing for an empty string
145 * @param string $str the string to be appended to
146 * @param string $delim the delimiter to use
147 * @param mixed $name the string (or array of strings) to append
153 static function append(&$str, $delim, $name) {
158 if (is_array($name)) {
159 foreach ($name as $n) {
176 $str .= $delim . $name;
182 * determine if the string is composed only of ascii characters
184 * @param string $str input string
185 * @param boolean $utf8 attempt utf8 match on failure (default yes)
187 * @return boolean true if string is ascii
191 static function isAscii($str, $utf8 = TRUE) {
192 if (!function_exists('mb_detect_encoding')) {
193 // eliminate all white space from the string
194 $str = preg_replace('/\s+/', '', $str);
195 // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work.
197 /* match low- or high-ascii characters */
198 if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) {
199 // || // low ascii characters
200 // high ascii characters
201 // preg_match( '/[\x7F-\xFF]/', $str ) ) {
203 /* if we did match, try for utf-8, or iso8859-1 */
205 return self
::isUtf8($str);
214 $order = array('ASCII');
218 $enc = mb_detect_encoding($str, $order, TRUE);
219 return ($enc == 'ASCII' ||
$enc == 'UTF-8');
224 * determine the string replacements for redaction
225 * on the basis of the regular expressions
227 * @param string $str input string
228 * @param array $regexRules regular expression to be matched w/ replacements
230 * @return array $match array of strings w/ corresponding redacted outputs
234 static function regex($str, $regexRules) {
235 //redact the regular expressions
236 if (!empty($regexRules) && isset($str)) {
237 static $matches, $totalMatches, $match = array();
238 foreach ($regexRules as $pattern => $replacement) {
239 preg_match_all($pattern, $str, $matches);
240 if (!empty($matches[0])) {
241 if (empty($totalMatches)) {
242 $totalMatches = $matches[0];
245 $totalMatches = array_merge($totalMatches, $matches[0]);
247 $match = array_flip($totalMatches);
252 if (!empty($match)) {
253 foreach ($match as $matchKey => & $dontCare) {
254 foreach ($regexRules as $pattern => $replacement) {
255 if (preg_match($pattern, $matchKey)) {
256 $dontCare = $replacement . substr(md5($matchKey), 0, 5);
263 return CRM_Core_DAO
::$_nullArray;
266 static function redaction($str, $stringRules) {
268 if (!empty($stringRules)) {
269 foreach ($stringRules as $match => $replace) {
270 $str = str_ireplace($match, $replace, $str);
274 //return the redacted output
279 * Determine if a string is composed only of utf8 characters
281 * @param string $str input string
287 static function isUtf8($str) {
288 if (!function_exists(mb_detect_encoding
)) {
289 // eliminate all white space from the string
290 $str = preg_replace('/\s+/', '', $str);
292 /* pattern stolen from the php.net function documentation for
294 * comment by JF Sebastian, 30-Mar-2005
297 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);
299 // iconv('ISO-8859-1', 'UTF-8', $str);
302 $enc = mb_detect_encoding($str, array('UTF-8'), TRUE);
303 return ($enc !== FALSE);
308 * determine if two href's are equivalent (fuzzy match)
310 * @param string $url1 the first url to be matched
311 * @param string $url2 the second url to be matched against
313 * @return boolean true if the urls match, else false
317 static function match($url1, $url2) {
318 $url1 = strtolower($url1);
319 $url2 = strtolower($url2);
321 $url1Str = parse_url($url1);
322 $url2Str = parse_url($url2);
324 if ($url1Str['path'] == $url2Str['path'] &&
325 self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url1Str)) == self
::extractURLVarValue(CRM_Utils_Array
::value('query', $url2Str))
333 * Function to extract variable values
335 * @param mix $query this is basically url
337 * @return mix $v returns civicrm url (eg: civicrm/contact/search/...)
341 static function extractURLVarValue($query) {
342 $config = CRM_Core_Config
::singleton();
343 $urlVar = $config->userFrameworkURLVar
;
345 $params = explode('&', $query);
346 foreach ($params as $p) {
347 if (strpos($p, '=')) {
348 list($k, $v) = explode('=', $p);
358 * translate a true/false/yes/no string to a 0 or 1 value
360 * @param string $str the string to be translated
366 static function strtobool($str) {
367 if (!is_scalar($str)) {
371 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
378 * returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
380 * @param string $str the string to be translated
386 static function strtoboolstr($str) {
387 if (!is_scalar($str)) {
391 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
394 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
403 * Convert a HTML string into a text one using html2text
405 * @param string $html the tring to be converted
407 * @return string the converted string
411 static function htmlToText($html) {
412 require_once 'packages/html2text/rcube_html2text.php';
413 $converter = new rcube_html2text($html);
414 return $converter->get_text();
417 static function extractName($string, &$params) {
418 $name = trim($string);
424 $name = str_replace('"', '', $name);
425 $name = str_replace('\'', '', $name);
427 // check for comma in name
428 if (strpos($name, ',') !== FALSE) {
430 // name has a comma - assume lname, fname [mname]
431 $names = explode(',', $name);
432 if (count($names) > 1) {
433 $params['last_name'] = trim($names[0]);
435 // check for space delim
436 $fnames = explode(' ', trim($names[1]));
437 if (count($fnames) > 1) {
438 $params['first_name'] = trim($fnames[0]);
439 $params['middle_name'] = trim($fnames[1]);
442 $params['first_name'] = trim($fnames[0]);
446 $params['first_name'] = trim($names[0]);
450 // name has no comma - assume fname [mname] fname
451 $names = explode(' ', $name);
452 if (count($names) == 1) {
453 $params['first_name'] = $names[0];
455 elseif (count($names) == 2) {
456 $params['first_name'] = $names[0];
457 $params['last_name'] = $names[1];
460 $params['first_name'] = $names[0];
461 $params['middle_name'] = $names[1];
462 $params['last_name'] = $names[2];
467 static function &makeArray($string) {
468 $string = trim($string);
470 $values = explode("\n", $string);
472 foreach ($values as $value) {
473 list($n, $v) = CRM_Utils_System
::explode('=', $value, 2);
475 $result[trim($n)] = trim($v);
482 * Function to add include files needed for jquery
484 * This appears to be used in cases where the normal html-header
485 * provided by CRM_Core_Resources can't be used (e.g. when outputting in
486 * "print" mode, the execution will short-circuit without allowing the
487 * CMS to output JS/CSS tags).
489 static function addJqueryFiles(&$html) {
490 CRM_Core_Resources
::singleton()->addCoreResources('html-header');
491 return CRM_Core_Region
::instance('html-header')->render('', FALSE) . $html;
495 * Given an ezComponents-parsed representation of
496 * a text with alternatives return only the first one
498 * @param string $full all alternatives as a long string (or some other text)
500 * @return string only the first alternative found (or the text without alternatives)
502 static function stripAlternatives($full) {
504 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
506 if (isset($matches[1]) &&
507 trim(strip_tags($matches[1])) != ''
517 * strip leading, trailing, double spaces from string
518 * used for postal/greeting/addressee
520 * @param string $string input string to be cleaned
522 * @return string the cleaned string
526 static function stripSpaces($string) {
527 return (empty($string)) ?
$string : preg_replace("/\s{2,}/", " ", trim($string));
531 * This function is used to clean the URL 'path' variable that we use
532 * to construct CiviCRM urls by removing characters from the path variable
534 * @param string $string the input string to be sanitized
535 * @param array $search the characters to be sanitized
536 * @param string $replace the character to replace it with
538 * @return string the sanitized string
542 static function stripPathChars($string,
546 static $_searchChars = NULL;
547 static $_replaceChar = NULL;
549 if (empty($string)) {
553 if ($_searchChars == NULL) {
554 $_searchChars = array(
555 '&', ';', ',', '=', '$',
558 ' ', "\r", "\r\n", "\n", "\t",
564 if ($search == NULL) {
565 $search = $_searchChars;
568 if ($replace == NULL) {
569 $replace = $_replaceChar;
572 return str_replace($search, $replace, $string);
577 * Use HTMLPurifier to clean up a text string and remove any potential
578 * xss attacks. This is primarily used in public facing pages which
579 * accept html as the input string
581 * @param string $string the input string
583 * @return string the cleaned up string
587 static function purifyHTML($string) {
588 static $_filter = null;
590 $config = HTMLPurifier_Config
::createDefault();
591 $config->set('Core.Encoding', 'UTF-8');
593 // Disable the cache entirely
594 $config->set('Cache.DefinitionImpl', null);
596 $_filter = new HTMLPurifier($config);
599 return $_filter->purify($string);
603 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
605 * @param string $string
608 static function ellipsify($string, $maxLen) {
609 $len = strlen($string);
610 if ($len <= $maxLen) {
614 return substr($string, 0, $maxLen-3) . '...';
619 * Generate a random string
625 public static function createRandom($len, $alphabet) {
626 $alphabetSize = strlen($alphabet);
628 for ($i = 0; $i < $len; $i++
) {
629 $result .= $alphabet{rand(1, $alphabetSize) - 1};
636 * "admin foo" => array(NULL,"admin foo")
637 * "cms:admin foo" => array("cms", "admin foo")
639 * @param string $string e.g. "view all contacts". Syntax: "[prefix:]name"
640 * @return array (0 => string|NULL $prefix, 1 => string $value)
642 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
643 $pos = strpos($string, $delim);
644 if ($pos === FALSE) {
645 return array($defaultPrefix, $string);
648 return array(substr($string, 0, $pos), substr($string, 1+
$pos));