Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
fe482240 | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | ||
f24846d5 SL |
18 | use function xKerman\Restricted\unserialize; |
19 | use xKerman\Restricted\UnserializeFailedException; | |
20 | ||
6a488035 TO |
21 | require_once 'HTML/QuickForm/Rule/Email.php'; |
22 | ||
23 | /** | |
fe482240 | 24 | * This class contains string functions. |
6a488035 TO |
25 | */ |
26 | class CRM_Utils_String { | |
7da04cde | 27 | const COMMA = ",", SEMICOLON = ";", SPACE = " ", TAB = "\t", LINEFEED = "\n", CARRIAGELINE = "\r\n", LINECARRIAGE = "\n\r", CARRIAGERETURN = "\r"; |
6a488035 TO |
28 | |
29 | /** | |
30 | * List of all letters and numbers | |
31 | */ | |
32 | const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; | |
33 | ||
34 | /** | |
fe482240 | 35 | * Convert a display name into a potential variable name. |
6a488035 | 36 | * |
5ab8fe4a | 37 | * @param string $title title of the string |
f4aaa82a EM |
38 | * @param int $maxLength |
39 | * | |
c866eb5f TO |
40 | * @return string |
41 | * An equivalent variable name. | |
6a488035 | 42 | */ |
00be9182 | 43 | public static function titleToVar($title, $maxLength = 31) { |
6a488035 TO |
44 | $variable = self::munge($title, '_', $maxLength); |
45 | ||
46 | if (CRM_Utils_Rule::title($variable, $maxLength)) { | |
47 | return $variable; | |
48 | } | |
49 | ||
50 | // if longer than the maxLength lets just return a substr of the | |
51 | // md5 to prevent errors downstream | |
52 | return substr(md5($title), 0, $maxLength); | |
53 | } | |
54 | ||
55 | /** | |
fe482240 | 56 | * Replace all non alpha numeric characters and spaces with the replacement character. |
6a488035 | 57 | * |
77855840 TO |
58 | * @param string $name |
59 | * The name to be worked on. | |
60 | * @param string $char | |
61 | * The character to use for non-valid chars. | |
62 | * @param int $len | |
63 | * Length of valid variables. | |
6a488035 | 64 | * |
a6c01b45 CW |
65 | * @return string |
66 | * returns the manipulated string | |
6a488035 | 67 | */ |
00be9182 | 68 | public static function munge($name, $char = '_', $len = 63) { |
fe482240 | 69 | // Replace all white space and non-alpha numeric with $char |
6a488035 TO |
70 | // we only use the ascii character set since mysql does not create table names / field names otherwise |
71 | // CRM-11744 | |
72 | $name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name)); | |
755a3caf AA |
73 | |
74 | //If there are no ascii characters present. | |
75 | if ($name == $char) { | |
76 | $name = self::createRandom($len, self::ALPHANUMERIC); | |
77 | } | |
78 | ||
6a488035 TO |
79 | if ($len) { |
80 | // lets keep variable names short | |
81 | return substr($name, 0, $len); | |
82 | } | |
83 | else { | |
84 | return $name; | |
85 | } | |
86 | } | |
87 | ||
dc913073 | 88 | /** |
100fef9d | 89 | * Convert possibly underscore separated words to camel case with special handling for 'UF' |
f3258574 CW |
90 | * e.g membership_payment returns MembershipPayment |
91 | * | |
dc913073 EM |
92 | * @param string $string |
93 | * | |
a6c01b45 | 94 | * @return string |
dc913073 | 95 | */ |
00be9182 | 96 | public static function convertStringToCamel($string) { |
be2fb01f | 97 | $map = [ |
6ba0ed7a TO |
98 | 'acl' => 'Acl', |
99 | 'ACL' => 'Acl', | |
100 | 'im' => 'Im', | |
101 | 'IM' => 'Im', | |
be2fb01f | 102 | ]; |
6ba0ed7a TO |
103 | if (isset($map[$string])) { |
104 | return $map[$string]; | |
105 | } | |
106 | ||
dc913073 EM |
107 | $fragments = explode('_', $string); |
108 | foreach ($fragments as & $fragment) { | |
109 | $fragment = ucfirst($fragment); | |
6d3a1c2b FG |
110 | // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in without underscores) |
111 | if (strpos($fragment, 'Uf') === 0 && strlen($string) > 2) { | |
112 | $fragment = 'UF' . ucfirst(substr($fragment, 2)); | |
113 | } | |
dc913073 | 114 | } |
6d3a1c2b | 115 | // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in underscore-separated) |
dc913073 EM |
116 | if ($fragments[0] === 'Uf') { |
117 | $fragments[0] = 'UF'; | |
118 | } | |
119 | return implode('', $fragments); | |
120 | } | |
121 | ||
6a488035 | 122 | /** |
fe482240 | 123 | * Takes a variable name and munges it randomly into another variable name. |
6a488035 | 124 | * |
77855840 TO |
125 | * @param string $name |
126 | * Initial Variable Name. | |
127 | * @param int $len | |
128 | * Length of valid variables. | |
6a488035 | 129 | * |
a6c01b45 CW |
130 | * @return string |
131 | * Randomized Variable Name | |
6a488035 | 132 | */ |
00be9182 | 133 | public static function rename($name, $len = 4) { |
6a488035 TO |
134 | $rand = substr(uniqid(), 0, $len); |
135 | return substr_replace($name, $rand, -$len, $len); | |
136 | } | |
137 | ||
138 | /** | |
100fef9d | 139 | * Takes a string and returns the last tuple of the string. |
fe482240 EM |
140 | * |
141 | * Useful while converting file names to class names etc | |
6a488035 | 142 | * |
77855840 TO |
143 | * @param string $string |
144 | * The input string. | |
f3258574 CW |
145 | * @param string $char |
146 | * Character used to demarcate the components | |
6a488035 | 147 | * |
a6c01b45 | 148 | * @return string |
f3258574 | 149 | * The last component |
6a488035 | 150 | */ |
00be9182 | 151 | public static function getClassName($string, $char = '_') { |
be2fb01f | 152 | $names = []; |
6a488035 TO |
153 | if (!is_array($string)) { |
154 | $names = explode($char, $string); | |
155 | } | |
156 | if (!empty($names)) { | |
157 | return array_pop($names); | |
158 | } | |
159 | } | |
160 | ||
161 | /** | |
f3258574 | 162 | * Appends a name to a string and separated by delimiter. |
fe482240 EM |
163 | * |
164 | * Does the right thing for an empty string | |
6a488035 | 165 | * |
77855840 TO |
166 | * @param string $str |
167 | * The string to be appended to. | |
168 | * @param string $delim | |
169 | * The delimiter to use. | |
170 | * @param mixed $name | |
171 | * The string (or array of strings) to append. | |
6a488035 | 172 | */ |
00be9182 | 173 | public static function append(&$str, $delim, $name) { |
6a488035 TO |
174 | if (empty($name)) { |
175 | return; | |
176 | } | |
177 | ||
178 | if (is_array($name)) { | |
179 | foreach ($name as $n) { | |
180 | if (empty($n)) { | |
181 | continue; | |
182 | } | |
183 | if (empty($str)) { | |
184 | $str = $n; | |
185 | } | |
186 | else { | |
187 | $str .= $delim . $n; | |
188 | } | |
189 | } | |
190 | } | |
191 | else { | |
192 | if (empty($str)) { | |
193 | $str = $name; | |
194 | } | |
195 | else { | |
196 | $str .= $delim . $name; | |
197 | } | |
198 | } | |
199 | } | |
200 | ||
201 | /** | |
fe482240 | 202 | * Determine if the string is composed only of ascii characters. |
6a488035 | 203 | * |
77855840 TO |
204 | * @param string $str |
205 | * Input string. | |
206 | * @param bool $utf8 | |
207 | * Attempt utf8 match on failure (default yes). | |
6a488035 | 208 | * |
608e6658 | 209 | * @return bool |
a6c01b45 | 210 | * true if string is ascii |
6a488035 | 211 | */ |
00be9182 | 212 | public static function isAscii($str, $utf8 = TRUE) { |
6a488035 TO |
213 | if (!function_exists('mb_detect_encoding')) { |
214 | // eliminate all white space from the string | |
215 | $str = preg_replace('/\s+/', '', $str); | |
216 | // FIXME: This is a pretty brutal hack to make utf8 and 8859-1 work. | |
217 | ||
50bfb460 | 218 | // match low- or high-ascii characters |
6a488035 TO |
219 | if (preg_match('/[\x00-\x20]|[\x7F-\xFF]/', $str)) { |
220 | // || // low ascii characters | |
221 | // high ascii characters | |
222 | // preg_match( '/[\x7F-\xFF]/', $str ) ) { | |
223 | if ($utf8) { | |
50bfb460 | 224 | // if we did match, try for utf-8, or iso8859-1 |
6a488035 TO |
225 | |
226 | return self::isUtf8($str); | |
227 | } | |
228 | else { | |
229 | return FALSE; | |
230 | } | |
231 | } | |
232 | return TRUE; | |
233 | } | |
234 | else { | |
be2fb01f | 235 | $order = ['ASCII']; |
6a488035 TO |
236 | if ($utf8) { |
237 | $order[] = 'UTF-8'; | |
238 | } | |
239 | $enc = mb_detect_encoding($str, $order, TRUE); | |
240 | return ($enc == 'ASCII' || $enc == 'UTF-8'); | |
241 | } | |
242 | } | |
243 | ||
244 | /** | |
fe482240 | 245 | * Determine the string replacements for redaction. |
6a488035 TO |
246 | * on the basis of the regular expressions |
247 | * | |
77855840 TO |
248 | * @param string $str |
249 | * Input string. | |
250 | * @param array $regexRules | |
251 | * Regular expression to be matched w/ replacements. | |
6a488035 | 252 | * |
a6c01b45 CW |
253 | * @return array |
254 | * array of strings w/ corresponding redacted outputs | |
6a488035 | 255 | */ |
00be9182 | 256 | public static function regex($str, $regexRules) { |
50bfb460 | 257 | // redact the regular expressions |
6a488035 | 258 | if (!empty($regexRules) && isset($str)) { |
be2fb01f | 259 | static $matches, $totalMatches, $match = []; |
6a488035 TO |
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]; | |
265 | } | |
266 | else { | |
267 | $totalMatches = array_merge($totalMatches, $matches[0]); | |
268 | } | |
269 | $match = array_flip($totalMatches); | |
270 | } | |
271 | } | |
272 | } | |
273 | ||
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); | |
279 | break; | |
280 | } | |
281 | } | |
282 | } | |
283 | return $match; | |
284 | } | |
db62d3a5 | 285 | return []; |
6a488035 TO |
286 | } |
287 | ||
5bc392e6 EM |
288 | /** |
289 | * @param $str | |
290 | * @param $stringRules | |
291 | * | |
292 | * @return mixed | |
293 | */ | |
00be9182 | 294 | public static function redaction($str, $stringRules) { |
50bfb460 | 295 | // redact the strings |
6a488035 TO |
296 | if (!empty($stringRules)) { |
297 | foreach ($stringRules as $match => $replace) { | |
298 | $str = str_ireplace($match, $replace, $str); | |
299 | } | |
300 | } | |
301 | ||
50bfb460 | 302 | // return the redacted output |
6a488035 TO |
303 | return $str; |
304 | } | |
305 | ||
306 | /** | |
307 | * Determine if a string is composed only of utf8 characters | |
308 | * | |
77855840 TO |
309 | * @param string $str |
310 | * Input string. | |
6a488035 | 311 | * |
608e6658 | 312 | * @return bool |
6a488035 | 313 | */ |
00be9182 | 314 | public static function isUtf8($str) { |
6a488035 TO |
315 | if (!function_exists(mb_detect_encoding)) { |
316 | // eliminate all white space from the string | |
317 | $str = preg_replace('/\s+/', '', $str); | |
318 | ||
50bfb460 SB |
319 | // pattern stolen from the php.net function documentation for |
320 | // utf8decode(); | |
321 | // comment by JF Sebastian, 30-Mar-2005 | |
6a488035 TO |
322 | 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); |
323 | // || | |
324 | // iconv('ISO-8859-1', 'UTF-8', $str); | |
325 | } | |
326 | else { | |
be2fb01f | 327 | $enc = mb_detect_encoding($str, ['UTF-8'], TRUE); |
6a488035 TO |
328 | return ($enc !== FALSE); |
329 | } | |
330 | } | |
331 | ||
332 | /** | |
50bfb460 | 333 | * Determine if two hrefs are equivalent (fuzzy match) |
6a488035 | 334 | * |
77855840 TO |
335 | * @param string $url1 |
336 | * The first url to be matched. | |
337 | * @param string $url2 | |
338 | * The second url to be matched against. | |
6a488035 | 339 | * |
608e6658 | 340 | * @return bool |
a6c01b45 | 341 | * true if the urls match, else false |
6a488035 | 342 | */ |
00be9182 | 343 | public static function match($url1, $url2) { |
6a488035 TO |
344 | $url1 = strtolower($url1); |
345 | $url2 = strtolower($url2); | |
346 | ||
347 | $url1Str = parse_url($url1); | |
348 | $url2Str = parse_url($url2); | |
349 | ||
350 | if ($url1Str['path'] == $url2Str['path'] && | |
351 | self::extractURLVarValue(CRM_Utils_Array::value('query', $url1Str)) == self::extractURLVarValue(CRM_Utils_Array::value('query', $url2Str)) | |
352 | ) { | |
353 | return TRUE; | |
354 | } | |
355 | return FALSE; | |
356 | } | |
357 | ||
358 | /** | |
fe482240 | 359 | * Extract the civicrm path from the url. |
6a488035 | 360 | * |
f3258574 CW |
361 | * @param string $query |
362 | * A url string. | |
6a488035 | 363 | * |
f3258574 CW |
364 | * @return string|null |
365 | * civicrm url (eg: civicrm/contact/search) | |
6a488035 | 366 | */ |
00be9182 | 367 | public static function extractURLVarValue($query) { |
6a488035 TO |
368 | $config = CRM_Core_Config::singleton(); |
369 | $urlVar = $config->userFrameworkURLVar; | |
370 | ||
371 | $params = explode('&', $query); | |
372 | foreach ($params as $p) { | |
373 | if (strpos($p, '=')) { | |
374 | list($k, $v) = explode('=', $p); | |
375 | if ($k == $urlVar) { | |
376 | return $v; | |
377 | } | |
378 | } | |
379 | } | |
380 | return NULL; | |
381 | } | |
382 | ||
383 | /** | |
100fef9d | 384 | * Translate a true/false/yes/no string to a 0 or 1 value |
6a488035 | 385 | * |
77855840 TO |
386 | * @param string $str |
387 | * The string to be translated. | |
6a488035 | 388 | * |
608e6658 | 389 | * @return bool |
6a488035 | 390 | */ |
00be9182 | 391 | public static function strtobool($str) { |
6a488035 TO |
392 | if (!is_scalar($str)) { |
393 | return FALSE; | |
394 | } | |
395 | ||
396 | if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) { | |
397 | return TRUE; | |
398 | } | |
399 | return FALSE; | |
400 | } | |
401 | ||
402 | /** | |
100fef9d | 403 | * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false |
6a488035 | 404 | * |
77855840 TO |
405 | * @param string $str |
406 | * The string to be translated. | |
6a488035 | 407 | * |
608e6658 | 408 | * @return bool |
6a488035 | 409 | */ |
00be9182 | 410 | public static function strtoboolstr($str) { |
6a488035 TO |
411 | if (!is_scalar($str)) { |
412 | return FALSE; | |
413 | } | |
414 | ||
415 | if (preg_match('/^(y(es)?|t(rue)?|1)$/i', $str)) { | |
416 | return '1'; | |
417 | } | |
418 | elseif (preg_match('/^(n(o)?|f(alse)?|0)$/i', $str)) { | |
419 | return '0'; | |
420 | } | |
421 | else { | |
422 | return FALSE; | |
423 | } | |
424 | } | |
425 | ||
426 | /** | |
427 | * Convert a HTML string into a text one using html2text | |
428 | * | |
77855840 TO |
429 | * @param string $html |
430 | * The string to be converted. | |
6a488035 | 431 | * |
a6c01b45 CW |
432 | * @return string |
433 | * the converted string | |
6a488035 | 434 | */ |
00be9182 | 435 | public static function htmlToText($html) { |
7a999eae | 436 | require_once 'packages/html2text/rcube_html2text.php'; |
bfef4c7e KW |
437 | $token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html); |
438 | $converter = new rcube_html2text($token_html); | |
439 | $token_text = $converter->get_text(); | |
440 | $text = preg_replace('!token\:\{([a-z_.]+)\}!i', '{$1}', $token_text); | |
441 | return $text; | |
6a488035 TO |
442 | } |
443 | ||
5bc392e6 EM |
444 | /** |
445 | * @param $string | |
c490a46a | 446 | * @param array $params |
5bc392e6 | 447 | */ |
00be9182 | 448 | public static function extractName($string, &$params) { |
6a488035 TO |
449 | $name = trim($string); |
450 | if (empty($name)) { | |
451 | return; | |
452 | } | |
453 | ||
454 | // strip out quotes | |
455 | $name = str_replace('"', '', $name); | |
456 | $name = str_replace('\'', '', $name); | |
457 | ||
458 | // check for comma in name | |
459 | if (strpos($name, ',') !== FALSE) { | |
460 | ||
461 | // name has a comma - assume lname, fname [mname] | |
462 | $names = explode(',', $name); | |
463 | if (count($names) > 1) { | |
464 | $params['last_name'] = trim($names[0]); | |
465 | ||
466 | // check for space delim | |
467 | $fnames = explode(' ', trim($names[1])); | |
468 | if (count($fnames) > 1) { | |
469 | $params['first_name'] = trim($fnames[0]); | |
470 | $params['middle_name'] = trim($fnames[1]); | |
471 | } | |
472 | else { | |
473 | $params['first_name'] = trim($fnames[0]); | |
474 | } | |
475 | } | |
476 | else { | |
477 | $params['first_name'] = trim($names[0]); | |
478 | } | |
479 | } | |
480 | else { | |
481 | // name has no comma - assume fname [mname] fname | |
482 | $names = explode(' ', $name); | |
483 | if (count($names) == 1) { | |
484 | $params['first_name'] = $names[0]; | |
485 | } | |
486 | elseif (count($names) == 2) { | |
487 | $params['first_name'] = $names[0]; | |
488 | $params['last_name'] = $names[1]; | |
489 | } | |
490 | else { | |
491 | $params['first_name'] = $names[0]; | |
492 | $params['middle_name'] = $names[1]; | |
493 | $params['last_name'] = $names[2]; | |
494 | } | |
495 | } | |
496 | } | |
497 | ||
5bc392e6 EM |
498 | /** |
499 | * @param $string | |
500 | * | |
501 | * @return array | |
502 | */ | |
00be9182 | 503 | public static function &makeArray($string) { |
6a488035 TO |
504 | $string = trim($string); |
505 | ||
506 | $values = explode("\n", $string); | |
be2fb01f | 507 | $result = []; |
6a488035 TO |
508 | foreach ($values as $value) { |
509 | list($n, $v) = CRM_Utils_System::explode('=', $value, 2); | |
510 | if (!empty($v)) { | |
511 | $result[trim($n)] = trim($v); | |
512 | } | |
513 | } | |
514 | return $result; | |
515 | } | |
516 | ||
6a488035 TO |
517 | /** |
518 | * Given an ezComponents-parsed representation of | |
519 | * a text with alternatives return only the first one | |
520 | * | |
77855840 TO |
521 | * @param string $full |
522 | * All alternatives as a long string (or some other text). | |
6a488035 | 523 | * |
a6c01b45 CW |
524 | * @return string |
525 | * only the first alternative found (or the text without alternatives) | |
6a488035 | 526 | */ |
00be9182 | 527 | public static function stripAlternatives($full) { |
be2fb01f | 528 | $matches = []; |
6a488035 TO |
529 | preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches); |
530 | ||
531 | if (isset($matches[1]) && | |
532 | trim(strip_tags($matches[1])) != '' | |
533 | ) { | |
534 | return $matches[1]; | |
535 | } | |
536 | else { | |
537 | return $full; | |
538 | } | |
539 | } | |
540 | ||
541 | /** | |
100fef9d | 542 | * Strip leading, trailing, double spaces from string |
6a488035 TO |
543 | * used for postal/greeting/addressee |
544 | * | |
77855840 TO |
545 | * @param string $string |
546 | * Input string to be cleaned. | |
6a488035 | 547 | * |
a6c01b45 CW |
548 | * @return string |
549 | * the cleaned string | |
6a488035 | 550 | */ |
00be9182 | 551 | public static function stripSpaces($string) { |
6a488035 TO |
552 | return (empty($string)) ? $string : preg_replace("/\s{2,}/", " ", trim($string)); |
553 | } | |
554 | ||
555 | /** | |
dc195289 | 556 | * clean the URL 'path' variable that we use |
6a488035 TO |
557 | * to construct CiviCRM urls by removing characters from the path variable |
558 | * | |
77855840 TO |
559 | * @param string $string |
560 | * The input string to be sanitized. | |
561 | * @param array $search | |
562 | * The characters to be sanitized. | |
563 | * @param string $replace | |
564 | * The character to replace it with. | |
6a488035 | 565 | * |
a6c01b45 CW |
566 | * @return string |
567 | * the sanitized string | |
6a488035 | 568 | */ |
608e6658 | 569 | public static function stripPathChars( |
a3e55d9c | 570 | $string, |
6a488035 TO |
571 | $search = NULL, |
572 | $replace = NULL | |
573 | ) { | |
574 | static $_searchChars = NULL; | |
575 | static $_replaceChar = NULL; | |
576 | ||
577 | if (empty($string)) { | |
578 | return $string; | |
579 | } | |
580 | ||
581 | if ($_searchChars == NULL) { | |
be2fb01f | 582 | $_searchChars = [ |
353ffa53 TO |
583 | '&', |
584 | ';', | |
585 | ',', | |
586 | '=', | |
587 | '$', | |
588 | '"', | |
589 | "'", | |
590 | '\\', | |
591 | '<', | |
592 | '>', | |
593 | '(', | |
594 | ')', | |
595 | ' ', | |
596 | "\r", | |
597 | "\r\n", | |
598 | "\n", | |
599 | "\t", | |
be2fb01f | 600 | ]; |
6a488035 TO |
601 | $_replaceChar = '_'; |
602 | } | |
603 | ||
6a488035 TO |
604 | if ($search == NULL) { |
605 | $search = $_searchChars; | |
606 | } | |
607 | ||
608 | if ($replace == NULL) { | |
609 | $replace = $_replaceChar; | |
610 | } | |
611 | ||
612 | return str_replace($search, $replace, $string); | |
613 | } | |
614 | ||
6a488035 TO |
615 | /** |
616 | * Use HTMLPurifier to clean up a text string and remove any potential | |
617 | * xss attacks. This is primarily used in public facing pages which | |
618 | * accept html as the input string | |
619 | * | |
77855840 TO |
620 | * @param string $string |
621 | * The input string. | |
6a488035 | 622 | * |
a6c01b45 CW |
623 | * @return string |
624 | * the cleaned up string | |
6a488035 | 625 | */ |
00be9182 | 626 | public static function purifyHTML($string) { |
e7292422 | 627 | static $_filter = NULL; |
6a488035 TO |
628 | if (!$_filter) { |
629 | $config = HTMLPurifier_Config::createDefault(); | |
630 | $config->set('Core.Encoding', 'UTF-8'); | |
7652022e | 631 | $config->set('Attr.AllowedFrameTargets', ['_blank', '_self', '_parent', '_top']); |
6a488035 TO |
632 | |
633 | // Disable the cache entirely | |
e7292422 | 634 | $config->set('Cache.DefinitionImpl', NULL); |
6a488035 TO |
635 | |
636 | $_filter = new HTMLPurifier($config); | |
637 | } | |
638 | ||
639 | return $_filter->purify($string); | |
640 | } | |
641 | ||
642 | /** | |
643 | * Truncate $string; if $string exceeds $maxLen, place "..." at the end | |
644 | * | |
645 | * @param string $string | |
646 | * @param int $maxLen | |
f4aaa82a EM |
647 | * |
648 | * @return string | |
6a488035 | 649 | */ |
00be9182 | 650 | public static function ellipsify($string, $maxLen) { |
47f49a22 | 651 | if (mb_strlen($string, 'UTF-8') <= $maxLen) { |
6a488035 TO |
652 | return $string; |
653 | } | |
47f49a22 | 654 | return mb_substr($string, 0, $maxLen - 3, 'UTF-8') . '...'; |
6a488035 TO |
655 | } |
656 | ||
657 | /** | |
fe482240 | 658 | * Generate a random string. |
6a488035 TO |
659 | * |
660 | * @param $len | |
661 | * @param $alphabet | |
662 | * @return string | |
663 | */ | |
664 | public static function createRandom($len, $alphabet) { | |
665 | $alphabetSize = strlen($alphabet); | |
666 | $result = ''; | |
667 | for ($i = 0; $i < $len; $i++) { | |
668 | $result .= $alphabet{rand(1, $alphabetSize) - 1}; | |
669 | } | |
670 | return $result; | |
671 | } | |
672 | ||
fc7a0aee TO |
673 | /** |
674 | * Examples: | |
675 | * "admin foo" => array(NULL,"admin foo") | |
676 | * "cms:admin foo" => array("cms", "admin foo") | |
677 | * | |
f4aaa82a | 678 | * @param $delim |
77855840 TO |
679 | * @param string $string |
680 | * E.g. "view all contacts". Syntax: "[prefix:]name". | |
f4aaa82a EM |
681 | * @param null $defaultPrefix |
682 | * | |
a6c01b45 CW |
683 | * @return array |
684 | * (0 => string|NULL $prefix, 1 => string $value) | |
fc7a0aee TO |
685 | */ |
686 | public static function parsePrefix($delim, $string, $defaultPrefix = NULL) { | |
687 | $pos = strpos($string, $delim); | |
688 | if ($pos === FALSE) { | |
be2fb01f | 689 | return [$defaultPrefix, $string]; |
fc7a0aee TO |
690 | } |
691 | else { | |
be2fb01f | 692 | return [substr($string, 0, $pos), substr($string, 1 + $pos)]; |
fc7a0aee TO |
693 | } |
694 | } | |
695 | ||
87b48098 | 696 | /** |
100fef9d | 697 | * This function will mask part of the the user portion of an Email address (everything before the @) |
87b48098 | 698 | * |
77855840 TO |
699 | * @param string $email |
700 | * The email address to be masked. | |
701 | * @param string $maskChar | |
702 | * The character used for masking. | |
703 | * @param int $percent | |
704 | * The percentage of the user portion to be masked. | |
87b48098 | 705 | * |
a6c01b45 CW |
706 | * @return string |
707 | * returns the masked Email address | |
87b48098 | 708 | */ |
e7292422 | 709 | public static function maskEmail($email, $maskChar = '*', $percent = 50) { |
87b48098 K |
710 | list($user, $domain) = preg_split("/@/", $email); |
711 | $len = strlen($user); | |
e7292422 | 712 | $maskCount = floor($len * $percent / 100); |
87b48098 K |
713 | $offset = floor(($len - $maskCount) / 2); |
714 | ||
715 | $masked = substr($user, 0, $offset) | |
353ffa53 TO |
716 | . str_repeat($maskChar, $maskCount) |
717 | . substr($user, $maskCount + $offset); | |
87b48098 | 718 | |
92fcb95f | 719 | return ($masked . '@' . $domain); |
87b48098 K |
720 | } |
721 | ||
722 | /** | |
fe482240 | 723 | * This function compares two strings. |
87b48098 | 724 | * |
77855840 TO |
725 | * @param string $strOne |
726 | * String one. | |
727 | * @param string $strTwo | |
728 | * String two. | |
729 | * @param bool $case | |
730 | * Boolean indicating whether you want the comparison to be case sensitive or not. | |
87b48098 | 731 | * |
608e6658 | 732 | * @return bool |
a6c01b45 | 733 | * TRUE (string are identical); FALSE (strings are not identical) |
87b48098 K |
734 | */ |
735 | public static function compareStr($strOne, $strTwo, $case) { | |
736 | if ($case == TRUE) { | |
dca9da6e | 737 | // Convert to lowercase and trim white spaces |
87b48098 K |
738 | if (strtolower(trim($strOne)) == strtolower(trim($strTwo))) { |
739 | // yes - they are identical | |
740 | return TRUE; | |
741 | } | |
742 | else { | |
743 | // not identical | |
744 | return FALSE; | |
745 | } | |
746 | } | |
747 | if ($case == FALSE) { | |
dca9da6e | 748 | // Trim white spaces |
87b48098 K |
749 | if (trim($strOne) == trim($strTwo)) { |
750 | // yes - they are identical | |
751 | return TRUE; | |
752 | } | |
753 | else { | |
754 | // not identical | |
755 | return FALSE; | |
756 | } | |
757 | } | |
758 | } | |
fc7a0aee | 759 | |
77d45291 TO |
760 | /** |
761 | * Many parts of the codebase have a convention of internally passing around | |
762 | * HTML-encoded URLs. This effectively means that "&" is replaced by "&" | |
763 | * (because most other odd characters are %-escaped in URLs; and %-escaped | |
764 | * strings don't need any extra escaping in HTML). | |
765 | * | |
608e6658 | 766 | * @param string $htmlUrl |
77855840 | 767 | * URL with HTML entities. |
a6c01b45 CW |
768 | * @return string |
769 | * URL without HTML entities | |
77d45291 TO |
770 | */ |
771 | public static function unstupifyUrl($htmlUrl) { | |
772 | return str_replace('&', '&', $htmlUrl); | |
773 | } | |
96025800 | 774 | |
6c094ca6 SM |
775 | /** |
776 | * When a user supplies a URL (e.g. to an image), we'd like to: | |
777 | * - Remove the protocol and domain name if the URL points to the current | |
778 | * site. | |
779 | * - Keep the domain name for remote URLs. | |
780 | * - Optionally, force remote URLs to use https instead of http (which is | |
781 | * useful for images) | |
782 | * | |
783 | * @param string $url | |
784 | * The URL to simplify. Examples: | |
785 | * "https://example.org/sites/default/files/coffee-mug.jpg" | |
786 | * "sites/default/files/coffee-mug.jpg" | |
787 | * "http://i.stack.imgur.com/9jb2ial01b.png" | |
788 | * @param bool $forceHttps = FALSE | |
789 | * If TRUE, ensure that remote URLs use https. If a URL with | |
790 | * http is supplied, then we'll change it to https. | |
791 | * This is useful for situations like showing a premium product on a | |
792 | * contribution, because (as reported in CRM-14283) if the user gets a | |
793 | * browser warning like "page contains insecure elements" on a contribution | |
794 | * page, that's a very bad thing. Thus, even if changing http to https | |
795 | * breaks the image, that's better than leaving http content in a | |
796 | * contribution page. | |
797 | * | |
798 | * @return string | |
799 | * The simplified URL. Examples: | |
800 | * "/sites/default/files/coffee-mug.jpg" | |
801 | * "https://i.stack.imgur.com/9jb2ial01b.png" | |
802 | */ | |
803 | public static function simplifyURL($url, $forceHttps = FALSE) { | |
804 | $config = CRM_Core_Config::singleton(); | |
805 | $siteURLParts = self::simpleParseUrl($config->userFrameworkBaseURL); | |
806 | $urlParts = self::simpleParseUrl($url); | |
807 | ||
808 | // If the image is locally hosted, then only give the path to the image | |
809 | $urlIsLocal | |
810 | = ($urlParts['host+port'] == '') | |
811 | | ($urlParts['host+port'] == $siteURLParts['host+port']); | |
812 | if ($urlIsLocal) { | |
813 | // and make sure it begins with one forward slash | |
814 | return preg_replace('_^/*(?=.)_', '/', $urlParts['path+query']); | |
815 | } | |
816 | ||
817 | // If the URL is external, then keep the full URL as supplied | |
818 | else { | |
819 | return $forceHttps ? preg_replace('_^http://_', 'https://', $url) : $url; | |
820 | } | |
821 | } | |
822 | ||
823 | /** | |
824 | * A simplified version of PHP's parse_url() function. | |
825 | * | |
826 | * @param string $url | |
827 | * e.g. "https://example.com:8000/foo/bar/?id=1#fragment" | |
828 | * | |
829 | * @return array | |
830 | * Will always contain keys 'host+port' and 'path+query', even if they're | |
831 | * empty strings. Example: | |
832 | * [ | |
833 | * 'host+port' => "example.com:8000", | |
834 | * 'path+query' => "/foo/bar/?id=1", | |
835 | * ] | |
836 | */ | |
837 | public static function simpleParseUrl($url) { | |
838 | $parts = parse_url($url); | |
839 | $host = isset($parts['host']) ? $parts['host'] : ''; | |
840 | $port = isset($parts['port']) ? ':' . $parts['port'] : ''; | |
841 | $path = isset($parts['path']) ? $parts['path'] : ''; | |
842 | $query = isset($parts['query']) ? '?' . $parts['query'] : ''; | |
be2fb01f | 843 | return [ |
6c094ca6 SM |
844 | 'host+port' => "$host$port", |
845 | 'path+query' => "$path$query", | |
be2fb01f | 846 | ]; |
6c094ca6 SM |
847 | } |
848 | ||
79a18c21 | 849 | /** |
fe482240 | 850 | * Formats a string of attributes for insertion in an html tag. |
79a18c21 CW |
851 | * |
852 | * @param array $attributes | |
853 | * | |
854 | * @return string | |
855 | */ | |
856 | public static function htmlAttributes($attributes) { | |
857 | $output = ''; | |
858 | foreach ($attributes as $name => $vals) { | |
859 | $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"'; | |
860 | } | |
861 | return ltrim($output); | |
862 | } | |
863 | ||
83d511e6 TO |
864 | /** |
865 | * Determine if $string starts with $fragment. | |
866 | * | |
867 | * @param string $string | |
868 | * The long string. | |
869 | * @param string $fragment | |
870 | * The fragment to look for. | |
871 | * @return bool | |
872 | */ | |
873 | public static function startsWith($string, $fragment) { | |
874 | if ($fragment === '') { | |
875 | return TRUE; | |
876 | } | |
877 | $len = strlen($fragment); | |
878 | return substr($string, 0, $len) === $fragment; | |
879 | } | |
880 | ||
881 | /** | |
882 | * Determine if $string ends with $fragment. | |
883 | * | |
884 | * @param string $string | |
885 | * The long string. | |
886 | * @param string $fragment | |
887 | * The fragment to look for. | |
888 | * @return bool | |
889 | */ | |
890 | public static function endsWith($string, $fragment) { | |
891 | if ($fragment === '') { | |
892 | return TRUE; | |
893 | } | |
894 | $len = strlen($fragment); | |
895 | return substr($string, -1 * $len) === $fragment; | |
896 | } | |
897 | ||
898 | /** | |
899 | * @param string|array $patterns | |
900 | * @param array $allStrings | |
901 | * @param bool $allowNew | |
902 | * Whether to return new, unrecognized names. | |
903 | * @return array | |
904 | */ | |
905 | public static function filterByWildcards($patterns, $allStrings, $allowNew = FALSE) { | |
906 | $patterns = (array) $patterns; | |
be2fb01f | 907 | $result = []; |
83d511e6 TO |
908 | foreach ($patterns as $pattern) { |
909 | if (!\CRM_Utils_String::endsWith($pattern, '*')) { | |
910 | if ($allowNew || in_array($pattern, $allStrings)) { | |
911 | $result[] = $pattern; | |
912 | } | |
913 | } | |
914 | else { | |
915 | $prefix = rtrim($pattern, '*'); | |
916 | foreach ($allStrings as $key) { | |
917 | if (\CRM_Utils_String::startsWith($key, $prefix)) { | |
918 | $result[] = $key; | |
919 | } | |
920 | } | |
921 | } | |
922 | } | |
923 | return array_values(array_unique($result)); | |
924 | } | |
925 | ||
f24846d5 | 926 | /** |
dc7c2d3e SL |
927 | * Safely unserialize a string of scalar or array values (but not objects!) |
928 | * | |
929 | * Use `xkerman/restricted-unserialize` to unserialize strings using PHP's | |
930 | * serialization format. `restricted-unserialize` works like PHP's built-in | |
931 | * `unserialize` function except that it does not deserialize object instances, | |
932 | * making it immune to PHP Object Injection {@see https://www.owasp.org/index.php/PHP_Object_Injection} | |
933 | * vulnerabilities. | |
934 | * | |
935 | * Note: When dealing with user inputs, it is generally recommended to use | |
936 | * safe, standard data interchange formats such as JSON rather than PHP's | |
937 | * serialization format when dealing with user input. | |
938 | * | |
f24846d5 SL |
939 | * @param string|NULL $string |
940 | * | |
941 | * @return mixed | |
f24846d5 SL |
942 | */ |
943 | public static function unserialize($string) { | |
944 | if (!is_string($string)) { | |
945 | return FALSE; | |
946 | } | |
947 | try { | |
948 | return unserialize($string); | |
949 | } | |
950 | catch (UnserializeFailedException $e) { | |
079546f5 | 951 | return FALSE; |
f24846d5 | 952 | } |
dc7c2d3e | 953 | } |
f24846d5 | 954 | |
6a488035 | 955 | } |