3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
36 require_once 'HTML/QuickForm/Rule/Email.php';
39 * Class CRM_Utils_Rule
41 class CRM_Utils_Rule
{
45 * @param int $maxLength
49 public static function title($str, $maxLength = 127) {
52 if (empty($str) ||
strlen($str) > $maxLength) {
56 // Make sure it include valid characters, alpha numeric and underscores
57 if (!preg_match('/^\w[\w\s\'\&\,\$\#\-\.\"\?\!]+$/i', $str)) {
69 public static function longTitle($str) {
70 return self
::title($str, 255);
78 public static function variable($str) {
80 if (empty($str) ||
strlen($str) > 31) {
84 // make sure it include valid characters, alpha numeric and underscores
85 if (!preg_match('/^[\w]+$/i', $str)) {
97 public static function qfVariable($str) {
99 //if ( empty( $str ) || strlen( $str ) > 31 ) {
100 if (strlen(trim($str)) == 0 ||
strlen($str) > 31) {
104 // make sure it include valid characters, alpha numeric and underscores
105 // added (. and ,) option (CRM-1336)
106 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
118 public static function phone($phone) {
120 if (empty($phone) ||
strlen($phone) > 16) {
124 // make sure it include valid characters, (, \s and numeric
125 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
136 public static function query($query) {
138 if (empty($query) ||
strlen($query) < 3 ||
strlen($query) > 127) {
142 // make sure it include valid characters, alpha numeric and underscores
143 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
155 public static function url($url) {
156 if (preg_match('/^\//', $url)) {
157 // allow relative URL's (CRM-15598)
158 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
160 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
168 public static function urlish($url) {
172 $url = Civi
::paths()->getUrl($url, 'absolute');
173 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
181 public static function wikiURL($string) {
182 $items = explode(' ', trim($string), 2);
183 return self
::url($items[0]);
191 public static function domain($domain) {
192 // not perfect, but better than the previous one; see CRM-1502
193 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
201 * @param null $default
205 public static function date($value, $default = NULL) {
206 if (is_string($value) &&
207 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
216 * @param null $default
218 * @return null|string
220 public static function dateTime($value, $default = NULL) {
222 if (is_string($value) &&
223 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
232 * Check the validity of the date (in qf format)
233 * note that only a year is valid, or a mon-year is
234 * also valid in addition to day-mon-year. The date
235 * specified has to be beyond today. (i.e today or later)
238 * @param bool $monthRequired
239 * Check whether month is mandatory.
244 public static function currentDate($date, $monthRequired = TRUE) {
245 $config = CRM_Core_Config
::singleton();
247 $d = CRM_Utils_Array
::value('d', $date);
248 $m = CRM_Utils_Array
::value('M', $date);
249 $y = CRM_Utils_Array
::value('Y', $date);
251 if (!$d && !$m && !$y) {
255 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
256 if (!$m && !empty($date['m'])) {
257 $m = CRM_Utils_Array
::value('m', $date);
272 // if we have day we need mon, and if we have mon we need year
281 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
282 $result = checkdate($mon, $day, $year);
289 // ensure we have month if required
290 if ($monthRequired && !$m) {
294 // now make sure this date is greater that today
295 $currentDate = getdate();
296 if ($year > $currentDate['year']) {
299 elseif ($year < $currentDate['year']) {
304 if ($mon > $currentDate['mon']) {
307 elseif ($mon < $currentDate['mon']) {
313 if ($day > $currentDate['mday']) {
316 elseif ($day < $currentDate['mday']) {
325 * Check the validity of a date or datetime (timestamp)
326 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
328 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
330 * @param string $date
335 public static function mysqlDate($date) {
336 // allow date to be null
341 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
353 public static function integer($value) {
354 if (is_int($value)) {
359 // ensure number passed is always a string numeral
360 if (!is_numeric($value)) {
364 // note that is_int matches only integer type
365 // and not strings which are only integers
366 // hence we do this here
367 if (preg_match('/^\d+$/', $value)) {
372 $negValue = -1 * $value;
373 if (is_int($negValue)) {
386 public static function positiveInteger($value) {
387 if (is_int($value)) {
388 return ($value < 0) ?
FALSE : TRUE;
392 // ensure number passed is always a string numeral
393 if (!is_numeric($value)) {
397 if (preg_match('/^\d+$/', $value)) {
409 public static function numeric($value) {
410 // lets use a php gatekeeper to ensure this is numeric
411 if (!is_numeric($value)) {
415 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ?
TRUE : FALSE;
424 public static function numberOfDigit($value, $noOfDigit) {
425 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ?
TRUE : FALSE;
433 public static function cleanMoney($value) {
434 // first remove all white space
435 $value = str_replace(array(' ', "\t", "\n"), '', $value);
437 $config = CRM_Core_Config
::singleton();
440 $currencySymbols = CRM_Core_PseudoConstant
::get(
441 'CRM_Contribute_DAO_Contribution',
443 'keyColumn' => 'name',
444 'labelColumn' => 'symbol',
447 $value = str_replace($currencySymbols, '', $value);
449 if ($config->monetaryThousandSeparator
) {
450 $mon_thousands_sep = $config->monetaryThousandSeparator
;
453 $mon_thousands_sep = ',';
456 // ugly fix for CRM-6391: do not drop the thousand separator if
457 // it looks like it’s separating decimal part (because a given
458 // value undergoes a second cleanMoney() call, for example)
459 // CRM-15835 - in case the amount/value contains 0 after decimal
460 // eg 150.5 the following if condition will pass
461 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
462 $value = str_replace($mon_thousands_sep, '', $value);
465 if ($config->monetaryDecimalPoint
) {
466 $mon_decimal_point = $config->monetaryDecimalPoint
;
469 $mon_decimal_point = '.';
471 $value = str_replace($mon_decimal_point, '.', $value);
481 public static function money($value) {
482 $config = CRM_Core_Config
::singleton();
484 //only edge case when we have a decimal point in the input money
485 //field and not defined in the decimal Point in config settings
486 if ($config->monetaryDecimalPoint
&&
487 $config->monetaryDecimalPoint
!= '.' &&
488 /* CRM-7122 also check for Thousands Separator in config settings */
489 $config->monetaryThousandSeparator
!= '.' &&
490 substr_count($value, '.')
495 $value = self
::cleanMoney($value);
497 if (self
::integer($value)) {
501 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ?
TRUE : FALSE;
506 * @param int $maxLength
510 public static function string($value, $maxLength = 0) {
511 if (is_string($value) &&
512 ($maxLength === 0 ||
strlen($value) <= $maxLength)
524 public static function boolean($value) {
526 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
535 public static function email($value) {
536 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
544 public static function emailList($list) {
545 $emails = explode(',', $list);
546 foreach ($emails as $email) {
547 $email = trim($email);
548 if (!self
::email($email)) {
556 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
557 * if u disregard the first 0, 4 (thanx excel!)
558 * FIXME: we need to figure out how to localize such rules
563 public static function postalCode($value) {
564 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
571 * See how file rules are written in HTML/QuickForm/file.php
572 * Checks to make sure the uploaded file is ascii
575 * true if file has been uploaded, false otherwise
577 public static function asciiFile($elementValue) {
578 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
579 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
581 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
587 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
590 * whether file has been uploaded properly and is now in UTF-8
592 public static function utf8File($elementValue) {
595 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
596 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
599 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
601 // if it's a file, but not UTF-8, let's try and recode it
602 // and then make sure it's an UTF-8 file in the end
604 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
606 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
614 * See how file rules are written in HTML/QuickForm/file.php
615 * Checks to make sure the uploaded file is html
618 * true if file has been uploaded, false otherwise
620 public static function htmlFile($elementValue) {
621 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
622 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
624 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
630 * Check if there is a record with the same name in the db.
632 * @param string $value
633 * The value of the field we are checking.
634 * @param array $options
635 * The daoName and fieldName (optional ).
638 * true if object exists
640 public static function objectExists($value, $options) {
642 if (isset($options[2])) {
646 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));
655 public static function optionExists($value, $options) {
656 return CRM_Core_OptionValue
::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array
::value(3, $options, 'name'));
665 public static function creditCardNumber($value, $type) {
666 require_once 'Validate/Finance/CreditCard.php';
667 return Validate_Finance_CreditCard
::number($value, $type);
676 public static function cvv($value, $type) {
677 require_once 'Validate/Finance/CreditCard.php';
679 return Validate_Finance_CreditCard
::cvv($value, $type);
687 public static function currencyCode($value) {
688 static $currencyCodes = NULL;
689 if (!$currencyCodes) {
690 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
692 if (in_array($value, $currencyCodes)) {
703 public static function xssString($value) {
704 if (is_string($value)) {
705 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
719 public static function fileExists($path) {
720 return file_exists($path);
724 * Determine whether the value contains a valid reference to a directory.
726 * Paths stored in the setting system may be absolute -- or may be
727 * relative to the default data directory.
729 * @param string $path
732 public static function settingPath($path) {
733 return is_dir(Civi
::paths()->getPath($path));
742 public static function autocomplete($value, $options) {
744 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($options['fieldID'], $options['optionGroupID']);
746 if (!in_array($value, $selectOption)) {
755 * @param null $actualElementValue
759 public static function validContact($value, $actualElementValue = NULL) {
760 if ($actualElementValue) {
761 $value = $actualElementValue;
764 if ($value && !is_numeric($value)) {
771 * Check the validity of the date (in qf format)
772 * note that only a year is valid, or a mon-year is
773 * also valid in addition to day-mon-year
780 public static function qfDate($date) {
781 $config = CRM_Core_Config
::singleton();
783 $d = CRM_Utils_Array
::value('d', $date);
784 $m = CRM_Utils_Array
::value('M', $date);
785 $y = CRM_Utils_Array
::value('Y', $date);
786 if (isset($date['h']) ||
789 $m = CRM_Utils_Array
::value('M', $date);
792 if (!$d && !$m && !$y) {
808 // if we have day we need mon, and if we have mon we need year
816 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
817 return checkdate($mon, $day, $year);
827 public static function qfKey($key) {
828 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;