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
{
26 * @param string|null $str
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)) {
47 * @param string|null $str
51 public static function longTitle($str) {
52 return self
::title($str, 255);
56 * @param string|null $str
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.
77 * @param string|null $str
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)) {
174 * @param string|null $phone
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)) {
192 * @param string|null $query
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)) {
211 * @param string|null $url
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 // Convert URLs with Unicode to ASCII
225 if (strlen($url) != strlen(utf8_decode($url))) {
226 $url = self
::idnToAsci($url);
228 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
232 * @param string|null $url
236 public static function urlish($url) {
240 $url = Civi
::paths()->getUrl($url, 'absolute');
241 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
245 * @param string $string
249 public static function wikiURL($string) {
250 $items = explode(' ', trim($string), 2);
251 return self
::url($items[0]);
255 * @param string $domain
259 public static function domain($domain) {
260 // not perfect, but better than the previous one; see CRM-1502
261 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
268 * @param string $value
269 * @param string|null $default
271 * @return string|null
273 public static function date($value, $default = NULL) {
274 if (is_string($value) &&
275 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
283 * @param string $value
284 * @param string|null $default
286 * @return string|null
288 public static function dateTime($value, $default = NULL) {
290 if (is_string($value) &&
291 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
300 * Check the validity of the date (in qf format)
301 * note that only a year is valid, or a mon-year is
302 * also valid in addition to day-mon-year. The date
303 * specified has to be beyond today. (i.e today or later)
306 * @param bool $monthRequired
307 * Check whether month is mandatory.
312 public static function currentDate($date, $monthRequired = TRUE) {
313 $config = CRM_Core_Config
::singleton();
315 $d = $date['d'] ??
NULL;
316 $m = $date['M'] ??
NULL;
317 $y = $date['Y'] ??
NULL;
319 if (!$d && !$m && !$y) {
323 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
324 if (!$m && !empty($date['m'])) {
325 $m = $date['m'] ??
NULL;
340 // if we have day we need mon, and if we have mon we need year
349 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
350 $result = checkdate($mon, $day, $year);
357 // ensure we have month if required
358 if ($monthRequired && !$m) {
362 // now make sure this date is greater that today
363 $currentDate = getdate();
364 if ($year > $currentDate['year']) {
367 elseif ($year < $currentDate['year']) {
372 if ($mon > $currentDate['mon']) {
375 elseif ($mon < $currentDate['mon']) {
381 if ($day > $currentDate['mday']) {
384 elseif ($day < $currentDate['mday']) {
393 * Check the validity of a date or datetime (timestamp)
394 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
396 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
398 * @param string $date
403 public static function mysqlDate($date) {
404 // allow date to be null
409 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
417 * @param mixed $value
421 public static function integer($value) {
422 if (is_int($value)) {
427 // ensure number passed is always a string numeral
428 if (!is_numeric($value)) {
432 // note that is_int matches only integer type
433 // and not strings which are only integers
434 // hence we do this here
435 if (preg_match('/^\d+$/', $value)) {
440 $negValue = -1 * $value;
441 if (is_int($negValue)) {
450 * @param mixed $value
454 public static function positiveInteger($value) {
455 if (is_int($value)) {
456 return !($value < 0);
460 // ensure number passed is always a string numeral
461 if (!is_numeric($value)) {
465 return (bool) preg_match('/^\d+$/', $value);
469 * @param mixed $value
473 public static function commaSeparatedIntegers($value) {
474 foreach (explode(',', $value) as $val) {
475 // Remove any Whitespace around the key.
477 if (!self
::positiveInteger($val)) {
485 * @param mixed $value
489 public static function numeric($value) {
490 // lets use a php gatekeeper to ensure this is numeric
491 if (!is_numeric($value)) {
495 return (bool) preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value);
499 * Test whether $value is alphanumeric.
501 * Underscores and dashes are also allowed!
503 * This is the type of string you could expect to see in URL parameters
504 * like `?mode=live` vs `?mode=test`. This function exists so that we can be
505 * strict about what we accept for such values, thus mitigating against
506 * potential security issues.
508 * @see \CRM_Utils_RuleTest::alphanumericData
509 * for examples of vales that give TRUE/FALSE here
511 * @param string $value
515 public static function alphanumeric($value) {
516 return (bool) preg_match('/^[a-zA-Z0-9_-]*$/', $value);
520 * @param string $value
521 * @param int $noOfDigit
525 public static function numberOfDigit($value, $noOfDigit) {
526 return (bool) preg_match('/^\d{' . $noOfDigit . '}$/', $value);
530 * Strict validation of 6-digit hex color notation per html5 <input type="color">
532 * @param string $value
535 public static function color($value) {
536 return (bool) preg_match('/^#([\da-fA-F]{6})$/', $value);
540 * Strip thousand separator from a money string.
542 * Note that this should be done at the form layer. Once we are processing
543 * money at the BAO or processor layer we should be working with something that
544 * is already in a normalised format.
546 * @param string $value
550 public static function cleanMoney($value) {
551 // first remove all white space
552 $value = str_replace([' ', "\t", "\n"], '', $value);
554 $config = CRM_Core_Config
::singleton();
557 $currencySymbols = CRM_Core_PseudoConstant
::get(
558 'CRM_Contribute_DAO_Contribution',
560 'keyColumn' => 'name',
561 'labelColumn' => 'symbol',
564 $value = str_replace($currencySymbols, '', $value);
566 if ($config->monetaryThousandSeparator
) {
567 $mon_thousands_sep = $config->monetaryThousandSeparator
;
570 $mon_thousands_sep = ',';
573 // ugly fix for CRM-6391: do not drop the thousand separator if
574 // it looks like it’s separating decimal part (because a given
575 // value undergoes a second cleanMoney() call, for example)
576 // CRM-15835 - in case the amount/value contains 0 after decimal
577 // eg 150.5 the following if condition will pass
578 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
579 $value = str_replace($mon_thousands_sep, '', $value);
582 if ($config->monetaryDecimalPoint
) {
583 $mon_decimal_point = $config->monetaryDecimalPoint
;
586 $mon_decimal_point = '.';
588 $value = str_replace($mon_decimal_point, '.', $value);
594 * @param string $value
595 * @param bool $checkSeparatorOrder
596 * Should the order of the separators be checked. ie if the thousand
597 * separator is , then it should never be after the decimal separator .
598 * so 1.300,23 would be invalid in that case. Honestly I'm amazed this
599 * check wasn't being done but in the interest of caution adding as opt in.
600 * Note clean money would convert this to 1.30023....
604 public static function money($value, $checkSeparatorOrder = FALSE) {
605 // We can't rely on only one var being passed so can't type-hint to a bool.
606 if ($checkSeparatorOrder === TRUE) {
607 $thousandSeparatorPosition = strpos((string) $value, \Civi
::settings()->get('monetaryThousandSeparator'));
608 $decimalSeparatorPosition = strpos((string) $value, \Civi
::settings()->get('monetaryDecimalPoint'));
609 if ($thousandSeparatorPosition && $decimalSeparatorPosition && $thousandSeparatorPosition > $decimalSeparatorPosition) {
613 $value = self
::cleanMoney($value);
615 if (self
::integer($value)) {
619 // Allow values such as -0, 1.024555, -.1
620 // We need to support multiple decimal places here, not just the number allowed by locale
621 // otherwise tax calculations break when you want the inclusive amount to be a round number (eg. £10 inc. VAT requires 8.333333333 here).
622 return (bool) preg_match('/(^-?\d+\.?\d*$)|(^-?\.\d+$)/', $value);
626 * @param mixed $value
627 * @param int $maxLength
631 public static function string($value, $maxLength = 0) {
632 if (is_string($value) &&
633 ($maxLength === 0 ||
strlen($value) <= $maxLength)
641 * @param bool|string $value
645 public static function boolean($value) {
646 if ($value === TRUE ||
$value === FALSE) {
649 // This is intentionally not using === comparison - but will fail on FALSE.
651 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
656 * @param mixed $value
660 public static function email($value): bool {
661 if (function_exists('idn_to_ascii')) {
662 $parts = explode('@', $value);
663 foreach ($parts as &$part) {
664 // if the function returns FALSE then let filter_var have at it.
665 $part = self
::idnToAsci($part) ?
: $part;
666 if ($part === 'localhost') {
667 // if we are in a dev environment add .com to trick it into accepting localhost.
668 // this is a bit best-effort - ie we don't really care that it's in a bigger if.
672 $value = implode('@', $parts);
674 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
678 * Convert domain string to ascii.
680 * See https://lab.civicrm.org/dev/core/-/issues/2769
681 * and also discussion over in guzzle land
682 * https://github.com/guzzle/guzzle/pull/2454
684 * @param string $string
686 * @return string|false
688 private static function idnToAsci(string $string) {
689 if (!\
extension_loaded('intl')) {
692 if (defined('INTL_IDNA_VARIANT_UTS46')) {
693 return idn_to_ascii($string, 0, INTL_IDNA_VARIANT_UTS46
);
695 return idn_to_ascii($string);
699 * @param string $list
703 public static function emailList($list) {
704 $emails = explode(',', $list);
705 foreach ($emails as $email) {
706 $email = trim($email);
707 if (!self
::email($email)) {
715 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
716 * if u disregard the first 0, 4 (thanx excel!)
717 * FIXME: we need to figure out how to localize such rules
718 * @param string $value
722 public static function postalCode($value) {
723 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
730 * See how file rules are written in HTML/QuickForm/file.php
731 * Checks to make sure the uploaded file is ascii
733 * @param string $elementValue
736 * True if file has been uploaded, false otherwise
738 public static function asciiFile($elementValue) {
739 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
740 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
742 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
748 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
750 * @param array $elementValue
753 * Whether file has been uploaded properly and is now in UTF-8.
755 public static function utf8File($elementValue) {
758 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
759 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
762 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
764 // if it's a file, but not UTF-8, let's try and recode it
765 // and then make sure it's an UTF-8 file in the end
767 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
769 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
777 * Check if there is a record with the same name in the db.
779 * @param string $value
780 * The value of the field we are checking.
781 * @param array $options
782 * The daoName, fieldName (optional) and DomainID (optional).
785 * true if object exists
787 public static function objectExists($value, $options) {
789 if (isset($options[2])) {
793 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));
802 public static function optionExists($value, $options) {
803 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));
807 * @param string $value
808 * @param string $type
812 public static function creditCardNumber($value, $type) {
813 return Validate_Finance_CreditCard
::number($value, $type);
817 * @param string $value
818 * @param string $type
822 public static function cvv($value, $type) {
823 return Validate_Finance_CreditCard
::cvv($value, $type);
827 * @param mixed $value
831 public static function currencyCode($value) {
832 static $currencyCodes = NULL;
833 if (!$currencyCodes) {
834 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
836 if (in_array($value, $currencyCodes)) {
843 * Validate json string for xss
845 * @param string $value
848 * False if invalid, true if valid / safe.
850 public static function json($value) {
851 $array = json_decode($value, TRUE);
852 if (!$array ||
!is_array($array)) {
855 return self
::arrayValue($array);
859 * @param string $path
863 public static function fileExists($path) {
864 return file_exists($path);
868 * Determine whether the value contains a valid reference to a directory.
870 * Paths stored in the setting system may be absolute -- or may be
871 * relative to the default data directory.
873 * @param string $path
876 public static function settingPath($path) {
877 return is_dir(Civi
::paths()->getPath($path));
881 * @param mixed $value
882 * @param mixed $actualElementValue
886 public static function validContact($value, $actualElementValue = NULL) {
887 if ($actualElementValue) {
888 $value = $actualElementValue;
891 return CRM_Utils_Rule
::positiveInteger($value);
895 * Check the validity of the date (in qf format)
896 * note that only a year is valid, or a mon-year is
897 * also valid in addition to day-mon-year
904 public static function qfDate($date) {
905 $config = CRM_Core_Config
::singleton();
907 $d = $date['d'] ??
NULL;
908 $m = $date['M'] ??
NULL;
909 $y = $date['Y'] ??
NULL;
910 if (isset($date['h']) ||
913 $m = $date['M'] ??
NULL;
916 if (!$d && !$m && !$y) {
932 // if we have day we need mon, and if we have mon we need year
940 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
941 return checkdate($mon, $day, $year);
951 public static function qfKey($key) {
952 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;
956 * Check if the values in the date range are in correct chronological order.
958 * @param array $fields
959 * Fields of the form.
961 * Name of date range field.
965 * Title of the date range to be displayed in the error message.
967 public static function validDateRange($fields, $fieldName, &$errors, $title) {
968 $lowDate = strtotime($fields[$fieldName . '_low']);
969 $highDate = strtotime($fields[$fieldName . '_high']);
971 if ($lowDate > $highDate) {
972 $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $title]);
977 * @param string $key Extension Key to check
980 public static function checkExtensionKeyIsValid($key = NULL) {
981 if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) {
988 * Validate array recursively checking keys and values.
990 * @param array $array
993 protected static function arrayValue($array) {
994 foreach ($array as $key => $item) {
995 if (is_array($item)) {
996 if (!self
::arrayValue($item)) {