Merge pull request #13943 from mlutfy/setMessageError
[civicrm-core.git] / CRM / Utils / Rule.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34 require_once 'HTML/QuickForm/Rule/Email.php';
35
36 /**
37 * Class CRM_Utils_Rule
38 */
39 class CRM_Utils_Rule {
40
41 /**
42 * @param $str
43 * @param int $maxLength
44 *
45 * @return bool
46 */
47 public static function title($str, $maxLength = 127) {
48
49 // check length etc
50 if (empty($str) || strlen($str) > $maxLength) {
51 return FALSE;
52 }
53
54 // Make sure it include valid characters, alpha numeric and underscores
55 if (!preg_match('/^\w[\w\s\'\&\,\$\#\-\.\"\?\!]+$/i', $str)) {
56 return FALSE;
57 }
58
59 return TRUE;
60 }
61
62 /**
63 * @param $str
64 *
65 * @return bool
66 */
67 public static function longTitle($str) {
68 return self::title($str, 255);
69 }
70
71 /**
72 * @param $str
73 *
74 * @return bool
75 */
76 public static function variable($str) {
77 // check length etc
78 if (empty($str) || strlen($str) > 31) {
79 return FALSE;
80 }
81
82 // make sure it includes valid characters, alpha numeric and underscores
83 if (!preg_match('/^[\w]+$/i', $str)) {
84 return FALSE;
85 }
86
87 return TRUE;
88 }
89
90 /**
91 * Validate that a string is a valid MySQL column name or alias.
92 *
93 * @param $str
94 *
95 * @return bool
96 */
97 public static function mysqlColumnNameOrAlias($str) {
98 // Check not empty.
99 if (empty($str)) {
100 return FALSE;
101 }
102
103 // Ensure $str conforms to expected format. Not a complete expression of
104 // what MySQL permits; this should permit the formats CiviCRM generates.
105 //
106 // * Table name prefix is optional.
107 // * Table & column names & aliases:
108 // * Composed of alphanumeric chars, underscore and hyphens.
109 // * Maximum length of 64 chars.
110 // * Optionally surrounded by backticks, in which case spaces also OK.
111 if (!preg_match('/^((`[-\w ]{1,64}`|[-\w]{1,64})\.)?(`[-\w ]{1,64}`|[-\w]{1,64})$/i', $str)) {
112 return FALSE;
113 }
114
115 return TRUE;
116 }
117
118 /**
119 * Validate that a string is ASC or DESC.
120 *
121 * Empty string should be treated as invalid and ignored => default = ASC.
122 *
123 * @param $str
124 * @return bool
125 */
126 public static function mysqlOrderByDirection($str) {
127 if (!preg_match('/^(asc|desc)$/i', $str)) {
128 return FALSE;
129 }
130
131 return TRUE;
132 }
133
134 /**
135 * Validate that a string is valid order by clause.
136 *
137 * @param $str
138 * @return bool
139 */
140 public static function mysqlOrderBy($str) {
141 $matches = array();
142 // Using the field function in order by is valid.
143 // Look for a string like field(contribution_status_id,3,4,6).
144 // or field(civicrm_contribution.contribution_status_id,3,4,6)
145 if (preg_match('/field\([a-z_.]+,[0-9,]+\)/', $str, $matches)) {
146 // We have checked these. Remove them as they will fail the next lot.
147 // Our check currently only permits numbers & no back ticks. If we get a
148 // need for strings or backticks we can add.
149 $str = str_replace($matches, '', $str);
150 }
151 $str = trim($str);
152 if (!empty($matches) && empty($str)) {
153 // nothing left to check after the field check.
154 return TRUE;
155 }
156 // Making a regex for a comma separated list is quite hard and not readable
157 // at all, so we split and loop over.
158 $parts = explode(',', $str);
159 foreach ($parts as $part) {
160 if (!preg_match('/^((`[\w-]{1,64}`|[\w-]{1,64})\.)*(`[\w-]{1,64}`|[\w-]{1,64})( (asc|desc))?$/i', trim($part))) {
161 return FALSE;
162 }
163 }
164
165 return TRUE;
166 }
167
168 /**
169 * @param $str
170 *
171 * @return bool
172 */
173 public static function qfVariable($str) {
174 // check length etc
175 //if ( empty( $str ) || strlen( $str ) > 31 ) {
176 if (strlen(trim($str)) == 0 || strlen($str) > 31) {
177 return FALSE;
178 }
179
180 // make sure it includes valid characters, alpha numeric and underscores
181 // added (. and ,) option (CRM-1336)
182 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
183 return FALSE;
184 }
185
186 return TRUE;
187 }
188
189 /**
190 * @param $phone
191 *
192 * @return bool
193 */
194 public static function phone($phone) {
195 // check length etc
196 if (empty($phone) || strlen($phone) > 16) {
197 return FALSE;
198 }
199
200 // make sure it includes valid characters, (, \s and numeric
201 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
202 return TRUE;
203 }
204 return FALSE;
205 }
206
207 /**
208 * @param $query
209 *
210 * @return bool
211 */
212 public static function query($query) {
213 // check length etc
214 if (empty($query) || strlen($query) < 3 || strlen($query) > 127) {
215 return FALSE;
216 }
217
218 // make sure it includes valid characters, alpha numeric and underscores
219 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
220 return FALSE;
221 }
222
223 return TRUE;
224 }
225
226 /**
227 * @param $url
228 *
229 * @return bool
230 */
231 public static function url($url) {
232 if (!$url) {
233 // If this is required then that should be checked elsewhere - here we are not assuming it is required.
234 return TRUE;
235 }
236 if (preg_match('/^\//', $url)) {
237 // allow relative URL's (CRM-15598)
238 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
239 }
240 return (bool) filter_var($url, FILTER_VALIDATE_URL);
241 }
242
243 /**
244 * @param $url
245 *
246 * @return bool
247 */
248 public static function urlish($url) {
249 if (empty($url)) {
250 return TRUE;
251 }
252 $url = Civi::paths()->getUrl($url, 'absolute');
253 return (bool) filter_var($url, FILTER_VALIDATE_URL);
254 }
255
256 /**
257 * @param $string
258 *
259 * @return bool
260 */
261 public static function wikiURL($string) {
262 $items = explode(' ', trim($string), 2);
263 return self::url($items[0]);
264 }
265
266 /**
267 * @param $domain
268 *
269 * @return bool
270 */
271 public static function domain($domain) {
272 // not perfect, but better than the previous one; see CRM-1502
273 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
274 return FALSE;
275 }
276 return TRUE;
277 }
278
279 /**
280 * @param $value
281 * @param null $default
282 *
283 * @return null
284 */
285 public static function date($value, $default = NULL) {
286 if (is_string($value) &&
287 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
288 ) {
289 return $value;
290 }
291 return $default;
292 }
293
294 /**
295 * @param $value
296 * @param null $default
297 *
298 * @return null|string
299 */
300 public static function dateTime($value, $default = NULL) {
301 $result = $default;
302 if (is_string($value) &&
303 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
304 ) {
305 $result = $value;
306 }
307
308 return $result;
309 }
310
311 /**
312 * Check the validity of the date (in qf format)
313 * note that only a year is valid, or a mon-year is
314 * also valid in addition to day-mon-year. The date
315 * specified has to be beyond today. (i.e today or later)
316 *
317 * @param array $date
318 * @param bool $monthRequired
319 * Check whether month is mandatory.
320 *
321 * @return bool
322 * true if valid date
323 */
324 public static function currentDate($date, $monthRequired = TRUE) {
325 $config = CRM_Core_Config::singleton();
326
327 $d = CRM_Utils_Array::value('d', $date);
328 $m = CRM_Utils_Array::value('M', $date);
329 $y = CRM_Utils_Array::value('Y', $date);
330
331 if (!$d && !$m && !$y) {
332 return TRUE;
333 }
334
335 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
336 if (!$m && !empty($date['m'])) {
337 $m = CRM_Utils_Array::value('m', $date);
338 }
339
340 $day = $mon = 1;
341 $year = 0;
342 if ($d) {
343 $day = $d;
344 }
345 if ($m) {
346 $mon = $m;
347 }
348 if ($y) {
349 $year = $y;
350 }
351
352 // if we have day we need mon, and if we have mon we need year
353 if (($d && !$m) ||
354 ($d && !$y) ||
355 ($m && !$y)
356 ) {
357 return FALSE;
358 }
359
360 $result = FALSE;
361 if (!empty($day) || !empty($mon) || !empty($year)) {
362 $result = checkdate($mon, $day, $year);
363 }
364
365 if (!$result) {
366 return FALSE;
367 }
368
369 // ensure we have month if required
370 if ($monthRequired && !$m) {
371 return FALSE;
372 }
373
374 // now make sure this date is greater that today
375 $currentDate = getdate();
376 if ($year > $currentDate['year']) {
377 return TRUE;
378 }
379 elseif ($year < $currentDate['year']) {
380 return FALSE;
381 }
382
383 if ($m) {
384 if ($mon > $currentDate['mon']) {
385 return TRUE;
386 }
387 elseif ($mon < $currentDate['mon']) {
388 return FALSE;
389 }
390 }
391
392 if ($d) {
393 if ($day > $currentDate['mday']) {
394 return TRUE;
395 }
396 elseif ($day < $currentDate['mday']) {
397 return FALSE;
398 }
399 }
400
401 return TRUE;
402 }
403
404 /**
405 * Check the validity of a date or datetime (timestamp)
406 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
407 *
408 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
409 *
410 * @param string $date
411 *
412 * @return bool
413 * true if valid date
414 */
415 public static function mysqlDate($date) {
416 // allow date to be null
417 if ($date == NULL) {
418 return TRUE;
419 }
420
421 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
422 return TRUE;
423 }
424
425 return FALSE;
426 }
427
428 /**
429 * @param $value
430 *
431 * @return bool
432 */
433 public static function integer($value) {
434 if (is_int($value)) {
435 return TRUE;
436 }
437
438 // CRM-13460
439 // ensure number passed is always a string numeral
440 if (!is_numeric($value)) {
441 return FALSE;
442 }
443
444 // note that is_int matches only integer type
445 // and not strings which are only integers
446 // hence we do this here
447 if (preg_match('/^\d+$/', $value)) {
448 return TRUE;
449 }
450
451 if ($value < 0) {
452 $negValue = -1 * $value;
453 if (is_int($negValue)) {
454 return TRUE;
455 }
456 }
457
458 return FALSE;
459 }
460
461 /**
462 * @param $value
463 *
464 * @return bool
465 */
466 public static function positiveInteger($value) {
467 if (is_int($value)) {
468 return ($value < 0) ? FALSE : TRUE;
469 }
470
471 // CRM-13460
472 // ensure number passed is always a string numeral
473 if (!is_numeric($value)) {
474 return FALSE;
475 }
476
477 if (preg_match('/^\d+$/', $value)) {
478 return TRUE;
479 }
480
481 return FALSE;
482 }
483
484 /**
485 * @param $value
486 *
487 * @return bool
488 */
489 public static function commaSeparatedIntegers($value) {
490 foreach (explode(',', $value) as $val) {
491 if (!self::positiveInteger($val)) {
492 return FALSE;
493 }
494 }
495 return TRUE;
496 }
497
498 /**
499 * @param $value
500 *
501 * @return bool
502 */
503 public static function numeric($value) {
504 // lets use a php gatekeeper to ensure this is numeric
505 if (!is_numeric($value)) {
506 return FALSE;
507 }
508
509 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ? TRUE : FALSE;
510 }
511
512 /**
513 * Test whether $value is alphanumeric.
514 *
515 * Underscores and dashes are also allowed!
516 *
517 * This is the type of string you could expect to see in URL parameters
518 * like `?mode=live` vs `?mode=test`. This function exists so that we can be
519 * strict about what we accept for such values, thus mitigating against
520 * potential security issues.
521 *
522 * @see \CRM_Utils_RuleTest::alphanumericData
523 * for examples of vales that give TRUE/FALSE here
524 *
525 * @param $value
526 *
527 * @return bool
528 */
529 public static function alphanumeric($value) {
530 return preg_match('/^[a-zA-Z0-9_-]*$/', $value) ? TRUE : FALSE;
531 }
532
533 /**
534 * @param $value
535 * @param $noOfDigit
536 *
537 * @return bool
538 */
539 public static function numberOfDigit($value, $noOfDigit) {
540 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ? TRUE : FALSE;
541 }
542
543 /**
544 * Strip thousand separator from a money string.
545 *
546 * Note that this should be done at the form layer. Once we are processing
547 * money at the BAO or processor layer we should be working with something that
548 * is already in a normalised format.
549 *
550 * @param string $value
551 *
552 * @return string
553 */
554 public static function cleanMoney($value) {
555 // first remove all white space
556 $value = str_replace(array(' ', "\t", "\n"), '', $value);
557
558 $config = CRM_Core_Config::singleton();
559
560 //CRM-14868
561 $currencySymbols = CRM_Core_PseudoConstant::get(
562 'CRM_Contribute_DAO_Contribution',
563 'currency', array(
564 'keyColumn' => 'name',
565 'labelColumn' => 'symbol',
566 )
567 );
568 $value = str_replace($currencySymbols, '', $value);
569
570 if ($config->monetaryThousandSeparator) {
571 $mon_thousands_sep = $config->monetaryThousandSeparator;
572 }
573 else {
574 $mon_thousands_sep = ',';
575 }
576
577 // ugly fix for CRM-6391: do not drop the thousand separator if
578 // it looks like it’s separating decimal part (because a given
579 // value undergoes a second cleanMoney() call, for example)
580 // CRM-15835 - in case the amount/value contains 0 after decimal
581 // eg 150.5 the following if condition will pass
582 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
583 $value = str_replace($mon_thousands_sep, '', $value);
584 }
585
586 if ($config->monetaryDecimalPoint) {
587 $mon_decimal_point = $config->monetaryDecimalPoint;
588 }
589 else {
590 $mon_decimal_point = '.';
591 }
592 $value = str_replace($mon_decimal_point, '.', $value);
593
594 return $value;
595 }
596
597 /**
598 * @param $value
599 *
600 * @return bool
601 */
602 public static function money($value) {
603 $config = CRM_Core_Config::singleton();
604
605 // only edge case when we have a decimal point in the input money
606 // field and not defined in the decimal Point in config settings
607 if ($config->monetaryDecimalPoint &&
608 $config->monetaryDecimalPoint != '.' &&
609 // CRM-7122 also check for Thousands Separator in config settings
610 $config->monetaryThousandSeparator != '.' &&
611 substr_count($value, '.')
612 ) {
613 return FALSE;
614 }
615
616 $value = self::cleanMoney($value);
617
618 if (self::integer($value)) {
619 return TRUE;
620 }
621
622 // Allow values such as -0, 1.024555, -.1
623 // We need to support multiple decimal places here, not just the number allowed by locale
624 // otherwise tax calculations break when you want the inclusive amount to be a round number (eg. £10 inc. VAT requires 8.333333333 here).
625 return preg_match('/(^-?\d+\.?\d*$)|(^-?\.\d+$)/', $value) ? TRUE : FALSE;
626 }
627
628 /**
629 * @param $value
630 * @param int $maxLength
631 *
632 * @return bool
633 */
634 public static function string($value, $maxLength = 0) {
635 if (is_string($value) &&
636 ($maxLength === 0 || strlen($value) <= $maxLength)
637 ) {
638 return TRUE;
639 }
640 return FALSE;
641 }
642
643 /**
644 * @param $value
645 *
646 * @return bool
647 */
648 public static function boolean($value) {
649 return preg_match(
650 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
651 ) ? TRUE : FALSE;
652 }
653
654 /**
655 * @param $value
656 *
657 * @return bool
658 */
659 public static function email($value) {
660 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL);
661 }
662
663 /**
664 * @param $list
665 *
666 * @return bool
667 */
668 public static function emailList($list) {
669 $emails = explode(',', $list);
670 foreach ($emails as $email) {
671 $email = trim($email);
672 if (!self::email($email)) {
673 return FALSE;
674 }
675 }
676 return TRUE;
677 }
678
679 /**
680 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
681 * if u disregard the first 0, 4 (thanx excel!)
682 * FIXME: we need to figure out how to localize such rules
683 * @param $value
684 *
685 * @return bool
686 */
687 public static function postalCode($value) {
688 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
689 return TRUE;
690 }
691 return FALSE;
692 }
693
694 /**
695 * See how file rules are written in HTML/QuickForm/file.php
696 * Checks to make sure the uploaded file is ascii
697 *
698 * @param string $elementValue
699 *
700 * @return bool
701 * True if file has been uploaded, false otherwise
702 */
703 public static function asciiFile($elementValue) {
704 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
705 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
706 ) {
707 return CRM_Utils_File::isAscii($elementValue['tmp_name']);
708 }
709 return FALSE;
710 }
711
712 /**
713 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
714 *
715 * @param array $elementValue
716 *
717 * @return bool
718 * Whether file has been uploaded properly and is now in UTF-8.
719 */
720 public static function utf8File($elementValue) {
721 $success = FALSE;
722
723 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
724 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
725 ) {
726
727 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
728
729 // if it's a file, but not UTF-8, let's try and recode it
730 // and then make sure it's an UTF-8 file in the end
731 if (!$success) {
732 $success = CRM_Utils_File::toUtf8($elementValue['tmp_name']);
733 if ($success) {
734 $success = CRM_Utils_File::isAscii($elementValue['tmp_name']);
735 }
736 }
737 }
738 return $success;
739 }
740
741 /**
742 * See how file rules are written in HTML/QuickForm/file.php
743 * Checks to make sure the uploaded file is html
744 *
745 * @param array $elementValue
746 *
747 * @return bool
748 * True if file has been uploaded, false otherwise
749 */
750 public static function htmlFile($elementValue) {
751 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
752 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
753 ) {
754 return CRM_Utils_File::isHtmlFile($elementValue['tmp_name']);
755 }
756 return FALSE;
757 }
758
759 /**
760 * Check if there is a record with the same name in the db.
761 *
762 * @param string $value
763 * The value of the field we are checking.
764 * @param array $options
765 * The daoName, fieldName (optional) and DomainID (optional).
766 *
767 * @return bool
768 * true if object exists
769 */
770 public static function objectExists($value, $options) {
771 $name = 'name';
772 if (isset($options[2])) {
773 $name = $options[2];
774 }
775
776 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), CRM_Utils_Array::value(3, $options));
777 }
778
779 /**
780 * @param $value
781 * @param $options
782 *
783 * @return bool
784 */
785 public static function optionExists($value, $options) {
786 return CRM_Core_OptionValue::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array::value(3, $options, 'name'), CRM_Utils_Array::value(4, $options, FALSE));
787 }
788
789 /**
790 * @param $value
791 * @param $type
792 *
793 * @return bool
794 */
795 public static function creditCardNumber($value, $type) {
796 return Validate_Finance_CreditCard::number($value, $type);
797 }
798
799 /**
800 * @param $value
801 * @param $type
802 *
803 * @return bool
804 */
805 public static function cvv($value, $type) {
806 return Validate_Finance_CreditCard::cvv($value, $type);
807 }
808
809 /**
810 * @param $value
811 *
812 * @return bool
813 */
814 public static function currencyCode($value) {
815 static $currencyCodes = NULL;
816 if (!$currencyCodes) {
817 $currencyCodes = CRM_Core_PseudoConstant::currencyCode();
818 }
819 if (in_array($value, $currencyCodes)) {
820 return TRUE;
821 }
822 return FALSE;
823 }
824
825 /**
826 * @param $value
827 *
828 * @return bool
829 */
830 public static function xssString($value) {
831 if (is_string($value)) {
832 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
833 $value
834 ) ? FALSE : TRUE;
835 }
836 else {
837 return TRUE;
838 }
839 }
840
841 /**
842 * Validate json string for xss
843 *
844 * @param string $value
845 *
846 * @return bool
847 * False if invalid, true if valid / safe.
848 */
849 public static function json($value) {
850 if (!self::xssString($value)) {
851 return FALSE;
852 }
853 $array = json_decode($value, TRUE);
854 if (!$array || !is_array($array)) {
855 return FALSE;
856 }
857 return self::arrayValue($array);
858 }
859
860 /**
861 * @param $path
862 *
863 * @return bool
864 */
865 public static function fileExists($path) {
866 return file_exists($path);
867 }
868
869 /**
870 * Determine whether the value contains a valid reference to a directory.
871 *
872 * Paths stored in the setting system may be absolute -- or may be
873 * relative to the default data directory.
874 *
875 * @param string $path
876 * @return bool
877 */
878 public static function settingPath($path) {
879 return is_dir(Civi::paths()->getPath($path));
880 }
881
882 /**
883 * @param $value
884 * @param null $actualElementValue
885 *
886 * @return bool
887 */
888 public static function validContact($value, $actualElementValue = NULL) {
889 if ($actualElementValue) {
890 $value = $actualElementValue;
891 }
892
893 return CRM_Utils_Rule::positiveInteger($value);
894 }
895
896 /**
897 * Check the validity of the date (in qf format)
898 * note that only a year is valid, or a mon-year is
899 * also valid in addition to day-mon-year
900 *
901 * @param array $date
902 *
903 * @return bool
904 * true if valid date
905 */
906 public static function qfDate($date) {
907 $config = CRM_Core_Config::singleton();
908
909 $d = CRM_Utils_Array::value('d', $date);
910 $m = CRM_Utils_Array::value('M', $date);
911 $y = CRM_Utils_Array::value('Y', $date);
912 if (isset($date['h']) ||
913 isset($date['g'])
914 ) {
915 $m = CRM_Utils_Array::value('M', $date);
916 }
917
918 if (!$d && !$m && !$y) {
919 return TRUE;
920 }
921
922 $day = $mon = 1;
923 $year = 0;
924 if ($d) {
925 $day = $d;
926 }
927 if ($m) {
928 $mon = $m;
929 }
930 if ($y) {
931 $year = $y;
932 }
933
934 // if we have day we need mon, and if we have mon we need year
935 if (($d && !$m) ||
936 ($d && !$y) ||
937 ($m && !$y)
938 ) {
939 return FALSE;
940 }
941
942 if (!empty($day) || !empty($mon) || !empty($year)) {
943 return checkdate($mon, $day, $year);
944 }
945 return FALSE;
946 }
947
948 /**
949 * @param $key
950 *
951 * @return bool
952 */
953 public static function qfKey($key) {
954 return ($key) ? CRM_Core_Key::valid($key) : FALSE;
955 }
956
957 /**
958 * Check if the values in the date range are in correct chronological order.
959 *
960 * @param array $fields
961 * Fields of the form.
962 * @param $fieldName
963 * Name of date range field.
964 * @param $errors
965 * The error array.
966 * @param $title
967 * Title of the date range to be displayed in the error message.
968 */
969 public static function validDateRange($fields, $fieldName, &$errors, $title) {
970 $lowDate = strtotime($fields[$fieldName . '_low']);
971 $highDate = strtotime($fields[$fieldName . '_high']);
972
973 if ($lowDate > $highDate) {
974 $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', array(1 => $title));
975 }
976 }
977
978 /**
979 * @param string $key Extension Key to check
980 * @return bool
981 */
982 public static function checkExtensionKeyIsValid($key = NULL) {
983 if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) {
984 return FALSE;
985 }
986 return TRUE;
987 }
988
989 /**
990 * Validate array recursively checking keys and values.
991 *
992 * @param array $array
993 * @return bool
994 */
995 protected static function arrayValue($array) {
996 foreach ($array as $key => $item) {
997 if (is_array($item)) {
998 if (!self::xssString($key) || !self::arrayValue($item)) {
999 return FALSE;
1000 }
1001 }
1002 if (!self::xssString($key) || !self::xssString($item)) {
1003 return FALSE;
1004 }
1005 }
1006 return TRUE;
1007 }
1008
1009 }