3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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) {
232 if (preg_match('/^\//', $url)) {
233 // allow relative URL's (CRM-15598)
234 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
236 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
244 public static function urlish($url) {
248 $url = Civi
::paths()->getUrl($url, 'absolute');
249 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
257 public static function wikiURL($string) {
258 $items = explode(' ', trim($string), 2);
259 return self
::url($items[0]);
267 public static function domain($domain) {
268 // not perfect, but better than the previous one; see CRM-1502
269 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
277 * @param null $default
281 public static function date($value, $default = NULL) {
282 if (is_string($value) &&
283 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
292 * @param null $default
294 * @return null|string
296 public static function dateTime($value, $default = NULL) {
298 if (is_string($value) &&
299 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
308 * Check the validity of the date (in qf format)
309 * note that only a year is valid, or a mon-year is
310 * also valid in addition to day-mon-year. The date
311 * specified has to be beyond today. (i.e today or later)
314 * @param bool $monthRequired
315 * Check whether month is mandatory.
320 public static function currentDate($date, $monthRequired = TRUE) {
321 $config = CRM_Core_Config
::singleton();
323 $d = CRM_Utils_Array
::value('d', $date);
324 $m = CRM_Utils_Array
::value('M', $date);
325 $y = CRM_Utils_Array
::value('Y', $date);
327 if (!$d && !$m && !$y) {
331 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
332 if (!$m && !empty($date['m'])) {
333 $m = CRM_Utils_Array
::value('m', $date);
348 // if we have day we need mon, and if we have mon we need year
357 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
358 $result = checkdate($mon, $day, $year);
365 // ensure we have month if required
366 if ($monthRequired && !$m) {
370 // now make sure this date is greater that today
371 $currentDate = getdate();
372 if ($year > $currentDate['year']) {
375 elseif ($year < $currentDate['year']) {
380 if ($mon > $currentDate['mon']) {
383 elseif ($mon < $currentDate['mon']) {
389 if ($day > $currentDate['mday']) {
392 elseif ($day < $currentDate['mday']) {
401 * Check the validity of a date or datetime (timestamp)
402 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
404 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
406 * @param string $date
411 public static function mysqlDate($date) {
412 // allow date to be null
417 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
429 public static function integer($value) {
430 if (is_int($value)) {
435 // ensure number passed is always a string numeral
436 if (!is_numeric($value)) {
440 // note that is_int matches only integer type
441 // and not strings which are only integers
442 // hence we do this here
443 if (preg_match('/^\d+$/', $value)) {
448 $negValue = -1 * $value;
449 if (is_int($negValue)) {
462 public static function positiveInteger($value) {
463 if (is_int($value)) {
464 return ($value < 0) ?
FALSE : TRUE;
468 // ensure number passed is always a string numeral
469 if (!is_numeric($value)) {
473 if (preg_match('/^\d+$/', $value)) {
485 public static function commaSeparatedIntegers($value) {
486 foreach (explode(',', $value) as $val) {
487 if (!self
::positiveInteger($val)) {
499 public static function numeric($value) {
500 // lets use a php gatekeeper to ensure this is numeric
501 if (!is_numeric($value)) {
505 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ?
TRUE : FALSE;
514 public static function numberOfDigit($value, $noOfDigit) {
515 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ?
TRUE : FALSE;
523 public static function cleanMoney($value) {
524 // first remove all white space
525 $value = str_replace(array(' ', "\t", "\n"), '', $value);
527 $config = CRM_Core_Config
::singleton();
530 $currencySymbols = CRM_Core_PseudoConstant
::get(
531 'CRM_Contribute_DAO_Contribution',
533 'keyColumn' => 'name',
534 'labelColumn' => 'symbol',
537 $value = str_replace($currencySymbols, '', $value);
539 if ($config->monetaryThousandSeparator
) {
540 $mon_thousands_sep = $config->monetaryThousandSeparator
;
543 $mon_thousands_sep = ',';
546 // ugly fix for CRM-6391: do not drop the thousand separator if
547 // it looks like it’s separating decimal part (because a given
548 // value undergoes a second cleanMoney() call, for example)
549 // CRM-15835 - in case the amount/value contains 0 after decimal
550 // eg 150.5 the following if condition will pass
551 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
552 $value = str_replace($mon_thousands_sep, '', $value);
555 if ($config->monetaryDecimalPoint
) {
556 $mon_decimal_point = $config->monetaryDecimalPoint
;
559 $mon_decimal_point = '.';
561 $value = str_replace($mon_decimal_point, '.', $value);
571 public static function money($value) {
572 $config = CRM_Core_Config
::singleton();
574 // only edge case when we have a decimal point in the input money
575 // field and not defined in the decimal Point in config settings
576 if ($config->monetaryDecimalPoint
&&
577 $config->monetaryDecimalPoint
!= '.' &&
578 // CRM-7122 also check for Thousands Separator in config settings
579 $config->monetaryThousandSeparator
!= '.' &&
580 substr_count($value, '.')
585 $value = self
::cleanMoney($value);
587 if (self
::integer($value)) {
591 // Allow values such as -0, 1.024555, -.1
592 // We need to support multiple decimal places here, not just the number allowed by locale
593 // otherwise tax calculations break when you want the inclusive amount to be a round number (eg. £10 inc. VAT requires 8.333333333 here).
594 return preg_match('/(^-?\d+\.?\d*$)|(^-?\.\d+$)/', $value) ?
TRUE : FALSE;
599 * @param int $maxLength
603 public static function string($value, $maxLength = 0) {
604 if (is_string($value) &&
605 ($maxLength === 0 ||
strlen($value) <= $maxLength)
617 public static function boolean($value) {
619 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
628 public static function email($value) {
629 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
637 public static function emailList($list) {
638 $emails = explode(',', $list);
639 foreach ($emails as $email) {
640 $email = trim($email);
641 if (!self
::email($email)) {
649 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
650 * if u disregard the first 0, 4 (thanx excel!)
651 * FIXME: we need to figure out how to localize such rules
656 public static function postalCode($value) {
657 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
664 * See how file rules are written in HTML/QuickForm/file.php
665 * Checks to make sure the uploaded file is ascii
667 * @param string $elementValue
670 * True if file has been uploaded, false otherwise
672 public static function asciiFile($elementValue) {
673 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
674 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
676 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
682 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
684 * @param array $elementValue
687 * Whether file has been uploaded properly and is now in UTF-8.
689 public static function utf8File($elementValue) {
692 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
693 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
696 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
698 // if it's a file, but not UTF-8, let's try and recode it
699 // and then make sure it's an UTF-8 file in the end
701 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
703 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
711 * See how file rules are written in HTML/QuickForm/file.php
712 * Checks to make sure the uploaded file is html
714 * @param array $elementValue
717 * True if file has been uploaded, false otherwise
719 public static function htmlFile($elementValue) {
720 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
721 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
723 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
729 * Check if there is a record with the same name in the db.
731 * @param string $value
732 * The value of the field we are checking.
733 * @param array $options
734 * The daoName, fieldName (optional) and DomainID (optional).
737 * true if object exists
739 public static function objectExists($value, $options) {
741 if (isset($options[2])) {
745 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));
754 public static function optionExists($value, $options) {
755 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));
764 public static function creditCardNumber($value, $type) {
765 return Validate_Finance_CreditCard
::number($value, $type);
774 public static function cvv($value, $type) {
775 return Validate_Finance_CreditCard
::cvv($value, $type);
783 public static function currencyCode($value) {
784 static $currencyCodes = NULL;
785 if (!$currencyCodes) {
786 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
788 if (in_array($value, $currencyCodes)) {
799 public static function xssString($value) {
800 if (is_string($value)) {
801 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
815 public static function fileExists($path) {
816 return file_exists($path);
820 * Determine whether the value contains a valid reference to a directory.
822 * Paths stored in the setting system may be absolute -- or may be
823 * relative to the default data directory.
825 * @param string $path
828 public static function settingPath($path) {
829 return is_dir(Civi
::paths()->getPath($path));
834 * @param null $actualElementValue
838 public static function validContact($value, $actualElementValue = NULL) {
839 if ($actualElementValue) {
840 $value = $actualElementValue;
843 return CRM_Utils_Rule
::positiveInteger($value);
847 * Check the validity of the date (in qf format)
848 * note that only a year is valid, or a mon-year is
849 * also valid in addition to day-mon-year
856 public static function qfDate($date) {
857 $config = CRM_Core_Config
::singleton();
859 $d = CRM_Utils_Array
::value('d', $date);
860 $m = CRM_Utils_Array
::value('M', $date);
861 $y = CRM_Utils_Array
::value('Y', $date);
862 if (isset($date['h']) ||
865 $m = CRM_Utils_Array
::value('M', $date);
868 if (!$d && !$m && !$y) {
884 // if we have day we need mon, and if we have mon we need year
892 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
893 return checkdate($mon, $day, $year);
903 public static function qfKey($key) {
904 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;
908 * Check if the values in the date range are in correct chronological order.
910 * @param array $fields
911 * Fields of the form.
913 * Name of date range field.
917 * Title of the date range to be displayed in the error message.
919 public static function validDateRange($fields, $fieldName, &$errors, $title) {
920 $lowDate = strtotime($fields[$fieldName . '_low']);
921 $highDate = strtotime($fields[$fieldName . '_high']);
923 if ($lowDate > $highDate) {
924 $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', array(1 => $title));
929 * @param string $key Extension Key to check
932 public static function checkExtesnionKeyIsValid($key = NULL) {
933 if (!empty($key) && !preg_match('/^[0-9a-zA-Z._-]+$/', $key)) {