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