Merge pull request #3273 from joannechester/master
[civicrm-core.git] / CRM / Utils / String.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 require_once 'HTML/QuickForm/Rule/Email.php';
37
38 /**
39 * This class contains string functions
40 *
41 */
42 class CRM_Utils_String {
43 CONST COMMA = ",", SEMICOLON = ";", SPACE = " ", TAB = "\t", LINEFEED = "\n", CARRIAGELINE = "\r\n", LINECARRIAGE = "\n\r", CARRIAGERETURN = "\r";
44
45 /**
46 * List of all letters and numbers
47 */
48 const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
49
50 /**
51 * Convert a display name into a potential variable
52 * name that we could use in forms/code
53 *
54 * @param name Name of the string
55 *
56 * @param int $maxLength
57 *
58 * @return string An equivalent variable name
59 *
60 * @access public
61 *
62 * @return string (or null)
63 * @static
64 */
65 static function titleToVar($title, $maxLength = 31) {
66 $variable = self::munge($title, '_', $maxLength);
67
68 if (CRM_Utils_Rule::title($variable, $maxLength)) {
69 return $variable;
70 }
71
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);
75 }
76
77 /**
78 * given a string, replace all non alpha numeric characters and
79 * spaces with the replacement character
80 *
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
84 *
85 * @access public
86 *
87 * @return string returns the manipulated string
88 * @static
89 */
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
93 // CRM-11744
94 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
95
96 if ($len) {
97 // lets keep variable names short
98 return substr($name, 0, $len);
99 }
100 else {
101 return $name;
102 }
103 }
104
105 /**
106 *
107 * Takes a variable name and munges it randomly into another variable name
108 *
109 * @param string $name Initial Variable Name
110 * @param int $len length of valid variables
111 *
112 * @return string Randomized Variable Name
113 * @access public
114 * @static
115 */
116 static function rename($name, $len = 4) {
117 $rand = substr(uniqid(), 0, $len);
118 return substr_replace($name, $rand, -$len, $len);
119 }
120
121 /**
122 * takes a string and returns the last tuple of the string.
123 * useful while converting file names to class names etc
124 *
125 * @param string $string the input string
126 * @param \char|string $char $char the character used to demarcate the componets
127 *
128 * @access public
129 *
130 * @return string the last component
131 * @static
132 */
133 static function getClassName($string, $char = '_') {
134 $names = array();
135 if (!is_array($string)) {
136 $names = explode($char, $string);
137 }
138 if (!empty($names)) {
139 return array_pop($names);
140 }
141 }
142
143 /**
144 * appends a name to a string and seperated by delimiter.
145 * does the right thing for an empty string
146 *
147 * @param string $str the string to be appended to
148 * @param string $delim the delimiter to use
149 * @param mixed $name the string (or array of strings) to append
150 *
151 * @return void
152 * @access public
153 * @static
154 */
155 static function append(&$str, $delim, $name) {
156 if (empty($name)) {
157 return;
158 }
159
160 if (is_array($name)) {
161 foreach ($name as $n) {
162 if (empty($n)) {
163 continue;
164 }
165 if (empty($str)) {
166 $str = $n;
167 }
168 else {
169 $str .= $delim . $n;
170 }
171 }
172 }
173 else {
174 if (empty($str)) {
175 $str = $name;
176 }
177 else {
178 $str .= $delim . $name;
179 }
180 }
181 }
182
183 /**
184 * determine if the string is composed only of ascii characters
185 *
186 * @param string $str input string
187 * @param boolean $utf8 attempt utf8 match on failure (default yes)
188 *
189 * @return boolean true if string is ascii
190 * @access public
191 * @static
192 */
193 static function isAscii($str, $utf8 = TRUE) {
194 if (!function_exists('mb_detect_encoding')) {
195 // eliminate all white space from the string
196 $str = preg_replace('/\s+/', '', $str);
197 // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work.
198
199 /* match low- or high-ascii characters */
200 if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) {
201 // || // low ascii characters
202 // high ascii characters
203 // preg_match( '/[\x7F-\xFF]/', $str ) ) {
204 if ($utf8) {
205 /* if we did match, try for utf-8, or iso8859-1 */
206
207 return self::isUtf8($str);
208 }
209 else {
210 return FALSE;
211 }
212 }
213 return TRUE;
214 }
215 else {
216 $order = array('ASCII');
217 if ($utf8) {
218 $order[] = 'UTF-8';
219 }
220 $enc = mb_detect_encoding($str, $order, TRUE);
221 return ($enc == 'ASCII' || $enc == 'UTF-8');
222 }
223 }
224
225 /**
226 * determine the string replacements for redaction
227 * on the basis of the regular expressions
228 *
229 * @param string $str input string
230 * @param array $regexRules regular expression to be matched w/ replacements
231 *
232 * @return array $match array of strings w/ corresponding redacted outputs
233 * @access public
234 * @static
235 */
236 static function regex($str, $regexRules) {
237 //redact the regular expressions
238 if (!empty($regexRules) && isset($str)) {
239 static $matches, $totalMatches, $match = array();
240 foreach ($regexRules as $pattern => $replacement) {
241 preg_match_all($pattern, $str, $matches);
242 if (!empty($matches[0])) {
243 if (empty($totalMatches)) {
244 $totalMatches = $matches[0];
245 }
246 else {
247 $totalMatches = array_merge($totalMatches, $matches[0]);
248 }
249 $match = array_flip($totalMatches);
250 }
251 }
252 }
253
254 if (!empty($match)) {
255 foreach ($match as $matchKey => & $dontCare) {
256 foreach ($regexRules as $pattern => $replacement) {
257 if (preg_match($pattern, $matchKey)) {
258 $dontCare = $replacement . substr(md5($matchKey), 0, 5);
259 break;
260 }
261 }
262 }
263 return $match;
264 }
265 return CRM_Core_DAO::$_nullArray;
266 }
267
268 static function redaction($str, $stringRules) {
269 //redact the strings
270 if (!empty($stringRules)) {
271 foreach ($stringRules as $match => $replace) {
272 $str = str_ireplace($match, $replace, $str);
273 }
274 }
275
276 //return the redacted output
277 return $str;
278 }
279
280 /**
281 * Determine if a string is composed only of utf8 characters
282 *
283 * @param string $str input string
284 * @access public
285 * @static
286 *
287 * @return boolean
288 */
289 static function isUtf8($str) {
290 if (!function_exists(mb_detect_encoding)) {
291 // eliminate all white space from the string
292 $str = preg_replace('/\s+/', '', $str);
293
294 /* pattern stolen from the php.net function documentation for
295 * utf8decode();
296 * comment by JF Sebastian, 30-Mar-2005
297 */
298
299 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);
300 // ||
301 // iconv('ISO-8859-1', 'UTF-8', $str);
302 }
303 else {
304 $enc = mb_detect_encoding($str, array('UTF-8'), TRUE);
305 return ($enc !== FALSE);
306 }
307 }
308
309 /**
310 * determine if two href's are equivalent (fuzzy match)
311 *
312 * @param string $url1 the first url to be matched
313 * @param string $url2 the second url to be matched against
314 *
315 * @return boolean true if the urls match, else false
316 * @access public
317 * @static
318 */
319 static function match($url1, $url2) {
320 $url1 = strtolower($url1);
321 $url2 = strtolower($url2);
322
323 $url1Str = parse_url($url1);
324 $url2Str = parse_url($url2);
325
326 if ($url1Str['path'] == $url2Str['path'] &&
327 self::extractURLVarValue(CRM_Utils_Array::value('query', $url1Str)) == self::extractURLVarValue(CRM_Utils_Array::value('query', $url2Str))
328 ) {
329 return TRUE;
330 }
331 return FALSE;
332 }
333
334 /**
335 * Function to extract variable values
336 *
337 * @param mix $query this is basically url
338 *
339 * @return mix $v returns civicrm url (eg: civicrm/contact/search/...)
340 * @access public
341 * @static
342 */
343 static function extractURLVarValue($query) {
344 $config = CRM_Core_Config::singleton();
345 $urlVar = $config->userFrameworkURLVar;
346
347 $params = explode('&', $query);
348 foreach ($params as $p) {
349 if (strpos($p, '=')) {
350 list($k, $v) = explode('=', $p);
351 if ($k == $urlVar) {
352 return $v;
353 }
354 }
355 }
356 return NULL;
357 }
358
359 /**
360 * translate a true/false/yes/no string to a 0 or 1 value
361 *
362 * @param string $str the string to be translated
363 *
364 * @return boolean
365 * @access public
366 * @static
367 */
368 static function strtobool($str) {
369 if (!is_scalar($str)) {
370 return FALSE;
371 }
372
373 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
374 return TRUE;
375 }
376 return FALSE;
377 }
378
379 /**
380 * returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
381 *
382 * @param string $str the string to be translated
383 *
384 * @return boolean
385 * @access public
386 * @static
387 */
388 static function strtoboolstr($str) {
389 if (!is_scalar($str)) {
390 return FALSE;
391 }
392
393 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
394 return '1';
395 }
396 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
397 return '0';
398 }
399 else {
400 return FALSE;
401 }
402 }
403
404 /**
405 * Convert a HTML string into a text one using html2text
406 *
407 * @param string $html the string to be converted
408 *
409 * @return string the converted string
410 * @access public
411 * @static
412 */
413 static function htmlToText($html) {
414 require_once 'packages/html2text/rcube_html2text.php';
415 $token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html);
416 $converter = new rcube_html2text($token_html);
417 $token_text = $converter->get_text();
418 $text = preg_replace('!token\:\{([a-z_.]+)\}!i', '{$1}', $token_text);
419 return $text;
420 }
421
422 static function extractName($string, &$params) {
423 $name = trim($string);
424 if (empty($name)) {
425 return;
426 }
427
428 // strip out quotes
429 $name = str_replace('"', '', $name);
430 $name = str_replace('\'', '', $name);
431
432 // check for comma in name
433 if (strpos($name, ',') !== FALSE) {
434
435 // name has a comma - assume lname, fname [mname]
436 $names = explode(',', $name);
437 if (count($names) > 1) {
438 $params['last_name'] = trim($names[0]);
439
440 // check for space delim
441 $fnames = explode(' ', trim($names[1]));
442 if (count($fnames) > 1) {
443 $params['first_name'] = trim($fnames[0]);
444 $params['middle_name'] = trim($fnames[1]);
445 }
446 else {
447 $params['first_name'] = trim($fnames[0]);
448 }
449 }
450 else {
451 $params['first_name'] = trim($names[0]);
452 }
453 }
454 else {
455 // name has no comma - assume fname [mname] fname
456 $names = explode(' ', $name);
457 if (count($names) == 1) {
458 $params['first_name'] = $names[0];
459 }
460 elseif (count($names) == 2) {
461 $params['first_name'] = $names[0];
462 $params['last_name'] = $names[1];
463 }
464 else {
465 $params['first_name'] = $names[0];
466 $params['middle_name'] = $names[1];
467 $params['last_name'] = $names[2];
468 }
469 }
470 }
471
472 static function &makeArray($string) {
473 $string = trim($string);
474
475 $values = explode("\n", $string);
476 $result = array();
477 foreach ($values as $value) {
478 list($n, $v) = CRM_Utils_System::explode('=', $value, 2);
479 if (!empty($v)) {
480 $result[trim($n)] = trim($v);
481 }
482 }
483 return $result;
484 }
485
486 /**
487 * Given an ezComponents-parsed representation of
488 * a text with alternatives return only the first one
489 *
490 * @param string $full all alternatives as a long string (or some other text)
491 *
492 * @return string only the first alternative found (or the text without alternatives)
493 */
494 static function stripAlternatives($full) {
495 $matches = array();
496 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
497
498 if (isset($matches[1]) &&
499 trim(strip_tags($matches[1])) != ''
500 ) {
501 return $matches[1];
502 }
503 else {
504 return $full;
505 }
506 }
507
508 /**
509 * strip leading, trailing, double spaces from string
510 * used for postal/greeting/addressee
511 *
512 * @param string $string input string to be cleaned
513 *
514 * @return string the cleaned string
515 * @access public
516 * @static
517 */
518 static function stripSpaces($string) {
519 return (empty($string)) ? $string : preg_replace("/\s{2,}/", " ", trim($string));
520 }
521
522 /**
523 * This function is used to clean the URL 'path' variable that we use
524 * to construct CiviCRM urls by removing characters from the path variable
525 *
526 * @param string $string the input string to be sanitized
527 * @param array $search the characters to be sanitized
528 * @param string $replace the character to replace it with
529 *
530 * @return string the sanitized string
531 * @access public
532 * @static
533 */
534 static function stripPathChars($string,
535 $search = NULL,
536 $replace = NULL
537 ) {
538 static $_searchChars = NULL;
539 static $_replaceChar = NULL;
540
541 if (empty($string)) {
542 return $string;
543 }
544
545 if ($_searchChars == NULL) {
546 $_searchChars = array(
547 '&', ';', ',', '=', '$',
548 '"', "'", '\\',
549 '<', '>', '(', ')',
550 ' ', "\r", "\r\n", "\n", "\t",
551 );
552 $_replaceChar = '_';
553 }
554
555
556 if ($search == NULL) {
557 $search = $_searchChars;
558 }
559
560 if ($replace == NULL) {
561 $replace = $_replaceChar;
562 }
563
564 return str_replace($search, $replace, $string);
565 }
566
567
568 /**
569 * Use HTMLPurifier to clean up a text string and remove any potential
570 * xss attacks. This is primarily used in public facing pages which
571 * accept html as the input string
572 *
573 * @param string $string the input string
574 *
575 * @return string the cleaned up string
576 * @public
577 * @static
578 */
579 static function purifyHTML($string) {
580 static $_filter = null;
581 if (!$_filter) {
582 $config = HTMLPurifier_Config::createDefault();
583 $config->set('Core.Encoding', 'UTF-8');
584
585 // Disable the cache entirely
586 $config->set('Cache.DefinitionImpl', null);
587
588 $_filter = new HTMLPurifier($config);
589 }
590
591 return $_filter->purify($string);
592 }
593
594 /**
595 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
596 *
597 * @param string $string
598 * @param int $maxLen
599 *
600 * @return string
601 */
602 static function ellipsify($string, $maxLen) {
603 $len = strlen($string);
604 if ($len <= $maxLen) {
605 return $string;
606 }
607 else {
608 return substr($string, 0, $maxLen-3) . '...';
609 }
610 }
611
612 /**
613 * Generate a random string
614 *
615 * @param $len
616 * @param $alphabet
617 * @return string
618 */
619 public static function createRandom($len, $alphabet) {
620 $alphabetSize = strlen($alphabet);
621 $result = '';
622 for ($i = 0; $i < $len; $i++) {
623 $result .= $alphabet{rand(1, $alphabetSize) - 1};
624 }
625 return $result;
626 }
627
628 /**
629 * Examples:
630 * "admin foo" => array(NULL,"admin foo")
631 * "cms:admin foo" => array("cms", "admin foo")
632 *
633 * @param $delim
634 * @param string $string e.g. "view all contacts". Syntax: "[prefix:]name"
635 * @param null $defaultPrefix
636 *
637 * @return array (0 => string|NULL $prefix, 1 => string $value)
638 */
639 public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
640 $pos = strpos($string, $delim);
641 if ($pos === FALSE) {
642 return array($defaultPrefix, $string);
643 }
644 else {
645 return array(substr($string, 0, $pos), substr($string, 1+$pos));
646 }
647 }
648
649 /**
650 * this function will mask part of the the user portion of an Email address (everything before the @)
651 *
652 * @param string $email the email address to be masked
653 * @param string $maskChar the character used for masking
654 * @param integer $percent the percentage of the user portion to be masked
655 *
656 * @return string returns the masked Email address
657 */
658 public static function maskEmail($email, $maskChar= '*', $percent=50) {
659 list($user, $domain) = preg_split("/@/", $email);
660 $len = strlen($user);
661 $maskCount = floor($len * $percent /100);
662 $offset = floor(($len - $maskCount) / 2);
663
664 $masked = substr($user, 0, $offset)
665 .str_repeat($maskChar, $maskCount)
666 .substr($user, $maskCount + $offset);
667
668 return($masked.'@'.$domain);
669 }
670
671 /**
672 * this function compares two strings
673 *
674 * @param string $strOne string one
675 * @param string $strTwo string two
676 * @param boolean $case boolean indicating whether you want the comparison to be case sensitive or not
677 *
678 * @return boolean TRUE (string are identical); FALSE (strings are not identical)
679 */
680 public static function compareStr($strOne, $strTwo, $case) {
681 if ($case == TRUE) {
682 // Convert to lowercase and trim white spaces
683 if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) {
684 // yes - they are identical
685 return TRUE;
686 }
687 else {
688 // not identical
689 return FALSE;
690 }
691 }
692 if ($case == FALSE) {
693 // Trim white spaces
694 if (trim($strOne) == trim($strTwo)) {
695 // yes - they are identical
696 return TRUE;
697 }
698 else {
699 // not identical
700 return FALSE;
701 }
702 }
703 }
704
705 }
706