3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 require_once 'HTML/QuickForm/Rule/Email.php';
21 * Class CRM_Utils_Rule
23 class CRM_Utils_Rule
{
27 * @param int $maxLength
31 public static function title($str, $maxLength = 127) {
34 if (empty($str) ||
strlen($str) > $maxLength) {
38 // Make sure it include valid characters, alpha numeric and underscores
39 if (!preg_match('/^\w[\w\s\'\&\,\$\#\-\.\"\?\!]+$/i', $str)) {
51 public static function longTitle($str) {
52 return self
::title($str, 255);
60 public static function variable($str) {
62 if (empty($str) ||
strlen($str) > 31) {
66 // make sure it includes valid characters, alpha numeric and underscores
67 if (!preg_match('/^[\w]+$/i', $str)) {
75 * Validate that a string is a valid MySQL column name or alias.
81 public static function mysqlColumnNameOrAlias($str) {
87 // Ensure $str conforms to expected format. Not a complete expression of
88 // what MySQL permits; this should permit the formats CiviCRM generates.
90 // * Table name prefix is optional.
91 // * Table & column names & aliases:
92 // * Composed of alphanumeric chars, underscore and hyphens.
93 // * Maximum length of 64 chars.
94 // * Optionally surrounded by backticks, in which case spaces also OK.
95 if (!preg_match('/^((`[-\w ]{1,64}`|[-\w]{1,64})\.)?(`[-\w ]{1,64}`|[-\w]{1,64})$/i', $str)) {
103 * Validate that a string is ASC or DESC.
105 * Empty string should be treated as invalid and ignored => default = ASC.
110 public static function mysqlOrderByDirection($str) {
111 if (!preg_match('/^(asc|desc)$/i', $str)) {
119 * Validate that a string is valid order by clause.
124 public static function mysqlOrderBy($str) {
126 // Using the field function in order by is valid.
127 // Look for a string like field(contribution_status_id,3,4,6).
128 // or field(civicrm_contribution.contribution_status_id,3,4,6)
129 if (preg_match('/field\([a-z_.]+,[0-9,]+\)/', $str, $matches)) {
130 // We have checked these. Remove them as they will fail the next lot.
131 // Our check currently only permits numbers & no back ticks. If we get a
132 // need for strings or backticks we can add.
133 $str = str_replace($matches, '', $str);
136 if (!empty($matches) && empty($str)) {
137 // nothing left to check after the field check.
140 // Making a regex for a comma separated list is quite hard and not readable
141 // at all, so we split and loop over.
142 $parts = explode(',', $str);
143 foreach ($parts as $part) {
144 if (!preg_match('/^((`[\w-]{1,64}`|[\w-]{1,64})\.)*(`[\w-]{1,64}`|[\w-]{1,64})( (asc|desc))?$/i', trim($part))) {
157 public static function qfVariable($str) {
159 //if ( empty( $str ) || strlen( $str ) > 31 ) {
160 if (strlen(trim($str)) == 0 ||
strlen($str) > 31) {
164 // make sure it includes valid characters, alpha numeric and underscores
165 // added (. and ,) option (CRM-1336)
166 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
178 public static function phone($phone) {
180 if (empty($phone) ||
strlen($phone) > 16) {
184 // make sure it includes valid characters, (, \s and numeric
185 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
196 public static function query($query) {
198 if (empty($query) ||
strlen($query) < 3 ||
strlen($query) > 127) {
202 // make sure it includes valid characters, alpha numeric and underscores
203 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
215 public static function url($url) {
217 // If this is required then that should be checked elsewhere - here we are not assuming it is required.
220 if (preg_match('/^\//', $url)) {
221 // allow relative URL's (CRM-15598)
222 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
224 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
232 public static function urlish($url) {
236 $url = Civi
::paths()->getUrl($url, 'absolute');
237 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
245 public static function wikiURL($string) {
246 $items = explode(' ', trim($string), 2);
247 return self
::url($items[0]);
255 public static function domain($domain) {
256 // not perfect, but better than the previous one; see CRM-1502
257 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
265 * @param null $default
269 public static function date($value, $default = NULL) {
270 if (is_string($value) &&
271 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
280 * @param null $default
282 * @return null|string
284 public static function dateTime($value, $default = NULL) {
286 if (is_string($value) &&
287 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
296 * Check the validity of the date (in qf format)
297 * note that only a year is valid, or a mon-year is
298 * also valid in addition to day-mon-year. The date
299 * specified has to be beyond today. (i.e today or later)
302 * @param bool $monthRequired
303 * Check whether month is mandatory.
308 public static function currentDate($date, $monthRequired = TRUE) {
309 $config = CRM_Core_Config
::singleton();
311 $d = $date['d'] ??
NULL;
312 $m = $date['M'] ??
NULL;
313 $y = $date['Y'] ??
NULL;
315 if (!$d && !$m && !$y) {
319 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
320 if (!$m && !empty($date['m'])) {
321 $m = $date['m'] ??
NULL;
336 // if we have day we need mon, and if we have mon we need year
345 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
346 $result = checkdate($mon, $day, $year);
353 // ensure we have month if required
354 if ($monthRequired && !$m) {
358 // now make sure this date is greater that today
359 $currentDate = getdate();
360 if ($year > $currentDate['year']) {
363 elseif ($year < $currentDate['year']) {
368 if ($mon > $currentDate['mon']) {
371 elseif ($mon < $currentDate['mon']) {
377 if ($day > $currentDate['mday']) {
380 elseif ($day < $currentDate['mday']) {
389 * Check the validity of a date or datetime (timestamp)
390 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
392 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
394 * @param string $date
399 public static function mysqlDate($date) {
400 // allow date to be null
405 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
417 public static function integer($value) {
418 if (is_int($value)) {
423 // ensure number passed is always a string numeral
424 if (!is_numeric($value)) {
428 // note that is_int matches only integer type
429 // and not strings which are only integers
430 // hence we do this here
431 if (preg_match('/^\d+$/', $value)) {
436 $negValue = -1 * $value;
437 if (is_int($negValue)) {
450 public static function positiveInteger($value) {
451 if (is_int($value)) {
452 return !($value < 0);
456 // ensure number passed is always a string numeral
457 if (!is_numeric($value)) {
461 return (bool) preg_match('/^\d+$/', $value);
469 public static function commaSeparatedIntegers($value) {
470 foreach (explode(',', $value) as $val) {
471 // Remove any Whitespace around the key.
473 if (!self
::positiveInteger($val)) {
485 public static function numeric($value) {
486 // lets use a php gatekeeper to ensure this is numeric
487 if (!is_numeric($value)) {
491 return (bool) preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value);
495 * Test whether $value is alphanumeric.
497 * Underscores and dashes are also allowed!
499 * This is the type of string you could expect to see in URL parameters
500 * like `?mode=live` vs `?mode=test`. This function exists so that we can be
501 * strict about what we accept for such values, thus mitigating against
502 * potential security issues.
504 * @see \CRM_Utils_RuleTest::alphanumericData
505 * for examples of vales that give TRUE/FALSE here
511 public static function alphanumeric($value) {
512 return (bool) preg_match('/^[a-zA-Z0-9_-]*$/', $value);
521 public static function numberOfDigit($value, $noOfDigit) {
522 return (bool) preg_match('/^\d{' . $noOfDigit . '}$/', $value);
526 * Strict validation of 6-digit hex color notation per html5 <input type="color">
531 public static function color($value) {
532 return (bool) preg_match('/^#([\da-fA-F]{6})$/', $value);
536 * Strip thousand separator from a money string.
538 * Note that this should be done at the form layer. Once we are processing
539 * money at the BAO or processor layer we should be working with something that
540 * is already in a normalised format.
542 * @param string $value
546 public static function cleanMoney($value) {
547 // first remove all white space
548 $value = str_replace([' ', "\t", "\n"], '', $value);
550 $config = CRM_Core_Config
::singleton();
553 $currencySymbols = CRM_Core_PseudoConstant
::get(
554 'CRM_Contribute_DAO_Contribution',
556 'keyColumn' => 'name',
557 'labelColumn' => 'symbol',
560 $value = str_replace($currencySymbols, '', $value);
562 if ($config->monetaryThousandSeparator
) {
563 $mon_thousands_sep = $config->monetaryThousandSeparator
;
566 $mon_thousands_sep = ',';
569 // ugly fix for CRM-6391: do not drop the thousand separator if
570 // it looks like it’s separating decimal part (because a given
571 // value undergoes a second cleanMoney() call, for example)
572 // CRM-15835 - in case the amount/value contains 0 after decimal
573 // eg 150.5 the following if condition will pass
574 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
575 $value = str_replace($mon_thousands_sep, '', $value);
578 if ($config->monetaryDecimalPoint
) {
579 $mon_decimal_point = $config->monetaryDecimalPoint
;
582 $mon_decimal_point = '.';
584 $value = str_replace($mon_decimal_point, '.', $value);
594 public static function money($value) {
595 $value = self
::cleanMoney($value);
597 if (self
::integer($value)) {
601 // Allow values such as -0, 1.024555, -.1
602 // We need to support multiple decimal places here, not just the number allowed by locale
603 // otherwise tax calculations break when you want the inclusive amount to be a round number (eg. £10 inc. VAT requires 8.333333333 here).
604 return (bool) preg_match('/(^-?\d+\.?\d*$)|(^-?\.\d+$)/', $value);
609 * @param int $maxLength
613 public static function string($value, $maxLength = 0) {
614 if (is_string($value) &&
615 ($maxLength === 0 ||
strlen($value) <= $maxLength)
627 public static function boolean($value) {
629 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
638 public static function email($value) {
639 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
647 public static function emailList($list) {
648 $emails = explode(',', $list);
649 foreach ($emails as $email) {
650 $email = trim($email);
651 if (!self
::email($email)) {
659 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
660 * if u disregard the first 0, 4 (thanx excel!)
661 * FIXME: we need to figure out how to localize such rules
666 public static function postalCode($value) {
667 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
674 * See how file rules are written in HTML/QuickForm/file.php
675 * Checks to make sure the uploaded file is ascii
677 * @param string $elementValue
680 * True if file has been uploaded, false otherwise
682 public static function asciiFile($elementValue) {
683 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
684 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
686 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
692 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
694 * @param array $elementValue
697 * Whether file has been uploaded properly and is now in UTF-8.
699 public static function utf8File($elementValue) {
702 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
703 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
706 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
708 // if it's a file, but not UTF-8, let's try and recode it
709 // and then make sure it's an UTF-8 file in the end
711 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
713 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
721 * See how file rules are written in HTML/QuickForm/file.php
722 * Checks to make sure the uploaded file is html
724 * @param array $elementValue
727 * True if file has been uploaded, false otherwise
729 public static function htmlFile($elementValue) {
730 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
731 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
733 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
739 * Check if there is a record with the same name in the db.
741 * @param string $value
742 * The value of the field we are checking.
743 * @param array $options
744 * The daoName, fieldName (optional) and DomainID (optional).
747 * true if object exists
749 public static function objectExists($value, $options) {
751 if (isset($options[2])) {
755 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));
764 public static function optionExists($value, $options) {
765 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));
774 public static function creditCardNumber($value, $type) {
775 return Validate_Finance_CreditCard
::number($value, $type);
784 public static function cvv($value, $type) {
785 return Validate_Finance_CreditCard
::cvv($value, $type);
793 public static function currencyCode($value) {
794 static $currencyCodes = NULL;
795 if (!$currencyCodes) {
796 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
798 if (in_array($value, $currencyCodes)) {
805 * Validate json string for xss
807 * @param string $value
810 * False if invalid, true if valid / safe.
812 public static function json($value) {
813 $array = json_decode($value, TRUE);
814 if (!$array ||
!is_array($array)) {
817 return self
::arrayValue($array);
825 public static function fileExists($path) {
826 return file_exists($path);
830 * Determine whether the value contains a valid reference to a directory.
832 * Paths stored in the setting system may be absolute -- or may be
833 * relative to the default data directory.
835 * @param string $path
838 public static function settingPath($path) {
839 return is_dir(Civi
::paths()->getPath($path));
844 * @param null $actualElementValue
848 public static function validContact($value, $actualElementValue = NULL) {
849 if ($actualElementValue) {
850 $value = $actualElementValue;
853 return CRM_Utils_Rule
::positiveInteger($value);
857 * Check the validity of the date (in qf format)
858 * note that only a year is valid, or a mon-year is
859 * also valid in addition to day-mon-year
866 public static function qfDate($date) {
867 $config = CRM_Core_Config
::singleton();
869 $d = $date['d'] ??
NULL;
870 $m = $date['M'] ??
NULL;
871 $y = $date['Y'] ??
NULL;
872 if (isset($date['h']) ||
875 $m = $date['M'] ??
NULL;
878 if (!$d && !$m && !$y) {
894 // if we have day we need mon, and if we have mon we need year
902 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
903 return checkdate($mon, $day, $year);
913 public static function qfKey($key) {
914 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;
918 * Check if the values in the date range are in correct chronological order.
920 * @param array $fields
921 * Fields of the form.
923 * Name of date range field.
927 * Title of the date range to be displayed in the error message.
929 public static function validDateRange($fields, $fieldName, &$errors, $title) {
930 $lowDate = strtotime($fields[$fieldName . '_low']);
931 $highDate = strtotime($fields[$fieldName . '_high']);
933 if ($lowDate > $highDate) {
934 $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $title]);
939 * @param string $key Extension Key to check
942 public static function checkExtensionKeyIsValid($key = NULL) {
943 if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) {
950 * Validate array recursively checking keys and values.
952 * @param array $array
955 protected static function arrayValue($array) {
956 foreach ($array as $key => $item) {
957 if (is_array($item)) {
958 if (!self
::arrayValue($item)) {