Merge pull request #4123 from eileenmcnaughton/CRM-15296
[civicrm-core.git] / CRM / Utils / Rule.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 require_once 'HTML/QuickForm/Rule/Email.php';
37
38 /**
39 * Class CRM_Utils_Rule
40 */
41 class CRM_Utils_Rule {
42
43 /**
44 * @param $str
45 * @param int $maxLength
46 *
47 * @return bool
48 */
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
64 /**
65 * @param $str
66 *
67 * @return bool
68 */
69 static function longTitle($str) {
70 return self::title($str, 255);
71 }
72
73 /**
74 * @param $str
75 *
76 * @return bool
77 */
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
92 /**
93 * @param $str
94 *
95 * @return bool
96 */
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
113 /**
114 * @param $phone
115 *
116 * @return bool
117 */
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
131 /**
132 * @param $query
133 *
134 * @return bool
135 */
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
150 /**
151 * @param $url
152 *
153 * @return bool
154 */
155 static function url($url) {
156 return (bool) filter_var($url, FILTER_VALIDATE_URL);
157 }
158
159 /**
160 * @param $string
161 *
162 * @return bool
163 */
164 static function wikiURL($string) {
165 $items = explode(' ', trim($string), 2);
166 return self::url($items[0]);
167 }
168
169 /**
170 * @param $domain
171 *
172 * @return bool
173 */
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
182 /**
183 * @param $value
184 * @param null $default
185 *
186 * @return null
187 */
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
197 /**
198 * @param $value
199 * @param null $default
200 *
201 * @return null|string
202 */
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 /**
215 * check the validity of the date (in qf format)
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'
239 if (!$m && !empty($date['m'])) {
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 /**
308 * check the validity of a date or datetime (timestamp)
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
332 /**
333 * @param $value
334 *
335 * @return bool
336 */
337 static function integer($value) {
338 if (is_int($value)) {
339 return TRUE;
340 }
341
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) {
356 $negValue = -1 * $value;
357 if (is_int($negValue)) {
358 return TRUE;
359 }
360 }
361
362 return FALSE;
363 }
364
365 /**
366 * @param $value
367 *
368 * @return bool
369 */
370 static function positiveInteger($value) {
371 if (is_int($value)) {
372 return ($value < 0) ? FALSE : TRUE;
373 }
374
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)) {
382 return TRUE;
383 }
384
385 return FALSE;
386 }
387
388 /**
389 * @param $value
390 *
391 * @return bool
392 */
393 static function numeric($value) {
394 // lets use a php gatekeeper to ensure this is numeric
395 if (!is_numeric($value)) {
396 return FALSE;
397 }
398
399 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ? TRUE : FALSE;
400 }
401
402 /**
403 * @param $value
404 * @param $noOfDigit
405 *
406 * @return bool
407 */
408 static function numberOfDigit($value, $noOfDigit) {
409 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ? TRUE : FALSE;
410 }
411
412 /**
413 * @param $value
414 *
415 * @return mixed
416 */
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
423 if ($config->monetaryThousandSeparator) {
424 $mon_thousands_sep = $config->monetaryThousandSeparator;
425 }
426 else {
427 $mon_thousands_sep = ',';
428 }
429
430 // ugly fix for CRM-6391: do not drop the thousand separator if
431 // it looks like it’s separating decimal part (because a given
432 // value undergoes a second cleanMoney() call, for example)
433 if ($mon_thousands_sep != '.' or substr($value, -3, 1) != '.') {
434 $value = str_replace($mon_thousands_sep, '', $value);
435 }
436
437 if ($config->monetaryDecimalPoint) {
438 $mon_decimal_point = $config->monetaryDecimalPoint;
439 }
440 else {
441 $mon_decimal_point = '.';
442 }
443 $value = str_replace($mon_decimal_point, '.', $value);
444
445 return $value;
446 }
447
448 /**
449 * @param $value
450 *
451 * @return bool
452 */
453 static function money($value) {
454 $config = CRM_Core_Config::singleton();
455
456 //only edge case when we have a decimal point in the input money
457 //field and not defined in the decimal Point in config settings
458 if ($config->monetaryDecimalPoint &&
459 $config->monetaryDecimalPoint != '.' &&
460 /* CRM-7122 also check for Thousands Separator in config settings */
461 $config->monetaryThousandSeparator != '.' &&
462 substr_count($value, '.')
463 ) {
464 return FALSE;
465 }
466
467 $value = self::cleanMoney($value);
468
469 if (self::integer($value)) {
470 return TRUE;
471 }
472
473 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ? TRUE : FALSE;
474 }
475
476 /**
477 * @param $value
478 * @param int $maxLength
479 *
480 * @return bool
481 */
482 static function string($value, $maxLength = 0) {
483 if (is_string($value) &&
484 ($maxLength === 0 || strlen($value) <= $maxLength)
485 ) {
486 return TRUE;
487 }
488 return FALSE;
489 }
490
491 /**
492 * @param $value
493 *
494 * @return bool
495 */
496 static function boolean($value) {
497 return preg_match(
498 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
499 ) ? TRUE : FALSE;
500 }
501
502 /**
503 * @param $value
504 *
505 * @return bool
506 */
507 static function email($value) {
508 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL);
509 }
510
511 /**
512 * @param $list
513 *
514 * @return bool
515 */
516 static function emailList($list) {
517 $emails = explode(',', $list);
518 foreach ($emails as $email) {
519 $email = trim($email);
520 if (!self::email($email)) {
521 return FALSE;
522 }
523 }
524 return TRUE;
525 }
526
527 // allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
528 // if u disregard the first 0, 4 (thanx excel!)
529 // FIXME: we need to figure out how to localize such rules
530 /**
531 * @param $value
532 *
533 * @return bool
534 */
535 static function postalCode($value) {
536 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
537 return TRUE;
538 }
539 return FALSE;
540 }
541
542 /**
543 * see how file rules are written in HTML/QuickForm/file.php
544 * Checks to make sure the uploaded file is ascii
545 *
546 * @param array Uploaded file info (from $_FILES)
547 * @access private
548 *
549 * @return bool true if file has been uploaded, false otherwise
550 */
551 static function asciiFile($elementValue) {
552 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
553 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
554 ) {
555 return CRM_Utils_File::isAscii($elementValue['tmp_name']);
556 }
557 return FALSE;
558 }
559
560 /**
561 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
562 *
563 * @param array Uploaded file info (from $_FILES)
564 * @access private
565 *
566 * @return bool whether file has been uploaded properly and is now in UTF-8
567 */
568 static function utf8File($elementValue) {
569 $success = FALSE;
570
571 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
572 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
573 ) {
574
575 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
576
577 // if it's a file, but not UTF-8, let's try and recode it
578 // and then make sure it's an UTF-8 file in the end
579 if (!$success) {
580 $success = CRM_Utils_File::toUtf8($elementValue['tmp_name']);
581 if ($success) {
582 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
583 }
584 }
585 }
586 return $success;
587 }
588
589 /**
590 * see how file rules are written in HTML/QuickForm/file.php
591 * Checks to make sure the uploaded file is html
592 *
593 * @param array Uploaded file info (from $_FILES)
594 * @access private
595 *
596 * @return bool true if file has been uploaded, false otherwise
597 */
598 static function htmlFile($elementValue) {
599 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
600 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
601 ) {
602 return CRM_Utils_File::isHtmlFile($elementValue['tmp_name']);
603 }
604 return FALSE;
605 }
606
607 /**
608 * Check if there is a record with the same name in the db
609 *
610 * @param string $value the value of the field we are checking
611 * @param array $options the daoName and fieldName (optional )
612 *
613 * @return boolean true if object exists
614 * @access public
615 * @static
616 */
617 static function objectExists($value, $options) {
618 $name = 'name';
619 if (isset($options[2])) {
620 $name = $options[2];
621 }
622
623 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));
624 }
625
626 /**
627 * @param $value
628 * @param $options
629 *
630 * @return bool
631 */
632 static function optionExists($value, $options) {
633 return CRM_Core_OptionValue::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array::value(3, $options, 'name'));
634 }
635
636 /**
637 * @param $value
638 * @param $type
639 *
640 * @return bool
641 */
642 static function creditCardNumber($value, $type) {
643 require_once 'Validate/Finance/CreditCard.php';
644 return Validate_Finance_CreditCard::number($value, $type);
645 }
646
647 /**
648 * @param $value
649 * @param $type
650 *
651 * @return bool
652 */
653 static function cvv($value, $type) {
654 require_once 'Validate/Finance/CreditCard.php';
655
656 return Validate_Finance_CreditCard::cvv($value, $type);
657 }
658
659 /**
660 * @param $value
661 *
662 * @return bool
663 */
664 static function currencyCode($value) {
665 static $currencyCodes = NULL;
666 if (!$currencyCodes) {
667 $currencyCodes = CRM_Core_PseudoConstant::currencyCode();
668 }
669 if (in_array($value, $currencyCodes)) {
670 return TRUE;
671 }
672 return FALSE;
673 }
674
675 /**
676 * @param $value
677 *
678 * @return bool
679 */
680 static function xssString($value) {
681 if (is_string($value)) {
682 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
683 $value
684 ) ? FALSE : TRUE;
685 }
686 else {
687 return TRUE;
688 }
689 }
690
691 /**
692 * @param $path
693 *
694 * @return bool
695 */
696 static function fileExists($path) {
697 return file_exists($path);
698 }
699
700 /**
701 * @param $value
702 * @param $options
703 *
704 * @return bool
705 */
706 static function autocomplete($value, $options) {
707 if ($value) {
708 $selectOption = CRM_Core_BAO_CustomOption::valuesByID($options['fieldID'], $options['optionGroupID']);
709
710 if (!in_array($value, $selectOption)) {
711 return FALSE;
712 }
713 }
714 return TRUE;
715 }
716
717 /**
718 * @param $value
719 * @param null $actualElementValue
720 *
721 * @return bool
722 */
723 static function validContact($value, $actualElementValue = NULL) {
724 if ($actualElementValue) {
725 $value = $actualElementValue;
726 }
727
728 if ($value && !is_numeric($value)) {
729 return FALSE;
730 }
731 return TRUE;
732 }
733
734 /**
735 * check the validity of the date (in qf format)
736 * note that only a year is valid, or a mon-year is
737 * also valid in addition to day-mon-year
738 *
739 * @param array $date
740 *
741 * @return bool true if valid date
742 * @static
743 * @access public
744 */
745 static function qfDate($date) {
746 $config = CRM_Core_Config::singleton();
747
748 $d = CRM_Utils_Array::value('d', $date);
749 $m = CRM_Utils_Array::value('M', $date);
750 $y = CRM_Utils_Array::value('Y', $date);
751 if (isset($date['h']) ||
752 isset($date['g'])
753 ) {
754 $m = CRM_Utils_Array::value('M', $date);
755 }
756
757 if (!$d && !$m && !$y) {
758 return TRUE;
759 }
760
761 $day = $mon = 1;
762 $year = 0;
763 if ($d) {
764 $day = $d;
765 }
766 if ($m) {
767 $mon = $m;
768 }
769 if ($y) {
770 $year = $y;
771 }
772
773 // if we have day we need mon, and if we have mon we need year
774 if (($d && !$m) ||
775 ($d && !$y) ||
776 ($m && !$y)
777 ) {
778 return FALSE;
779 }
780
781 if (!empty($day) || !empty($mon) || !empty($year)) {
782 return checkdate($mon, $day, $year);
783 }
784 return FALSE;
785 }
786
787 /**
788 * @param $key
789 *
790 * @return bool
791 */
792 static function qfKey($key) {
793 return ($key) ? CRM_Core_Key::valid($key) : FALSE;
794 }
795 }
796