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