3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
34 require_once 'HTML/QuickForm/Rule/Email.php';
37 * Class CRM_Utils_Rule
39 class CRM_Utils_Rule
{
43 * @param int $maxLength
47 public static function title($str, $maxLength = 127) {
50 if (empty($str) ||
strlen($str) > $maxLength) {
54 // Make sure it include valid characters, alpha numeric and underscores
55 if (!preg_match('/^\w[\w\s\'\&\,\$\#\-\.\"\?\!]+$/i', $str)) {
67 public static function longTitle($str) {
68 return self
::title($str, 255);
76 public static function variable($str) {
78 if (empty($str) ||
strlen($str) > 31) {
82 // make sure it includes valid characters, alpha numeric and underscores
83 if (!preg_match('/^[\w]+$/i', $str)) {
91 * Validate that a string is a valid MySQL column name or alias.
97 public static function mysqlColumnNameOrAlias($str) {
103 // Ensure $str conforms to expected format. Not a complete expression of
104 // what MySQL permits; this should permit the formats CiviCRM generates.
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)) {
119 * Validate that a string is ASC or DESC.
121 * Empty string should be treated as invalid and ignored => default = ASC.
126 public static function mysqlOrderByDirection($str) {
127 if (!preg_match('/^(asc|desc)$/i', $str)) {
135 * Validate that a string is valid order by clause.
140 public static function mysqlOrderBy($str) {
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);
152 if (!empty($matches) && empty($str)) {
153 // nothing left to check after the field check.
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))) {
173 public static function qfVariable($str) {
175 //if ( empty( $str ) || strlen( $str ) > 31 ) {
176 if (strlen(trim($str)) == 0 ||
strlen($str) > 31) {
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)) {
194 public static function phone($phone) {
196 if (empty($phone) ||
strlen($phone) > 16) {
200 // make sure it includes valid characters, (, \s and numeric
201 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
212 public static function query($query) {
214 if (empty($query) ||
strlen($query) < 3 ||
strlen($query) > 127) {
218 // make sure it includes valid characters, alpha numeric and underscores
219 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
231 public static function url($url) {
233 // If this is required then that should be checked elsewhere - here we are not assuming it is required.
236 if (preg_match('/^\//', $url)) {
237 // allow relative URL's (CRM-15598)
238 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
240 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
248 public static function urlish($url) {
252 $url = Civi
::paths()->getUrl($url, 'absolute');
253 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
261 public static function wikiURL($string) {
262 $items = explode(' ', trim($string), 2);
263 return self
::url($items[0]);
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)) {
281 * @param null $default
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)
296 * @param null $default
298 * @return null|string
300 public static function dateTime($value, $default = NULL) {
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)
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)
318 * @param bool $monthRequired
319 * Check whether month is mandatory.
324 public static function currentDate($date, $monthRequired = TRUE) {
325 $config = CRM_Core_Config
::singleton();
327 $d = CRM_Utils_Array
::value('d', $date);
328 $m = CRM_Utils_Array
::value('M', $date);
329 $y = CRM_Utils_Array
::value('Y', $date);
331 if (!$d && !$m && !$y) {
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);
352 // if we have day we need mon, and if we have mon we need year
361 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
362 $result = checkdate($mon, $day, $year);
369 // ensure we have month if required
370 if ($monthRequired && !$m) {
374 // now make sure this date is greater that today
375 $currentDate = getdate();
376 if ($year > $currentDate['year']) {
379 elseif ($year < $currentDate['year']) {
384 if ($mon > $currentDate['mon']) {
387 elseif ($mon < $currentDate['mon']) {
393 if ($day > $currentDate['mday']) {
396 elseif ($day < $currentDate['mday']) {
405 * Check the validity of a date or datetime (timestamp)
406 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
408 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
410 * @param string $date
415 public static function mysqlDate($date) {
416 // allow date to be null
421 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
433 public static function integer($value) {
434 if (is_int($value)) {
439 // ensure number passed is always a string numeral
440 if (!is_numeric($value)) {
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)) {
452 $negValue = -1 * $value;
453 if (is_int($negValue)) {
466 public static function positiveInteger($value) {
467 if (is_int($value)) {
468 return ($value < 0) ?
FALSE : TRUE;
472 // ensure number passed is always a string numeral
473 if (!is_numeric($value)) {
477 if (preg_match('/^\d+$/', $value)) {
489 public static function commaSeparatedIntegers($value) {
490 foreach (explode(',', $value) as $val) {
491 if (!self
::positiveInteger($val)) {
503 public static function numeric($value) {
504 // lets use a php gatekeeper to ensure this is numeric
505 if (!is_numeric($value)) {
509 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ?
TRUE : FALSE;
513 * Test whether $value is alphanumeric.
515 * Underscores and dashes are also allowed!
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.
522 * @see \CRM_Utils_RuleTest::alphanumericData
523 * for examples of vales that give TRUE/FALSE here
529 public static function alphanumeric($value) {
530 return preg_match('/^[a-zA-Z0-9_-]*$/', $value) ?
TRUE : FALSE;
539 public static function numberOfDigit($value, $noOfDigit) {
540 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ?
TRUE : FALSE;
544 * Strict validation of 6-digit hex color notation per html5 <input type="color">
549 public static function color($value) {
550 return (bool) preg_match('/^#([\da-fA-F]{6})$/', $value);
554 * Strip thousand separator from a money string.
556 * Note that this should be done at the form layer. Once we are processing
557 * money at the BAO or processor layer we should be working with something that
558 * is already in a normalised format.
560 * @param string $value
564 public static function cleanMoney($value) {
565 // first remove all white space
566 $value = str_replace([' ', "\t", "\n"], '', $value);
568 $config = CRM_Core_Config
::singleton();
571 $currencySymbols = CRM_Core_PseudoConstant
::get(
572 'CRM_Contribute_DAO_Contribution',
574 'keyColumn' => 'name',
575 'labelColumn' => 'symbol',
578 $value = str_replace($currencySymbols, '', $value);
580 if ($config->monetaryThousandSeparator
) {
581 $mon_thousands_sep = $config->monetaryThousandSeparator
;
584 $mon_thousands_sep = ',';
587 // ugly fix for CRM-6391: do not drop the thousand separator if
588 // it looks like it’s separating decimal part (because a given
589 // value undergoes a second cleanMoney() call, for example)
590 // CRM-15835 - in case the amount/value contains 0 after decimal
591 // eg 150.5 the following if condition will pass
592 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
593 $value = str_replace($mon_thousands_sep, '', $value);
596 if ($config->monetaryDecimalPoint
) {
597 $mon_decimal_point = $config->monetaryDecimalPoint
;
600 $mon_decimal_point = '.';
602 $value = str_replace($mon_decimal_point, '.', $value);
612 public static function money($value) {
613 $config = CRM_Core_Config
::singleton();
615 // only edge case when we have a decimal point in the input money
616 // field and not defined in the decimal Point in config settings
617 if ($config->monetaryDecimalPoint
&&
618 $config->monetaryDecimalPoint
!= '.' &&
619 // CRM-7122 also check for Thousands Separator in config settings
620 $config->monetaryThousandSeparator
!= '.' &&
621 substr_count($value, '.')
626 $value = self
::cleanMoney($value);
628 if (self
::integer($value)) {
632 // Allow values such as -0, 1.024555, -.1
633 // We need to support multiple decimal places here, not just the number allowed by locale
634 // otherwise tax calculations break when you want the inclusive amount to be a round number (eg. £10 inc. VAT requires 8.333333333 here).
635 return preg_match('/(^-?\d+\.?\d*$)|(^-?\.\d+$)/', $value) ?
TRUE : FALSE;
640 * @param int $maxLength
644 public static function string($value, $maxLength = 0) {
645 if (is_string($value) &&
646 ($maxLength === 0 ||
strlen($value) <= $maxLength)
658 public static function boolean($value) {
660 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
669 public static function email($value) {
670 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
678 public static function emailList($list) {
679 $emails = explode(',', $list);
680 foreach ($emails as $email) {
681 $email = trim($email);
682 if (!self
::email($email)) {
690 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
691 * if u disregard the first 0, 4 (thanx excel!)
692 * FIXME: we need to figure out how to localize such rules
697 public static function postalCode($value) {
698 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
705 * See how file rules are written in HTML/QuickForm/file.php
706 * Checks to make sure the uploaded file is ascii
708 * @param string $elementValue
711 * True if file has been uploaded, false otherwise
713 public static function asciiFile($elementValue) {
714 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
715 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
717 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
723 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
725 * @param array $elementValue
728 * Whether file has been uploaded properly and is now in UTF-8.
730 public static function utf8File($elementValue) {
733 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
734 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
737 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
739 // if it's a file, but not UTF-8, let's try and recode it
740 // and then make sure it's an UTF-8 file in the end
742 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
744 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
752 * See how file rules are written in HTML/QuickForm/file.php
753 * Checks to make sure the uploaded file is html
755 * @param array $elementValue
758 * True if file has been uploaded, false otherwise
760 public static function htmlFile($elementValue) {
761 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
762 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
764 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
770 * Check if there is a record with the same name in the db.
772 * @param string $value
773 * The value of the field we are checking.
774 * @param array $options
775 * The daoName, fieldName (optional) and DomainID (optional).
778 * true if object exists
780 public static function objectExists($value, $options) {
782 if (isset($options[2])) {
786 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));
795 public static function optionExists($value, $options) {
796 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));
805 public static function creditCardNumber($value, $type) {
806 return Validate_Finance_CreditCard
::number($value, $type);
815 public static function cvv($value, $type) {
816 return Validate_Finance_CreditCard
::cvv($value, $type);
824 public static function currencyCode($value) {
825 static $currencyCodes = NULL;
826 if (!$currencyCodes) {
827 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
829 if (in_array($value, $currencyCodes)) {
840 public static function xssString($value) {
841 if (is_string($value)) {
842 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
852 * Validate json string for xss
854 * @param string $value
857 * False if invalid, true if valid / safe.
859 public static function json($value) {
860 if (!self
::xssString($value)) {
863 $array = json_decode($value, TRUE);
864 if (!$array ||
!is_array($array)) {
867 return self
::arrayValue($array);
875 public static function fileExists($path) {
876 return file_exists($path);
880 * Determine whether the value contains a valid reference to a directory.
882 * Paths stored in the setting system may be absolute -- or may be
883 * relative to the default data directory.
885 * @param string $path
888 public static function settingPath($path) {
889 return is_dir(Civi
::paths()->getPath($path));
894 * @param null $actualElementValue
898 public static function validContact($value, $actualElementValue = NULL) {
899 if ($actualElementValue) {
900 $value = $actualElementValue;
903 return CRM_Utils_Rule
::positiveInteger($value);
907 * Check the validity of the date (in qf format)
908 * note that only a year is valid, or a mon-year is
909 * also valid in addition to day-mon-year
916 public static function qfDate($date) {
917 $config = CRM_Core_Config
::singleton();
919 $d = CRM_Utils_Array
::value('d', $date);
920 $m = CRM_Utils_Array
::value('M', $date);
921 $y = CRM_Utils_Array
::value('Y', $date);
922 if (isset($date['h']) ||
925 $m = CRM_Utils_Array
::value('M', $date);
928 if (!$d && !$m && !$y) {
944 // if we have day we need mon, and if we have mon we need year
952 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
953 return checkdate($mon, $day, $year);
963 public static function qfKey($key) {
964 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;
968 * Check if the values in the date range are in correct chronological order.
970 * @param array $fields
971 * Fields of the form.
973 * Name of date range field.
977 * Title of the date range to be displayed in the error message.
979 public static function validDateRange($fields, $fieldName, &$errors, $title) {
980 $lowDate = strtotime($fields[$fieldName . '_low']);
981 $highDate = strtotime($fields[$fieldName . '_high']);
983 if ($lowDate > $highDate) {
984 $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $title]);
989 * @param string $key Extension Key to check
992 public static function checkExtensionKeyIsValid($key = NULL) {
993 if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) {
1000 * Validate array recursively checking keys and values.
1002 * @param array $array
1005 protected static function arrayValue($array) {
1006 foreach ($array as $key => $item) {
1007 if (is_array($item)) {
1008 if (!self
::xssString($key) ||
!self
::arrayValue($item)) {
1012 if (!self
::xssString($key) ||
!self
::xssString($item)) {