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