CRM-15789 - Move htmlAttributes helper to utils class
[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 );
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 public 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 public 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 public 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 public 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 public 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 /**
541 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
542 * if u disregard the first 0, 4 (thanx excel!)
543 * FIXME: we need to figure out how to localize such rules
544 * @param $value
545 *
546 * @return bool
547 */
548 public 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 * @return bool
560 * true if file has been uploaded, false otherwise
561 */
562 public static function asciiFile($elementValue) {
563 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
564 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
565 ) {
566 return CRM_Utils_File::isAscii($elementValue['tmp_name']);
567 }
568 return FALSE;
569 }
570
571 /**
572 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
573 *
574 * @return bool
575 * whether file has been uploaded properly and is now in UTF-8
576 */
577 public static function utf8File($elementValue) {
578 $success = FALSE;
579
580 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
581 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
582 ) {
583
584 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
585
586 // if it's a file, but not UTF-8, let's try and recode it
587 // and then make sure it's an UTF-8 file in the end
588 if (!$success) {
589 $success = CRM_Utils_File::toUtf8($elementValue['tmp_name']);
590 if ($success) {
591 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
592 }
593 }
594 }
595 return $success;
596 }
597
598 /**
599 * See how file rules are written in HTML/QuickForm/file.php
600 * Checks to make sure the uploaded file is html
601 *
602 * @return bool
603 * true if file has been uploaded, false otherwise
604 */
605 public static function htmlFile($elementValue) {
606 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
607 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
608 ) {
609 return CRM_Utils_File::isHtmlFile($elementValue['tmp_name']);
610 }
611 return FALSE;
612 }
613
614 /**
615 * Check if there is a record with the same name in the db
616 *
617 * @param string $value
618 * The value of the field we are checking.
619 * @param array $options
620 * The daoName and fieldName (optional ).
621 *
622 * @return bool
623 * true if object exists
624 */
625 public static function objectExists($value, $options) {
626 $name = 'name';
627 if (isset($options[2])) {
628 $name = $options[2];
629 }
630
631 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));
632 }
633
634 /**
635 * @param $value
636 * @param $options
637 *
638 * @return bool
639 */
640 public static function optionExists($value, $options) {
641 return CRM_Core_OptionValue::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array::value(3, $options, 'name'));
642 }
643
644 /**
645 * @param $value
646 * @param $type
647 *
648 * @return bool
649 */
650 public static function creditCardNumber($value, $type) {
651 require_once 'Validate/Finance/CreditCard.php';
652 return Validate_Finance_CreditCard::number($value, $type);
653 }
654
655 /**
656 * @param $value
657 * @param $type
658 *
659 * @return bool
660 */
661 public static function cvv($value, $type) {
662 require_once 'Validate/Finance/CreditCard.php';
663
664 return Validate_Finance_CreditCard::cvv($value, $type);
665 }
666
667 /**
668 * @param $value
669 *
670 * @return bool
671 */
672 public static function currencyCode($value) {
673 static $currencyCodes = NULL;
674 if (!$currencyCodes) {
675 $currencyCodes = CRM_Core_PseudoConstant::currencyCode();
676 }
677 if (in_array($value, $currencyCodes)) {
678 return TRUE;
679 }
680 return FALSE;
681 }
682
683 /**
684 * @param $value
685 *
686 * @return bool
687 */
688 public static function xssString($value) {
689 if (is_string($value)) {
690 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
691 $value
692 ) ? FALSE : TRUE;
693 }
694 else {
695 return TRUE;
696 }
697 }
698
699 /**
700 * @param $path
701 *
702 * @return bool
703 */
704 public static function fileExists($path) {
705 return file_exists($path);
706 }
707
708 /**
709 * @param $value
710 * @param $options
711 *
712 * @return bool
713 */
714 public static function autocomplete($value, $options) {
715 if ($value) {
716 $selectOption = CRM_Core_BAO_CustomOption::valuesByID($options['fieldID'], $options['optionGroupID']);
717
718 if (!in_array($value, $selectOption)) {
719 return FALSE;
720 }
721 }
722 return TRUE;
723 }
724
725 /**
726 * @param $value
727 * @param null $actualElementValue
728 *
729 * @return bool
730 */
731 public static function validContact($value, $actualElementValue = NULL) {
732 if ($actualElementValue) {
733 $value = $actualElementValue;
734 }
735
736 if ($value && !is_numeric($value)) {
737 return FALSE;
738 }
739 return TRUE;
740 }
741
742 /**
743 * Check the validity of the date (in qf format)
744 * note that only a year is valid, or a mon-year is
745 * also valid in addition to day-mon-year
746 *
747 * @param array $date
748 *
749 * @return bool
750 * true if valid date
751 */
752 public static function qfDate($date) {
753 $config = CRM_Core_Config::singleton();
754
755 $d = CRM_Utils_Array::value('d', $date);
756 $m = CRM_Utils_Array::value('M', $date);
757 $y = CRM_Utils_Array::value('Y', $date);
758 if (isset($date['h']) ||
759 isset($date['g'])
760 ) {
761 $m = CRM_Utils_Array::value('M', $date);
762 }
763
764 if (!$d && !$m && !$y) {
765 return TRUE;
766 }
767
768 $day = $mon = 1;
769 $year = 0;
770 if ($d) {
771 $day = $d;
772 }
773 if ($m) {
774 $mon = $m;
775 }
776 if ($y) {
777 $year = $y;
778 }
779
780 // if we have day we need mon, and if we have mon we need year
781 if (($d && !$m) ||
782 ($d && !$y) ||
783 ($m && !$y)
784 ) {
785 return FALSE;
786 }
787
788 if (!empty($day) || !empty($mon) || !empty($year)) {
789 return checkdate($mon, $day, $year);
790 }
791 return FALSE;
792 }
793
794 /**
795 * @param $key
796 *
797 * @return bool
798 */
799 public static function qfKey($key) {
800 return ($key) ? CRM_Core_Key::valid($key) : FALSE;
801 }
802
803 }