65944518963515ecf2bedba812b9e32229f9b938
[civicrm-core.git] / CRM / Utils / Rule.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 public 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 public static function longTitle($str) {
70 return self::title($str, 255);
71 }
72
73 /**
74 * @param $str
75 *
76 * @return bool
77 */
78 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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
226 * Check whether month is mandatory.
227 *
228 * @return bool
229 * true if valid date
230 */
231 public 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
320 * true if valid date
321 */
322 public static function mysqlDate($date) {
323 // allow date to be null
324 if ($date == NULL) {
325 return TRUE;
326 }
327
328 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
329 return TRUE;
330 }
331
332 return FALSE;
333 }
334
335 /**
336 * @param $value
337 *
338 * @return bool
339 */
340 public static function integer($value) {
341 if (is_int($value)) {
342 return TRUE;
343 }
344
345 // CRM-13460
346 // ensure number passed is always a string numeral
347 if (!is_numeric($value)) {
348 return FALSE;
349 }
350
351 // note that is_int matches only integer type
352 // and not strings which are only integers
353 // hence we do this here
354 if (preg_match('/^\d+$/', $value)) {
355 return TRUE;
356 }
357
358 if ($value < 0) {
359 $negValue = -1 * $value;
360 if (is_int($negValue)) {
361 return TRUE;
362 }
363 }
364
365 return FALSE;
366 }
367
368 /**
369 * @param $value
370 *
371 * @return bool
372 */
373 public static function positiveInteger($value) {
374 if (is_int($value)) {
375 return ($value < 0) ? FALSE : TRUE;
376 }
377
378 // CRM-13460
379 // ensure number passed is always a string numeral
380 if (!is_numeric($value)) {
381 return FALSE;
382 }
383
384 if (preg_match('/^\d+$/', $value)) {
385 return TRUE;
386 }
387
388 return FALSE;
389 }
390
391 /**
392 * @param $value
393 *
394 * @return bool
395 */
396 public static function numeric($value) {
397 // lets use a php gatekeeper to ensure this is numeric
398 if (!is_numeric($value)) {
399 return FALSE;
400 }
401
402 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ? TRUE : FALSE;
403 }
404
405 /**
406 * @param $value
407 * @param $noOfDigit
408 *
409 * @return bool
410 */
411 public static function numberOfDigit($value, $noOfDigit) {
412 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ? TRUE : FALSE;
413 }
414
415 /**
416 * @param $value
417 *
418 * @return mixed
419 */
420 public static function cleanMoney($value) {
421 // first remove all white space
422 $value = str_replace(array(' ', "\t", "\n"), '', $value);
423
424 $config = CRM_Core_Config::singleton();
425
426 //CRM-14868
427 $currencySymbols = CRM_Core_PseudoConstant::get(
428 'CRM_Contribute_DAO_Contribution',
429 'currency', array(
430 'keyColumn' => 'name',
431 'labelColumn' => 'symbol',
432 ));
433 $value = str_replace($currencySymbols, '', $value);
434
435 if ($config->monetaryThousandSeparator) {
436 $mon_thousands_sep = $config->monetaryThousandSeparator;
437 }
438 else {
439 $mon_thousands_sep = ',';
440 }
441
442 // ugly fix for CRM-6391: do not drop the thousand separator if
443 // it looks like it’s separating decimal part (because a given
444 // value undergoes a second cleanMoney() call, for example)
445 if ($mon_thousands_sep != '.' or substr($value, -3, 1) != '.') {
446 $value = str_replace($mon_thousands_sep, '', $value);
447 }
448
449 if ($config->monetaryDecimalPoint) {
450 $mon_decimal_point = $config->monetaryDecimalPoint;
451 }
452 else {
453 $mon_decimal_point = '.';
454 }
455 $value = str_replace($mon_decimal_point, '.', $value);
456
457 return $value;
458 }
459
460 /**
461 * @param $value
462 *
463 * @return bool
464 */
465 public static function money($value) {
466 $config = CRM_Core_Config::singleton();
467
468 //only edge case when we have a decimal point in the input money
469 //field and not defined in the decimal Point in config settings
470 if ($config->monetaryDecimalPoint &&
471 $config->monetaryDecimalPoint != '.' &&
472 /* CRM-7122 also check for Thousands Separator in config settings */
473 $config->monetaryThousandSeparator != '.' &&
474 substr_count($value, '.')
475 ) {
476 return FALSE;
477 }
478
479 $value = self::cleanMoney($value);
480
481 if (self::integer($value)) {
482 return TRUE;
483 }
484
485 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ? TRUE : FALSE;
486 }
487
488 /**
489 * @param $value
490 * @param int $maxLength
491 *
492 * @return bool
493 */
494 public static function string($value, $maxLength = 0) {
495 if (is_string($value) &&
496 ($maxLength === 0 || strlen($value) <= $maxLength)
497 ) {
498 return TRUE;
499 }
500 return FALSE;
501 }
502
503 /**
504 * @param $value
505 *
506 * @return bool
507 */
508 public static function boolean($value) {
509 return preg_match(
510 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
511 ) ? TRUE : FALSE;
512 }
513
514 /**
515 * @param $value
516 *
517 * @return bool
518 */
519 public static function email($value) {
520 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL);
521 }
522
523 /**
524 * @param $list
525 *
526 * @return bool
527 */
528 public static function emailList($list) {
529 $emails = explode(',', $list);
530 foreach ($emails as $email) {
531 $email = trim($email);
532 if (!self::email($email)) {
533 return FALSE;
534 }
535 }
536 return TRUE;
537 }
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 * @param $value
544 *
545 * @return bool
546 */
547 public static function postalCode($value) {
548 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
549 return TRUE;
550 }
551 return FALSE;
552 }
553
554 /**
555 * See how file rules are written in HTML/QuickForm/file.php
556 * Checks to make sure the uploaded file is ascii
557 *
558 * @param array Uploaded file info (from $_FILES)
559 *
560 * @return bool
561 * true if file has been uploaded, false otherwise
562 */
563 public static function asciiFile($elementValue) {
564 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
565 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
566 ) {
567 return CRM_Utils_File::isAscii($elementValue['tmp_name']);
568 }
569 return FALSE;
570 }
571
572 /**
573 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
574 *
575 * @param array Uploaded file info (from $_FILES)
576 *
577 * @return bool
578 * whether file has been uploaded properly and is now in UTF-8
579 */
580 public static function utf8File($elementValue) {
581 $success = FALSE;
582
583 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
584 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
585 ) {
586
587 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
588
589 // if it's a file, but not UTF-8, let's try and recode it
590 // and then make sure it's an UTF-8 file in the end
591 if (!$success) {
592 $success = CRM_Utils_File::toUtf8($elementValue['tmp_name']);
593 if ($success) {
594 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
595 }
596 }
597 }
598 return $success;
599 }
600
601 /**
602 * See how file rules are written in HTML/QuickForm/file.php
603 * Checks to make sure the uploaded file is html
604 *
605 * @param array Uploaded file info (from $_FILES)
606 *
607 * @return bool
608 * true if file has been uploaded, false otherwise
609 */
610 public static function htmlFile($elementValue) {
611 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
612 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
613 ) {
614 return CRM_Utils_File::isHtmlFile($elementValue['tmp_name']);
615 }
616 return FALSE;
617 }
618
619 /**
620 * Check if there is a record with the same name in the db
621 *
622 * @param string $value
623 * The value of the field we are checking.
624 * @param array $options
625 * The daoName and fieldName (optional ).
626 *
627 * @return boolean
628 * true if object exists
629 */
630 public 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 public 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 public 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 public 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 public 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 public 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 public static function fileExists($path) {
710 return file_exists($path);
711 }
712
713 /**
714 * @param $value
715 * @param $options
716 *
717 * @return bool
718 */
719 public 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 public 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
755 * true if valid date
756 */
757 public static function qfDate($date) {
758 $config = CRM_Core_Config::singleton();
759
760 $d = CRM_Utils_Array::value('d', $date);
761 $m = CRM_Utils_Array::value('M', $date);
762 $y = CRM_Utils_Array::value('Y', $date);
763 if (isset($date['h']) ||
764 isset($date['g'])
765 ) {
766 $m = CRM_Utils_Array::value('M', $date);
767 }
768
769 if (!$d && !$m && !$y) {
770 return TRUE;
771 }
772
773 $day = $mon = 1;
774 $year = 0;
775 if ($d) {
776 $day = $d;
777 }
778 if ($m) {
779 $mon = $m;
780 }
781 if ($y) {
782 $year = $y;
783 }
784
785 // if we have day we need mon, and if we have mon we need year
786 if (($d && !$m) ||
787 ($d && !$y) ||
788 ($m && !$y)
789 ) {
790 return FALSE;
791 }
792
793 if (!empty($day) || !empty($mon) || !empty($year)) {
794 return checkdate($mon, $day, $year);
795 }
796 return FALSE;
797 }
798
799 /**
800 * @param $key
801 *
802 * @return bool
803 */
804 public static function qfKey($key) {
805 return ($key) ? CRM_Core_Key::valid($key) : FALSE;
806 }
807 }