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