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)) {
95 public static function mysqlColumnNameLoose($str) {
97 // This check can be incorrect for the <table>.<column> format, which can be
99 if (empty($str) ||
strlen($str) > 64) {
107 * Validate an acceptable column name for sorting results.
113 public static function mysqlColumnName($str) {
115 if (empty($str) ||
strlen($str) > 64) {
119 // Make sure it only contains valid characters (alphanumeric and underscores).
121 // MySQL permits column names that don't match this (eg containing spaces),
122 // but CiviCRM won't create those ...
123 if (!preg_match('/^[\w_]+(\.[\w_]+)?$/i', $str)) {
131 * Validate that a string is ASC or DESC.
133 * Empty string should be treated as invalid and ignored => default = ASC.
138 public static function mysqlOrderByDirection($str) {
139 if (!preg_match('/^(asc|desc)$/i', $str)) {
151 public static function qfVariable($str) {
153 //if ( empty( $str ) || strlen( $str ) > 31 ) {
154 if (strlen(trim($str)) == 0 ||
strlen($str) > 31) {
158 // make sure it includes valid characters, alpha numeric and underscores
159 // added (. and ,) option (CRM-1336)
160 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
172 public static function phone($phone) {
174 if (empty($phone) ||
strlen($phone) > 16) {
178 // make sure it includes valid characters, (, \s and numeric
179 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
190 public static function query($query) {
192 if (empty($query) ||
strlen($query) < 3 ||
strlen($query) > 127) {
196 // make sure it includes valid characters, alpha numeric and underscores
197 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
209 public static function url($url) {
210 if (preg_match('/^\//', $url)) {
211 // allow relative URL's (CRM-15598)
212 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
214 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
222 public static function urlish($url) {
226 $url = Civi
::paths()->getUrl($url, 'absolute');
227 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
235 public static function wikiURL($string) {
236 $items = explode(' ', trim($string), 2);
237 return self
::url($items[0]);
245 public static function domain($domain) {
246 // not perfect, but better than the previous one; see CRM-1502
247 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
255 * @param null $default
259 public static function date($value, $default = NULL) {
260 if (is_string($value) &&
261 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
270 * @param null $default
272 * @return null|string
274 public static function dateTime($value, $default = NULL) {
276 if (is_string($value) &&
277 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
286 * Check the validity of the date (in qf format)
287 * note that only a year is valid, or a mon-year is
288 * also valid in addition to day-mon-year. The date
289 * specified has to be beyond today. (i.e today or later)
292 * @param bool $monthRequired
293 * Check whether month is mandatory.
298 public static function currentDate($date, $monthRequired = TRUE) {
299 $config = CRM_Core_Config
::singleton();
301 $d = CRM_Utils_Array
::value('d', $date);
302 $m = CRM_Utils_Array
::value('M', $date);
303 $y = CRM_Utils_Array
::value('Y', $date);
305 if (!$d && !$m && !$y) {
309 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
310 if (!$m && !empty($date['m'])) {
311 $m = CRM_Utils_Array
::value('m', $date);
326 // if we have day we need mon, and if we have mon we need year
335 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
336 $result = checkdate($mon, $day, $year);
343 // ensure we have month if required
344 if ($monthRequired && !$m) {
348 // now make sure this date is greater that today
349 $currentDate = getdate();
350 if ($year > $currentDate['year']) {
353 elseif ($year < $currentDate['year']) {
358 if ($mon > $currentDate['mon']) {
361 elseif ($mon < $currentDate['mon']) {
367 if ($day > $currentDate['mday']) {
370 elseif ($day < $currentDate['mday']) {
379 * Check the validity of a date or datetime (timestamp)
380 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
382 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
384 * @param string $date
389 public static function mysqlDate($date) {
390 // allow date to be null
395 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
407 public static function integer($value) {
408 if (is_int($value)) {
413 // ensure number passed is always a string numeral
414 if (!is_numeric($value)) {
418 // note that is_int matches only integer type
419 // and not strings which are only integers
420 // hence we do this here
421 if (preg_match('/^\d+$/', $value)) {
426 $negValue = -1 * $value;
427 if (is_int($negValue)) {
440 public static function positiveInteger($value) {
441 if (is_int($value)) {
442 return ($value < 0) ?
FALSE : TRUE;
446 // ensure number passed is always a string numeral
447 if (!is_numeric($value)) {
451 if (preg_match('/^\d+$/', $value)) {
463 public static function numeric($value) {
464 // lets use a php gatekeeper to ensure this is numeric
465 if (!is_numeric($value)) {
469 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ?
TRUE : FALSE;
478 public static function numberOfDigit($value, $noOfDigit) {
479 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ?
TRUE : FALSE;
487 public static function cleanMoney($value) {
488 // first remove all white space
489 $value = str_replace(array(' ', "\t", "\n"), '', $value);
491 $config = CRM_Core_Config
::singleton();
494 $currencySymbols = CRM_Core_PseudoConstant
::get(
495 'CRM_Contribute_DAO_Contribution',
497 'keyColumn' => 'name',
498 'labelColumn' => 'symbol',
501 $value = str_replace($currencySymbols, '', $value);
503 if ($config->monetaryThousandSeparator
) {
504 $mon_thousands_sep = $config->monetaryThousandSeparator
;
507 $mon_thousands_sep = ',';
510 // ugly fix for CRM-6391: do not drop the thousand separator if
511 // it looks like it’s separating decimal part (because a given
512 // value undergoes a second cleanMoney() call, for example)
513 // CRM-15835 - in case the amount/value contains 0 after decimal
514 // eg 150.5 the following if condition will pass
515 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
516 $value = str_replace($mon_thousands_sep, '', $value);
519 if ($config->monetaryDecimalPoint
) {
520 $mon_decimal_point = $config->monetaryDecimalPoint
;
523 $mon_decimal_point = '.';
525 $value = str_replace($mon_decimal_point, '.', $value);
535 public static function money($value) {
536 $config = CRM_Core_Config
::singleton();
538 // only edge case when we have a decimal point in the input money
539 // field and not defined in the decimal Point in config settings
540 if ($config->monetaryDecimalPoint
&&
541 $config->monetaryDecimalPoint
!= '.' &&
542 // CRM-7122 also check for Thousands Separator in config settings
543 $config->monetaryThousandSeparator
!= '.' &&
544 substr_count($value, '.')
549 $value = self
::cleanMoney($value);
551 if (self
::integer($value)) {
555 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ?
TRUE : FALSE;
560 * @param int $maxLength
564 public static function string($value, $maxLength = 0) {
565 if (is_string($value) &&
566 ($maxLength === 0 ||
strlen($value) <= $maxLength)
578 public static function boolean($value) {
580 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
589 public static function email($value) {
590 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
598 public static function emailList($list) {
599 $emails = explode(',', $list);
600 foreach ($emails as $email) {
601 $email = trim($email);
602 if (!self
::email($email)) {
610 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
611 * if u disregard the first 0, 4 (thanx excel!)
612 * FIXME: we need to figure out how to localize such rules
617 public static function postalCode($value) {
618 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
625 * See how file rules are written in HTML/QuickForm/file.php
626 * Checks to make sure the uploaded file is ascii
628 * @param string $elementValue
631 * True if file has been uploaded, false otherwise
633 public static function asciiFile($elementValue) {
634 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
635 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
637 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
643 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
645 * @param array $elementValue
648 * Whether file has been uploaded properly and is now in UTF-8.
650 public static function utf8File($elementValue) {
653 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
654 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
657 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
659 // if it's a file, but not UTF-8, let's try and recode it
660 // and then make sure it's an UTF-8 file in the end
662 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
664 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
672 * See how file rules are written in HTML/QuickForm/file.php
673 * Checks to make sure the uploaded file is html
675 * @param array $elementValue
678 * True if file has been uploaded, false otherwise
680 public static function htmlFile($elementValue) {
681 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
682 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
684 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
690 * Check if there is a record with the same name in the db.
692 * @param string $value
693 * The value of the field we are checking.
694 * @param array $options
695 * The daoName and fieldName (optional ).
698 * true if object exists
700 public static function objectExists($value, $options) {
702 if (isset($options[2])) {
706 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));
715 public static function optionExists($value, $options) {
716 return CRM_Core_OptionValue
::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array
::value(3, $options, 'name'));
725 public static function creditCardNumber($value, $type) {
726 require_once 'Validate/Finance/CreditCard.php';
727 return Validate_Finance_CreditCard
::number($value, $type);
736 public static function cvv($value, $type) {
737 require_once 'Validate/Finance/CreditCard.php';
739 return Validate_Finance_CreditCard
::cvv($value, $type);
747 public static function currencyCode($value) {
748 static $currencyCodes = NULL;
749 if (!$currencyCodes) {
750 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
752 if (in_array($value, $currencyCodes)) {
763 public static function xssString($value) {
764 if (is_string($value)) {
765 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
779 public static function fileExists($path) {
780 return file_exists($path);
784 * Determine whether the value contains a valid reference to a directory.
786 * Paths stored in the setting system may be absolute -- or may be
787 * relative to the default data directory.
789 * @param string $path
792 public static function settingPath($path) {
793 return is_dir(Civi
::paths()->getPath($path));
798 * @param null $actualElementValue
802 public static function validContact($value, $actualElementValue = NULL) {
803 if ($actualElementValue) {
804 $value = $actualElementValue;
807 return CRM_Utils_Rule
::positiveInteger($value);
811 * Check the validity of the date (in qf format)
812 * note that only a year is valid, or a mon-year is
813 * also valid in addition to day-mon-year
820 public static function qfDate($date) {
821 $config = CRM_Core_Config
::singleton();
823 $d = CRM_Utils_Array
::value('d', $date);
824 $m = CRM_Utils_Array
::value('M', $date);
825 $y = CRM_Utils_Array
::value('Y', $date);
826 if (isset($date['h']) ||
829 $m = CRM_Utils_Array
::value('M', $date);
832 if (!$d && !$m && !$y) {
848 // if we have day we need mon, and if we have mon we need year
856 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
857 return checkdate($mon, $day, $year);
867 public static function qfKey($key) {
868 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;
872 * Check if the values in the date range are in correct chronological order.
874 * @param array $fields
875 * Fields of the form.
877 * Name of date range field.
881 * Title of the date range to be displayed in the error message.
883 public static function validDateRange($fields, $fieldName, &$errors, $title) {
884 $lowDate = strtotime($fields[$fieldName . '_low']);
885 $highDate = strtotime($fields[$fieldName . '_high']);
887 if ($lowDate > $highDate) {
888 $errors[$fieldName . '_range_error'] = ts('%1: Please check that your date range is in correct chronological order.', array(1 => $title));