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