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