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
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 qfVariable($str) {
97 //if ( empty( $str ) || strlen( $str ) > 31 ) {
98 if (strlen(trim($str)) == 0 ||
strlen($str) > 31) {
102 // make sure it includes valid characters, alpha numeric and underscores
103 // added (. and ,) option (CRM-1336)
104 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
116 public static function phone($phone) {
118 if (empty($phone) ||
strlen($phone) > 16) {
122 // make sure it includes valid characters, (, \s and numeric
123 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
134 public static function query($query) {
136 if (empty($query) ||
strlen($query) < 3 ||
strlen($query) > 127) {
140 // make sure it includes valid characters, alpha numeric and underscores
141 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
153 public static function url($url) {
154 if (preg_match('/^\//', $url)) {
155 // allow relative URL's (CRM-15598)
156 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
158 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
166 public static function urlish($url) {
170 $url = Civi
::paths()->getUrl($url, 'absolute');
171 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
179 public static function wikiURL($string) {
180 $items = explode(' ', trim($string), 2);
181 return self
::url($items[0]);
189 public static function domain($domain) {
190 // not perfect, but better than the previous one; see CRM-1502
191 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
199 * @param null $default
203 public static function date($value, $default = NULL) {
204 if (is_string($value) &&
205 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
214 * @param null $default
216 * @return null|string
218 public static function dateTime($value, $default = NULL) {
220 if (is_string($value) &&
221 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
230 * Check the validity of the date (in qf format)
231 * note that only a year is valid, or a mon-year is
232 * also valid in addition to day-mon-year. The date
233 * specified has to be beyond today. (i.e today or later)
236 * @param bool $monthRequired
237 * Check whether month is mandatory.
242 public static function currentDate($date, $monthRequired = TRUE) {
243 $config = CRM_Core_Config
::singleton();
245 $d = CRM_Utils_Array
::value('d', $date);
246 $m = CRM_Utils_Array
::value('M', $date);
247 $y = CRM_Utils_Array
::value('Y', $date);
249 if (!$d && !$m && !$y) {
253 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
254 if (!$m && !empty($date['m'])) {
255 $m = CRM_Utils_Array
::value('m', $date);
270 // if we have day we need mon, and if we have mon we need year
279 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
280 $result = checkdate($mon, $day, $year);
287 // ensure we have month if required
288 if ($monthRequired && !$m) {
292 // now make sure this date is greater that today
293 $currentDate = getdate();
294 if ($year > $currentDate['year']) {
297 elseif ($year < $currentDate['year']) {
302 if ($mon > $currentDate['mon']) {
305 elseif ($mon < $currentDate['mon']) {
311 if ($day > $currentDate['mday']) {
314 elseif ($day < $currentDate['mday']) {
323 * Check the validity of a date or datetime (timestamp)
324 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
326 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
328 * @param string $date
333 public static function mysqlDate($date) {
334 // allow date to be null
339 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
351 public static function integer($value) {
352 if (is_int($value)) {
357 // ensure number passed is always a string numeral
358 if (!is_numeric($value)) {
362 // note that is_int matches only integer type
363 // and not strings which are only integers
364 // hence we do this here
365 if (preg_match('/^\d+$/', $value)) {
370 $negValue = -1 * $value;
371 if (is_int($negValue)) {
384 public static function positiveInteger($value) {
385 if (is_int($value)) {
386 return ($value < 0) ?
FALSE : TRUE;
390 // ensure number passed is always a string numeral
391 if (!is_numeric($value)) {
395 if (preg_match('/^\d+$/', $value)) {
407 public static function numeric($value) {
408 // lets use a php gatekeeper to ensure this is numeric
409 if (!is_numeric($value)) {
413 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ?
TRUE : FALSE;
422 public static function numberOfDigit($value, $noOfDigit) {
423 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ?
TRUE : FALSE;
431 public static function cleanMoney($value) {
432 // first remove all white space
433 $value = str_replace(array(' ', "\t", "\n"), '', $value);
435 $config = CRM_Core_Config
::singleton();
438 $currencySymbols = CRM_Core_PseudoConstant
::get(
439 'CRM_Contribute_DAO_Contribution',
441 'keyColumn' => 'name',
442 'labelColumn' => 'symbol',
445 $value = str_replace($currencySymbols, '', $value);
447 if ($config->monetaryThousandSeparator
) {
448 $mon_thousands_sep = $config->monetaryThousandSeparator
;
451 $mon_thousands_sep = ',';
454 // ugly fix for CRM-6391: do not drop the thousand separator if
455 // it looks like it’s separating decimal part (because a given
456 // value undergoes a second cleanMoney() call, for example)
457 // CRM-15835 - in case the amount/value contains 0 after decimal
458 // eg 150.5 the following if condition will pass
459 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
460 $value = str_replace($mon_thousands_sep, '', $value);
463 if ($config->monetaryDecimalPoint
) {
464 $mon_decimal_point = $config->monetaryDecimalPoint
;
467 $mon_decimal_point = '.';
469 $value = str_replace($mon_decimal_point, '.', $value);
479 public static function money($value) {
480 $config = CRM_Core_Config
::singleton();
482 // only edge case when we have a decimal point in the input money
483 // field and not defined in the decimal Point in config settings
484 if ($config->monetaryDecimalPoint
&&
485 $config->monetaryDecimalPoint
!= '.' &&
486 // CRM-7122 also check for Thousands Separator in config settings
487 $config->monetaryThousandSeparator
!= '.' &&
488 substr_count($value, '.')
493 $value = self
::cleanMoney($value);
495 if (self
::integer($value)) {
499 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ?
TRUE : FALSE;
504 * @param int $maxLength
508 public static function string($value, $maxLength = 0) {
509 if (is_string($value) &&
510 ($maxLength === 0 ||
strlen($value) <= $maxLength)
522 public static function boolean($value) {
524 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
533 public static function email($value) {
534 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
542 public static function emailList($list) {
543 $emails = explode(',', $list);
544 foreach ($emails as $email) {
545 $email = trim($email);
546 if (!self
::email($email)) {
554 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
555 * if u disregard the first 0, 4 (thanx excel!)
556 * FIXME: we need to figure out how to localize such rules
561 public static function postalCode($value) {
562 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
569 * See how file rules are written in HTML/QuickForm/file.php
570 * Checks to make sure the uploaded file is ascii
572 * @param string $elementValue
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
589 * @param array $elementValue
592 * Whether file has been uploaded properly and is now in UTF-8.
594 public static function utf8File($elementValue) {
597 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
598 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
601 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
603 // if it's a file, but not UTF-8, let's try and recode it
604 // and then make sure it's an UTF-8 file in the end
606 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
608 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
616 * See how file rules are written in HTML/QuickForm/file.php
617 * Checks to make sure the uploaded file is html
619 * @param array $elementValue
622 * True if file has been uploaded, false otherwise
624 public static function htmlFile($elementValue) {
625 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
626 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
628 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
634 * Check if there is a record with the same name in the db.
636 * @param string $value
637 * The value of the field we are checking.
638 * @param array $options
639 * The daoName and fieldName (optional ).
642 * true if object exists
644 public static function objectExists($value, $options) {
646 if (isset($options[2])) {
650 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));
659 public static function optionExists($value, $options) {
660 return CRM_Core_OptionValue
::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array
::value(3, $options, 'name'));
669 public static function creditCardNumber($value, $type) {
670 require_once 'Validate/Finance/CreditCard.php';
671 return Validate_Finance_CreditCard
::number($value, $type);
680 public static function cvv($value, $type) {
681 require_once 'Validate/Finance/CreditCard.php';
683 return Validate_Finance_CreditCard
::cvv($value, $type);
691 public static function currencyCode($value) {
692 static $currencyCodes = NULL;
693 if (!$currencyCodes) {
694 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
696 if (in_array($value, $currencyCodes)) {
707 public static function xssString($value) {
708 if (is_string($value)) {
709 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
723 public static function fileExists($path) {
724 return file_exists($path);
728 * Determine whether the value contains a valid reference to a directory.
730 * Paths stored in the setting system may be absolute -- or may be
731 * relative to the default data directory.
733 * @param string $path
736 public static function settingPath($path) {
737 return is_dir(Civi
::paths()->getPath($path));
742 * @param null $actualElementValue
746 public static function validContact($value, $actualElementValue = NULL) {
747 if ($actualElementValue) {
748 $value = $actualElementValue;
751 return CRM_Utils_Rule
::positiveInteger($value);
755 * Check the validity of the date (in qf format)
756 * note that only a year is valid, or a mon-year is
757 * also valid in addition to day-mon-year
764 public static function qfDate($date) {
765 $config = CRM_Core_Config
::singleton();
767 $d = CRM_Utils_Array
::value('d', $date);
768 $m = CRM_Utils_Array
::value('M', $date);
769 $y = CRM_Utils_Array
::value('Y', $date);
770 if (isset($date['h']) ||
773 $m = CRM_Utils_Array
::value('M', $date);
776 if (!$d && !$m && !$y) {
792 // if we have day we need mon, and if we have mon we need year
800 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
801 return checkdate($mon, $day, $year);
811 public static function qfKey($key) {
812 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;