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