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