Merge pull request #5090 from colemanw/explorer
[civicrm-core.git] / CRM / Utils / Rule.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 * Class CRM_Utils_Rule
40 */
41 class CRM_Utils_Rule {
42
43 /**
44 * @param $str
45 * @param int $maxLength
46 *
47 * @return bool
48 */
49 public static function title($str, $maxLength = 127) {
50
51 // check length etc
52 if (empty($str) || strlen($str) > $maxLength) {
53 return FALSE;
54 }
55
56 // Make sure it include valid characters, alpha numeric and underscores
57 if (!preg_match('/^\w[\w\s\'\&\,\$\#\-\.\"\?\!]+$/i', $str)) {
58 return FALSE;
59 }
60
61 return TRUE;
62 }
63
64 /**
65 * @param $str
66 *
67 * @return bool
68 */
69 public static function longTitle($str) {
70 return self::title($str, 255);
71 }
72
73 /**
74 * @param $str
75 *
76 * @return bool
77 */
78 public static function variable($str) {
79 // check length etc
80 if (empty($str) || strlen($str) > 31) {
81 return FALSE;
82 }
83
84 // make sure it include valid characters, alpha numeric and underscores
85 if (!preg_match('/^[\w]+$/i', $str)) {
86 return FALSE;
87 }
88
89 return TRUE;
90 }
91
92 /**
93 * @param $str
94 *
95 * @return bool
96 */
97 public static function qfVariable($str) {
98 // check length etc
99 //if ( empty( $str ) || strlen( $str ) > 31 ) {
100 if (strlen(trim($str)) == 0 || strlen($str) > 31) {
101 return FALSE;
102 }
103
104 // make sure it include valid characters, alpha numeric and underscores
105 // added (. and ,) option (CRM-1336)
106 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
107 return FALSE;
108 }
109
110 return TRUE;
111 }
112
113 /**
114 * @param $phone
115 *
116 * @return bool
117 */
118 public static function phone($phone) {
119 // check length etc
120 if (empty($phone) || strlen($phone) > 16) {
121 return FALSE;
122 }
123
124 // make sure it include valid characters, (, \s and numeric
125 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
126 return TRUE;
127 }
128 return FALSE;
129 }
130
131 /**
132 * @param $query
133 *
134 * @return bool
135 */
136 public static function query($query) {
137 // check length etc
138 if (empty($query) || strlen($query) < 3 || strlen($query) > 127) {
139 return FALSE;
140 }
141
142 // make sure it include valid characters, alpha numeric and underscores
143 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
144 return FALSE;
145 }
146
147 return TRUE;
148 }
149
150 /**
151 * @param $url
152 *
153 * @return bool
154 */
155 public static function url($url) {
156 if (preg_match('/^\//', $url)) {
157 // allow relative URL's (CRM-15598)
158 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
159 }
160 return (bool) filter_var($url, FILTER_VALIDATE_URL);
161 }
162
163 /**
164 * @param $string
165 *
166 * @return bool
167 */
168 public static function wikiURL($string) {
169 $items = explode(' ', trim($string), 2);
170 return self::url($items[0]);
171 }
172
173 /**
174 * @param $domain
175 *
176 * @return bool
177 */
178 public static function domain($domain) {
179 // not perfect, but better than the previous one; see CRM-1502
180 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
181 return FALSE;
182 }
183 return TRUE;
184 }
185
186 /**
187 * @param $value
188 * @param null $default
189 *
190 * @return null
191 */
192 public static function date($value, $default = NULL) {
193 if (is_string($value) &&
194 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
195 ) {
196 return $value;
197 }
198 return $default;
199 }
200
201 /**
202 * @param $value
203 * @param null $default
204 *
205 * @return null|string
206 */
207 public static function dateTime($value, $default = NULL) {
208 $result = $default;
209 if (is_string($value) &&
210 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
211 ) {
212 $result = $value;
213 }
214
215 return $result;
216 }
217
218 /**
219 * Check the validity of the date (in qf format)
220 * note that only a year is valid, or a mon-year is
221 * also valid in addition to day-mon-year. The date
222 * specified has to be beyond today. (i.e today or later)
223 *
224 * @param array $date
225 * @param bool $monthRequired
226 * Check whether month is mandatory.
227 *
228 * @return bool
229 * true if valid date
230 */
231 public static function currentDate($date, $monthRequired = TRUE) {
232 $config = CRM_Core_Config::singleton();
233
234 $d = CRM_Utils_Array::value('d', $date);
235 $m = CRM_Utils_Array::value('M', $date);
236 $y = CRM_Utils_Array::value('Y', $date);
237
238 if (!$d && !$m && !$y) {
239 return TRUE;
240 }
241
242 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
243 if (!$m && !empty($date['m'])) {
244 $m = CRM_Utils_Array::value('m', $date);
245 }
246
247 $day = $mon = 1;
248 $year = 0;
249 if ($d) {
250 $day = $d;
251 }
252 if ($m) {
253 $mon = $m;
254 }
255 if ($y) {
256 $year = $y;
257 }
258
259 // if we have day we need mon, and if we have mon we need year
260 if (($d && !$m) ||
261 ($d && !$y) ||
262 ($m && !$y)
263 ) {
264 return FALSE;
265 }
266
267 $result = FALSE;
268 if (!empty($day) || !empty($mon) || !empty($year)) {
269 $result = checkdate($mon, $day, $year);
270 }
271
272 if (!$result) {
273 return FALSE;
274 }
275
276 // ensure we have month if required
277 if ($monthRequired && !$m) {
278 return FALSE;
279 }
280
281 // now make sure this date is greater that today
282 $currentDate = getdate();
283 if ($year > $currentDate['year']) {
284 return TRUE;
285 }
286 elseif ($year < $currentDate['year']) {
287 return FALSE;
288 }
289
290 if ($m) {
291 if ($mon > $currentDate['mon']) {
292 return TRUE;
293 }
294 elseif ($mon < $currentDate['mon']) {
295 return FALSE;
296 }
297 }
298
299 if ($d) {
300 if ($day > $currentDate['mday']) {
301 return TRUE;
302 }
303 elseif ($day < $currentDate['mday']) {
304 return FALSE;
305 }
306 }
307
308 return TRUE;
309 }
310
311 /**
312 * Check the validity of a date or datetime (timestamp)
313 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
314 *
315 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
316 *
317 * @param string $date
318 *
319 * @return bool
320 * true if valid date
321 */
322 public static function mysqlDate($date) {
323 // allow date to be null
324 if ($date == NULL) {
325 return TRUE;
326 }
327
328 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
329 return TRUE;
330 }
331
332 return FALSE;
333 }
334
335 /**
336 * @param $value
337 *
338 * @return bool
339 */
340 public static function integer($value) {
341 if (is_int($value)) {
342 return TRUE;
343 }
344
345 // CRM-13460
346 // ensure number passed is always a string numeral
347 if (!is_numeric($value)) {
348 return FALSE;
349 }
350
351 // note that is_int matches only integer type
352 // and not strings which are only integers
353 // hence we do this here
354 if (preg_match('/^\d+$/', $value)) {
355 return TRUE;
356 }
357
358 if ($value < 0) {
359 $negValue = -1 * $value;
360 if (is_int($negValue)) {
361 return TRUE;
362 }
363 }
364
365 return FALSE;
366 }
367
368 /**
369 * @param $value
370 *
371 * @return bool
372 */
373 public static function positiveInteger($value) {
374 if (is_int($value)) {
375 return ($value < 0) ? FALSE : TRUE;
376 }
377
378 // CRM-13460
379 // ensure number passed is always a string numeral
380 if (!is_numeric($value)) {
381 return FALSE;
382 }
383
384 if (preg_match('/^\d+$/', $value)) {
385 return TRUE;
386 }
387
388 return FALSE;
389 }
390
391 /**
392 * @param $value
393 *
394 * @return bool
395 */
396 public static function numeric($value) {
397 // lets use a php gatekeeper to ensure this is numeric
398 if (!is_numeric($value)) {
399 return FALSE;
400 }
401
402 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ? TRUE : FALSE;
403 }
404
405 /**
406 * @param $value
407 * @param $noOfDigit
408 *
409 * @return bool
410 */
411 public static function numberOfDigit($value, $noOfDigit) {
412 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ? TRUE : FALSE;
413 }
414
415 /**
416 * @param $value
417 *
418 * @return mixed
419 */
420 public static function cleanMoney($value) {
421 // first remove all white space
422 $value = str_replace(array(' ', "\t", "\n"), '', $value);
423
424 $config = CRM_Core_Config::singleton();
425
426 //CRM-14868
427 $currencySymbols = CRM_Core_PseudoConstant::get(
428 'CRM_Contribute_DAO_Contribution',
429 'currency', array(
430 'keyColumn' => 'name',
431 'labelColumn' => 'symbol',
432 )
433 );
434 $value = str_replace($currencySymbols, '', $value);
435
436 if ($config->monetaryThousandSeparator) {
437 $mon_thousands_sep = $config->monetaryThousandSeparator;
438 }
439 else {
440 $mon_thousands_sep = ',';
441 }
442
443 // ugly fix for CRM-6391: do not drop the thousand separator if
444 // it looks like it’s separating decimal part (because a given
445 // value undergoes a second cleanMoney() call, for example)
446 // CRM-15835 - in case the amount/value contains 0 after decimal
447 // eg 150.5 the following if condition will pass
448 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
449 $value = str_replace($mon_thousands_sep, '', $value);
450 }
451
452 if ($config->monetaryDecimalPoint) {
453 $mon_decimal_point = $config->monetaryDecimalPoint;
454 }
455 else {
456 $mon_decimal_point = '.';
457 }
458 $value = str_replace($mon_decimal_point, '.', $value);
459
460 return $value;
461 }
462
463 /**
464 * @param $value
465 *
466 * @return bool
467 */
468 public static function money($value) {
469 $config = CRM_Core_Config::singleton();
470
471 //only edge case when we have a decimal point in the input money
472 //field and not defined in the decimal Point in config settings
473 if ($config->monetaryDecimalPoint &&
474 $config->monetaryDecimalPoint != '.' &&
475 /* CRM-7122 also check for Thousands Separator in config settings */
476 $config->monetaryThousandSeparator != '.' &&
477 substr_count($value, '.')
478 ) {
479 return FALSE;
480 }
481
482 $value = self::cleanMoney($value);
483
484 if (self::integer($value)) {
485 return TRUE;
486 }
487
488 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ? TRUE : FALSE;
489 }
490
491 /**
492 * @param $value
493 * @param int $maxLength
494 *
495 * @return bool
496 */
497 public static function string($value, $maxLength = 0) {
498 if (is_string($value) &&
499 ($maxLength === 0 || strlen($value) <= $maxLength)
500 ) {
501 return TRUE;
502 }
503 return FALSE;
504 }
505
506 /**
507 * @param $value
508 *
509 * @return bool
510 */
511 public static function boolean($value) {
512 return preg_match(
513 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
514 ) ? TRUE : FALSE;
515 }
516
517 /**
518 * @param $value
519 *
520 * @return bool
521 */
522 public static function email($value) {
523 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL);
524 }
525
526 /**
527 * @param $list
528 *
529 * @return bool
530 */
531 public static function emailList($list) {
532 $emails = explode(',', $list);
533 foreach ($emails as $email) {
534 $email = trim($email);
535 if (!self::email($email)) {
536 return FALSE;
537 }
538 }
539 return TRUE;
540 }
541
542 /**
543 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
544 * if u disregard the first 0, 4 (thanx excel!)
545 * FIXME: we need to figure out how to localize such rules
546 * @param $value
547 *
548 * @return bool
549 */
550 public static function postalCode($value) {
551 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
552 return TRUE;
553 }
554 return FALSE;
555 }
556
557 /**
558 * See how file rules are written in HTML/QuickForm/file.php
559 * Checks to make sure the uploaded file is ascii
560 *
561 * @return bool
562 * true if file has been uploaded, false otherwise
563 */
564 public static function asciiFile($elementValue) {
565 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
566 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
567 ) {
568 return CRM_Utils_File::isAscii($elementValue['tmp_name']);
569 }
570 return FALSE;
571 }
572
573 /**
574 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
575 *
576 * @return bool
577 * whether file has been uploaded properly and is now in UTF-8
578 */
579 public static function utf8File($elementValue) {
580 $success = FALSE;
581
582 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
583 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
584 ) {
585
586 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
587
588 // if it's a file, but not UTF-8, let's try and recode it
589 // and then make sure it's an UTF-8 file in the end
590 if (!$success) {
591 $success = CRM_Utils_File::toUtf8($elementValue['tmp_name']);
592 if ($success) {
593 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
594 }
595 }
596 }
597 return $success;
598 }
599
600 /**
601 * See how file rules are written in HTML/QuickForm/file.php
602 * Checks to make sure the uploaded file is html
603 *
604 * @return bool
605 * true if file has been uploaded, false otherwise
606 */
607 public static function htmlFile($elementValue) {
608 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
609 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
610 ) {
611 return CRM_Utils_File::isHtmlFile($elementValue['tmp_name']);
612 }
613 return FALSE;
614 }
615
616 /**
617 * Check if there is a record with the same name in the db.
618 *
619 * @param string $value
620 * The value of the field we are checking.
621 * @param array $options
622 * The daoName and fieldName (optional ).
623 *
624 * @return bool
625 * true if object exists
626 */
627 public static function objectExists($value, $options) {
628 $name = 'name';
629 if (isset($options[2])) {
630 $name = $options[2];
631 }
632
633 return CRM_Core_DAO::objectExists($value, CRM_Utils_Array::value(0, $options), CRM_Utils_Array::value(1, $options), CRM_Utils_Array::value(2, $options, $name));
634 }
635
636 /**
637 * @param $value
638 * @param $options
639 *
640 * @return bool
641 */
642 public static function optionExists($value, $options) {
643 return CRM_Core_OptionValue::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array::value(3, $options, 'name'));
644 }
645
646 /**
647 * @param $value
648 * @param $type
649 *
650 * @return bool
651 */
652 public static function creditCardNumber($value, $type) {
653 require_once 'Validate/Finance/CreditCard.php';
654 return Validate_Finance_CreditCard::number($value, $type);
655 }
656
657 /**
658 * @param $value
659 * @param $type
660 *
661 * @return bool
662 */
663 public static function cvv($value, $type) {
664 require_once 'Validate/Finance/CreditCard.php';
665
666 return Validate_Finance_CreditCard::cvv($value, $type);
667 }
668
669 /**
670 * @param $value
671 *
672 * @return bool
673 */
674 public static function currencyCode($value) {
675 static $currencyCodes = NULL;
676 if (!$currencyCodes) {
677 $currencyCodes = CRM_Core_PseudoConstant::currencyCode();
678 }
679 if (in_array($value, $currencyCodes)) {
680 return TRUE;
681 }
682 return FALSE;
683 }
684
685 /**
686 * @param $value
687 *
688 * @return bool
689 */
690 public static function xssString($value) {
691 if (is_string($value)) {
692 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
693 $value
694 ) ? FALSE : TRUE;
695 }
696 else {
697 return TRUE;
698 }
699 }
700
701 /**
702 * @param $path
703 *
704 * @return bool
705 */
706 public static function fileExists($path) {
707 return file_exists($path);
708 }
709
710 /**
711 * @param $value
712 * @param $options
713 *
714 * @return bool
715 */
716 public static function autocomplete($value, $options) {
717 if ($value) {
718 $selectOption = CRM_Core_BAO_CustomOption::valuesByID($options['fieldID'], $options['optionGroupID']);
719
720 if (!in_array($value, $selectOption)) {
721 return FALSE;
722 }
723 }
724 return TRUE;
725 }
726
727 /**
728 * @param $value
729 * @param null $actualElementValue
730 *
731 * @return bool
732 */
733 public static function validContact($value, $actualElementValue = NULL) {
734 if ($actualElementValue) {
735 $value = $actualElementValue;
736 }
737
738 if ($value && !is_numeric($value)) {
739 return FALSE;
740 }
741 return TRUE;
742 }
743
744 /**
745 * Check the validity of the date (in qf format)
746 * note that only a year is valid, or a mon-year is
747 * also valid in addition to day-mon-year
748 *
749 * @param array $date
750 *
751 * @return bool
752 * true if valid date
753 */
754 public static function qfDate($date) {
755 $config = CRM_Core_Config::singleton();
756
757 $d = CRM_Utils_Array::value('d', $date);
758 $m = CRM_Utils_Array::value('M', $date);
759 $y = CRM_Utils_Array::value('Y', $date);
760 if (isset($date['h']) ||
761 isset($date['g'])
762 ) {
763 $m = CRM_Utils_Array::value('M', $date);
764 }
765
766 if (!$d && !$m && !$y) {
767 return TRUE;
768 }
769
770 $day = $mon = 1;
771 $year = 0;
772 if ($d) {
773 $day = $d;
774 }
775 if ($m) {
776 $mon = $m;
777 }
778 if ($y) {
779 $year = $y;
780 }
781
782 // if we have day we need mon, and if we have mon we need year
783 if (($d && !$m) ||
784 ($d && !$y) ||
785 ($m && !$y)
786 ) {
787 return FALSE;
788 }
789
790 if (!empty($day) || !empty($mon) || !empty($year)) {
791 return checkdate($mon, $day, $year);
792 }
793 return FALSE;
794 }
795
796 /**
797 * @param $key
798 *
799 * @return bool
800 */
801 public static function qfKey($key) {
802 return ($key) ? CRM_Core_Key::valid($key) : FALSE;
803 }
804
805 }