Import from SVN (r45945, r596)
[civicrm-core.git] / CRM / Utils / String.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36require_once 'HTML/QuickForm/Rule/Email.php';
37
38/**
39 * This class contains string functions
40 *
41 */
42class 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 * @return string An equivalent variable name
57 *
58 * @access public
59 *
60 * @return string (or null)
61 * @static
62 */
63 static function titleToVar($title, $maxLength = 31) {
64 $variable = self::munge($title, '_', $maxLength);
65
66 if (CRM_Utils_Rule::title($variable, $maxLength)) {
67 return $variable;
68 }
69
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);
73 }
74
75 /**
76 * given a string, replace all non alpha numeric characters and
77 * spaces with the replacement character
78 *
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
82 *
83 * @access public
84 *
85 * @return string returns the manipulated string
86 * @static
87 */
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
91 // CRM-11744
92 $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
93
94 if ($len) {
95 // lets keep variable names short
96 return substr($name, 0, $len);
97 }
98 else {
99 return $name;
100 }
101 }
102
103 /**
104 *
105 * Takes a variable name and munges it randomly into another variable name
106 *
107 * @param string $name Initial Variable Name
108 * @param int $len length of valid variables
109 *
110 * @return string Randomized Variable Name
111 * @access public
112 * @static
113 */
114 static function rename($name, $len = 4) {
115 $rand = substr(uniqid(), 0, $len);
116 return substr_replace($name, $rand, -$len, $len);
117 }
118
119 /**
120 * takes a string and returns the last tuple of the string.
121 * useful while converting file names to class names etc
122 *
123 * @param string $string the input string
124 * @param char $char the character used to demarcate the componets
125 *
126 * @access public
127 *
128 * @return string the last component
129 * @static
130 */
131 static function getClassName($string, $char = '_') {
132 $names = array();
133 if (!is_array($string)) {
134 $names = explode($char, $string);
135 }
136 if (!empty($names)) {
137 return array_pop($names);
138 }
139 }
140
141 /**
142 * appends a name to a string and seperated by delimiter.
143 * does the right thing for an empty string
144 *
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
148 *
149 * @return void
150 * @access public
151 * @static
152 */
153 static function append(&$str, $delim, $name) {
154 if (empty($name)) {
155 return;
156 }
157
158 if (is_array($name)) {
159 foreach ($name as $n) {
160 if (empty($n)) {
161 continue;
162 }
163 if (empty($str)) {
164 $str = $n;
165 }
166 else {
167 $str .= $delim . $n;
168 }
169 }
170 }
171 else {
172 if (empty($str)) {
173 $str = $name;
174 }
175 else {
176 $str .= $delim . $name;
177 }
178 }
179 }
180
181 /**
182 * determine if the string is composed only of ascii characters
183 *
184 * @param string $str input string
185 * @param boolean $utf8 attempt utf8 match on failure (default yes)
186 *
187 * @return boolean true if string is ascii
188 * @access public
189 * @static
190 */
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.
196
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 ) ) {
202 if ($utf8) {
203 /* if we did match, try for utf-8, or iso8859-1 */
204
205 return self::isUtf8($str);
206 }
207 else {
208 return FALSE;
209 }
210 }
211 return TRUE;
212 }
213 else {
214 $order = array('ASCII');
215 if ($utf8) {
216 $order[] = 'UTF-8';
217 }
218 $enc = mb_detect_encoding($str, $order, TRUE);
219 return ($enc == 'ASCII' || $enc == 'UTF-8');
220 }
221 }
222
223 /**
224 * determine the string replacements for redaction
225 * on the basis of the regular expressions
226 *
227 * @param string $str input string
228 * @param array $regexRules regular expression to be matched w/ replacements
229 *
230 * @return array $match array of strings w/ corresponding redacted outputs
231 * @access public
232 * @static
233 */
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];
243 }
244 else {
245 $totalMatches = array_merge($totalMatches, $matches[0]);
246 }
247 $match = array_flip($totalMatches);
248 }
249 }
250 }
251
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);
257 break;
258 }
259 }
260 }
261 return $match;
262 }
263 return CRM_Core_DAO::$_nullArray;
264 }
265
266 static function redaction($str, $stringRules) {
267 //redact the strings
268 if (!empty($stringRules)) {
269 foreach ($stringRules as $match => $replace) {
270 $str = str_ireplace($match, $replace, $str);
271 }
272 }
273
274 //return the redacted output
275 return $str;
276 }
277
278 /**
279 * Determine if a string is composed only of utf8 characters
280 *
281 * @param string $str input string
282 * @access public
283 * @static
284 *
285 * @return boolean
286 */
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);
291
292 /* pattern stolen from the php.net function documentation for
293 * utf8decode();
294 * comment by JF Sebastian, 30-Mar-2005
295 */
296
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);
298 // ||
299 // iconv('ISO-8859-1', 'UTF-8', $str);
300 }
301 else {
302 $enc = mb_detect_encoding($str, array('UTF-8'), TRUE);
303 return ($enc !== FALSE);
304 }
305 }
306
307 /**
308 * determine if two href's are equivalent (fuzzy match)
309 *
310 * @param string $url1 the first url to be matched
311 * @param string $url2 the second url to be matched against
312 *
313 * @return boolean true if the urls match, else false
314 * @access public
315 * @static
316 */
317 static function match($url1, $url2) {
318 $url1 = strtolower($url1);
319 $url2 = strtolower($url2);
320
321 $url1Str = parse_url($url1);
322 $url2Str = parse_url($url2);
323
324 if ($url1Str['path'] == $url2Str['path'] &&
325 self::extractURLVarValue(CRM_Utils_Array::value('query', $url1Str)) == self::extractURLVarValue(CRM_Utils_Array::value('query', $url2Str))
326 ) {
327 return TRUE;
328 }
329 return FALSE;
330 }
331
332 /**
333 * Function to extract variable values
334 *
335 * @param mix $query this is basically url
336 *
337 * @return mix $v returns civicrm url (eg: civicrm/contact/search/...)
338 * @access public
339 * @static
340 */
341 static function extractURLVarValue($query) {
342 $config = CRM_Core_Config::singleton();
343 $urlVar = $config->userFrameworkURLVar;
344
345 $params = explode('&', $query);
346 foreach ($params as $p) {
347 if (strpos($p, '=')) {
348 list($k, $v) = explode('=', $p);
349 if ($k == $urlVar) {
350 return $v;
351 }
352 }
353 }
354 return NULL;
355 }
356
357 /**
358 * translate a true/false/yes/no string to a 0 or 1 value
359 *
360 * @param string $str the string to be translated
361 *
362 * @return boolean
363 * @access public
364 * @static
365 */
366 static function strtobool($str) {
367 if (!is_scalar($str)) {
368 return FALSE;
369 }
370
371 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
372 return TRUE;
373 }
374 return FALSE;
375 }
376
377 /**
378 * returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
379 *
380 * @param string $str the string to be translated
381 *
382 * @return boolean
383 * @access public
384 * @static
385 */
386 static function strtoboolstr($str) {
387 if (!is_scalar($str)) {
388 return FALSE;
389 }
390
391 if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) {
392 return '1';
393 }
394 elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) {
395 return '0';
396 }
397 else {
398 return FALSE;
399 }
400 }
401
402 /**
403 * Convert a HTML string into a text one using html2text
404 *
405 * @param string $html the tring to be converted
406 *
407 * @return string the converted string
408 * @access public
409 * @static
410 */
411 static function htmlToText($html) {
412 require_once 'packages/html2text/class.html2text.inc';
413 $converter = new html2text($html);
414 return $converter->get_text();
415 }
416
417 static function extractName($string, &$params) {
418 $name = trim($string);
419 if (empty($name)) {
420 return;
421 }
422
423 // strip out quotes
424 $name = str_replace('"', '', $name);
425 $name = str_replace('\'', '', $name);
426
427 // check for comma in name
428 if (strpos($name, ',') !== FALSE) {
429
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]);
434
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]);
440 }
441 else {
442 $params['first_name'] = trim($fnames[0]);
443 }
444 }
445 else {
446 $params['first_name'] = trim($names[0]);
447 }
448 }
449 else {
450 // name has no comma - assume fname [mname] fname
451 $names = explode(' ', $name);
452 if (count($names) == 1) {
453 $params['first_name'] = $names[0];
454 }
455 elseif (count($names) == 2) {
456 $params['first_name'] = $names[0];
457 $params['last_name'] = $names[1];
458 }
459 else {
460 $params['first_name'] = $names[0];
461 $params['middle_name'] = $names[1];
462 $params['last_name'] = $names[2];
463 }
464 }
465 }
466
467 static function &makeArray($string) {
468 $string = trim($string);
469
470 $values = explode("\n", $string);
471 $result = array();
472 foreach ($values as $value) {
473 list($n, $v) = CRM_Utils_System::explode('=', $value, 2);
474 if (!empty($v)) {
475 $result[trim($n)] = trim($v);
476 }
477 }
478 return $result;
479 }
480
481 /**
482 * Function to add include files needed for jquery
483 *
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).
488 */
489 static function addJqueryFiles(&$html) {
490 CRM_Core_Resources::singleton()->addCoreResources('html-header');
491 return CRM_Core_Region::instance('html-header')->render('', FALSE) . $html;
492 }
493
494 /**
495 * Given an ezComponents-parsed representation of
496 * a text with alternatives return only the first one
497 *
498 * @param string $full all alternatives as a long string (or some other text)
499 *
500 * @return string only the first alternative found (or the text without alternatives)
501 */
502 static function stripAlternatives($full) {
503 $matches = array();
504 preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
505
506 if (isset($matches[1]) &&
507 trim(strip_tags($matches[1])) != ''
508 ) {
509 return $matches[1];
510 }
511 else {
512 return $full;
513 }
514 }
515
516 /**
517 * strip leading, trailing, double spaces from string
518 * used for postal/greeting/addressee
519 *
520 * @param string $string input string to be cleaned
521 *
522 * @return string the cleaned string
523 * @access public
524 * @static
525 */
526 static function stripSpaces($string) {
527 return (empty($string)) ? $string : preg_replace("/\s{2,}/", " ", trim($string));
528 }
529
530 /**
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
533 *
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
537 *
538 * @return string the sanitized string
539 * @access public
540 * @static
541 */
542 static function stripPathChars($string,
543 $search = NULL,
544 $replace = NULL
545 ) {
546 static $_searchChars = NULL;
547 static $_replaceChar = NULL;
548
549 if (empty($string)) {
550 return $string;
551 }
552
553 if ($_searchChars == NULL) {
554 $_searchChars = array(
555 '&', ';', ',', '=', '$',
556 '"', "'", '\\',
557 '<', '>', '(', ')',
558 ' ', "\r", "\r\n", "\n", "\t",
559 );
560 $_replaceChar = '_';
561 }
562
563
564 if ($search == NULL) {
565 $search = $_searchChars;
566 }
567
568 if ($replace == NULL) {
569 $replace = $_replaceChar;
570 }
571
572 return str_replace($search, $replace, $string);
573 }
574
575
576 /**
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
580 *
581 * @param string $string the input string
582 *
583 * @return string the cleaned up string
584 * @public
585 * @static
586 */
587 static function purifyHTML($string) {
588 static $_filter = null;
589 if (!$_filter) {
590 $config = HTMLPurifier_Config::createDefault();
591 $config->set('Core.Encoding', 'UTF-8');
592
593 // Disable the cache entirely
594 $config->set('Cache.DefinitionImpl', null);
595
596 $_filter = new HTMLPurifier($config);
597 }
598
599 return $_filter->purify($string);
600 }
601
602 /**
603 * Truncate $string; if $string exceeds $maxLen, place "..." at the end
604 *
605 * @param string $string
606 * @param int $maxLen
607 */
608 static function ellipsify($string, $maxLen) {
609 $len = strlen($string);
610 if ($len <= $maxLen) {
611 return $string;
612 }
613 else {
614 return substr($string, 0, $maxLen-3) . '...';
615 }
616 }
617
618 /**
619 * Generate a random string
620 *
621 * @param $len
622 * @param $alphabet
623 * @return string
624 */
625 public static function createRandom($len, $alphabet) {
626 $alphabetSize = strlen($alphabet);
627 $result = '';
628 for ($i = 0; $i < $len; $i++) {
629 $result .= $alphabet{rand(1, $alphabetSize) - 1};
630 }
631 return $result;
632 }
633
634}
635