3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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 the string contains only valid characters:
104 // For column names: alphanumeric and underscores
105 // For aliases: backticks, alphanumeric hyphens and underscores.
106 if (!preg_match('/^((`[\w-]{1,64}`|[\w-]{1,64})\.)?(`[\w-]{1,64}`|[\w-]{1,64})$/i', $str)) {
114 * Validate that a string is ASC or DESC.
116 * Empty string should be treated as invalid and ignored => default = ASC.
121 public static function mysqlOrderByDirection($str) {
122 if (!preg_match('/^(asc|desc)$/i', $str)) {
130 * Validate that a string is valid order by clause.
135 public static function mysqlOrderBy($str) {
136 // Making a regex for a comma separated list is quite hard and not readable
137 // at all, so we split and loop over.
138 $parts = explode(',', $str);
139 foreach ($parts as $part) {
140 if (!preg_match('/^((`[\w-]{1,64}`|[\w-]{1,64})\.)?(`[\w-]{1,64}`|[\w-]{1,64})( (asc|desc))?$/i', trim($part))) {
153 public static function qfVariable($str) {
155 //if ( empty( $str ) || strlen( $str ) > 31 ) {
156 if (strlen(trim($str)) == 0 ||
strlen($str) > 31) {
160 // make sure it includes valid characters, alpha numeric and underscores
161 // added (. and ,) option (CRM-1336)
162 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
174 public static function phone($phone) {
176 if (empty($phone) ||
strlen($phone) > 16) {
180 // make sure it includes valid characters, (, \s and numeric
181 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
192 public static function query($query) {
194 if (empty($query) ||
strlen($query) < 3 ||
strlen($query) > 127) {
198 // make sure it includes valid characters, alpha numeric and underscores
199 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
211 public static function url($url) {
212 if (preg_match('/^\//', $url)) {
213 // allow relative URL's (CRM-15598)
214 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
216 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
224 public static function urlish($url) {
228 $url = Civi
::paths()->getUrl($url, 'absolute');
229 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
237 public static function wikiURL($string) {
238 $items = explode(' ', trim($string), 2);
239 return self
::url($items[0]);
247 public static function domain($domain) {
248 // not perfect, but better than the previous one; see CRM-1502
249 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
257 * @param null $default
261 public static function date($value, $default = NULL) {
262 if (is_string($value) &&
263 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
272 * @param null $default
274 * @return null|string
276 public static function dateTime($value, $default = NULL) {
278 if (is_string($value) &&
279 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
288 * Check the validity of the date (in qf format)
289 * note that only a year is valid, or a mon-year is
290 * also valid in addition to day-mon-year. The date
291 * specified has to be beyond today. (i.e today or later)
294 * @param bool $monthRequired
295 * Check whether month is mandatory.
300 public static function currentDate($date, $monthRequired = TRUE) {
301 $config = CRM_Core_Config
::singleton();
303 $d = CRM_Utils_Array
::value('d', $date);
304 $m = CRM_Utils_Array
::value('M', $date);
305 $y = CRM_Utils_Array
::value('Y', $date);
307 if (!$d && !$m && !$y) {
311 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
312 if (!$m && !empty($date['m'])) {
313 $m = CRM_Utils_Array
::value('m', $date);
328 // if we have day we need mon, and if we have mon we need year
337 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
338 $result = checkdate($mon, $day, $year);
345 // ensure we have month if required
346 if ($monthRequired && !$m) {
350 // now make sure this date is greater that today
351 $currentDate = getdate();
352 if ($year > $currentDate['year']) {
355 elseif ($year < $currentDate['year']) {
360 if ($mon > $currentDate['mon']) {
363 elseif ($mon < $currentDate['mon']) {
369 if ($day > $currentDate['mday']) {
372 elseif ($day < $currentDate['mday']) {
381 * Check the validity of a date or datetime (timestamp)
382 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
384 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
386 * @param string $date
391 public static function mysqlDate($date) {
392 // allow date to be null
397 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
409 public static function integer($value) {
410 if (is_int($value)) {
415 // ensure number passed is always a string numeral
416 if (!is_numeric($value)) {
420 // note that is_int matches only integer type
421 // and not strings which are only integers
422 // hence we do this here
423 if (preg_match('/^\d+$/', $value)) {
428 $negValue = -1 * $value;
429 if (is_int($negValue)) {
442 public static function positiveInteger($value) {
443 if (is_int($value)) {
444 return ($value < 0) ?
FALSE : TRUE;
448 // ensure number passed is always a string numeral
449 if (!is_numeric($value)) {
453 if (preg_match('/^\d+$/', $value)) {
465 public static function numeric($value) {
466 // lets use a php gatekeeper to ensure this is numeric
467 if (!is_numeric($value)) {
471 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ?
TRUE : FALSE;
480 public static function numberOfDigit($value, $noOfDigit) {
481 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ?
TRUE : FALSE;
489 public static function cleanMoney($value) {
490 // first remove all white space
491 $value = str_replace(array(' ', "\t", "\n"), '', $value);
493 $config = CRM_Core_Config
::singleton();
496 $currencySymbols = CRM_Core_PseudoConstant
::get(
497 'CRM_Contribute_DAO_Contribution',
499 'keyColumn' => 'name',
500 'labelColumn' => 'symbol',
503 $value = str_replace($currencySymbols, '', $value);
505 if ($config->monetaryThousandSeparator
) {
506 $mon_thousands_sep = $config->monetaryThousandSeparator
;
509 $mon_thousands_sep = ',';
512 // ugly fix for CRM-6391: do not drop the thousand separator if
513 // it looks like it’s separating decimal part (because a given
514 // value undergoes a second cleanMoney() call, for example)
515 // CRM-15835 - in case the amount/value contains 0 after decimal
516 // eg 150.5 the following if condition will pass
517 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
518 $value = str_replace($mon_thousands_sep, '', $value);
521 if ($config->monetaryDecimalPoint
) {
522 $mon_decimal_point = $config->monetaryDecimalPoint
;
525 $mon_decimal_point = '.';
527 $value = str_replace($mon_decimal_point, '.', $value);
537 public static function money($value) {
538 $config = CRM_Core_Config
::singleton();
540 // only edge case when we have a decimal point in the input money
541 // field and not defined in the decimal Point in config settings
542 if ($config->monetaryDecimalPoint
&&
543 $config->monetaryDecimalPoint
!= '.' &&
544 // CRM-7122 also check for Thousands Separator in config settings
545 $config->monetaryThousandSeparator
!= '.' &&
546 substr_count($value, '.')
551 $value = self
::cleanMoney($value);
553 if (self
::integer($value)) {
557 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ?
TRUE : FALSE;
562 * @param int $maxLength
566 public static function string($value, $maxLength = 0) {
567 if (is_string($value) &&
568 ($maxLength === 0 ||
strlen($value) <= $maxLength)
580 public static function boolean($value) {
582 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
591 public static function email($value) {
592 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
600 public static function emailList($list) {
601 $emails = explode(',', $list);
602 foreach ($emails as $email) {
603 $email = trim($email);
604 if (!self
::email($email)) {
612 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
613 * if u disregard the first 0, 4 (thanx excel!)
614 * FIXME: we need to figure out how to localize such rules
619 public static function postalCode($value) {
620 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
627 * See how file rules are written in HTML/QuickForm/file.php
628 * Checks to make sure the uploaded file is ascii
630 * @param string $elementValue
633 * True if file has been uploaded, false otherwise
635 public static function asciiFile($elementValue) {
636 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
637 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
639 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
645 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
647 * @param array $elementValue
650 * Whether file has been uploaded properly and is now in UTF-8.
652 public static function utf8File($elementValue) {
655 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
656 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
659 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
661 // if it's a file, but not UTF-8, let's try and recode it
662 // and then make sure it's an UTF-8 file in the end
664 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
666 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
674 * See how file rules are written in HTML/QuickForm/file.php
675 * Checks to make sure the uploaded file is html
677 * @param array $elementValue
680 * True if file has been uploaded, false otherwise
682 public static function htmlFile($elementValue) {
683 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
684 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
686 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
692 * Check if there is a record with the same name in the db.
694 * @param string $value
695 * The value of the field we are checking.
696 * @param array $options
697 * The daoName, fieldName (optional) and DomainID (optional).
700 * true if object exists
702 public static function objectExists($value, $options) {
704 if (isset($options[2])) {
708 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));
717 public static function optionExists($value, $options) {
718 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));
727 public static function creditCardNumber($value, $type) {
728 return Validate_Finance_CreditCard
::number($value, $type);
737 public static function cvv($value, $type) {
738 return Validate_Finance_CreditCard
::cvv($value, $type);
746 public static function currencyCode($value) {
747 static $currencyCodes = NULL;
748 if (!$currencyCodes) {
749 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
751 if (in_array($value, $currencyCodes)) {
762 public static function xssString($value) {
763 if (is_string($value)) {
764 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
778 public static function fileExists($path) {
779 return file_exists($path);
783 * Determine whether the value contains a valid reference to a directory.
785 * Paths stored in the setting system may be absolute -- or may be
786 * relative to the default data directory.
788 * @param string $path
791 public static function settingPath($path) {
792 return is_dir(Civi
::paths()->getPath($path));
797 * @param null $actualElementValue
801 public static function validContact($value, $actualElementValue = NULL) {
802 if ($actualElementValue) {
803 $value = $actualElementValue;
806 return CRM_Utils_Rule
::positiveInteger($value);
810 * Check the validity of the date (in qf format)
811 * note that only a year is valid, or a mon-year is
812 * also valid in addition to day-mon-year
819 public static function qfDate($date) {
820 $config = CRM_Core_Config
::singleton();
822 $d = CRM_Utils_Array
::value('d', $date);
823 $m = CRM_Utils_Array
::value('M', $date);
824 $y = CRM_Utils_Array
::value('Y', $date);
825 if (isset($date['h']) ||
828 $m = CRM_Utils_Array
::value('M', $date);
831 if (!$d && !$m && !$y) {
847 // if we have day we need mon, and if we have mon we need year
855 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
856 return checkdate($mon, $day, $year);
866 public static function qfKey($key) {
867 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;
871 * Check if the values in the date range are in correct chronological order.
873 * @param array $fields
874 * Fields of the form.
876 * Name of date range field.
880 * Title of the date range to be displayed in the error message.
882 public static function validDateRange($fields, $fieldName, &$errors, $title) {
883 $lowDate = strtotime($fields[$fieldName . '_low']);
884 $highDate = strtotime($fields[$fieldName . '_high']);
886 if ($lowDate > $highDate) {
887 $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', array(1 => $title));