3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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)) {
93 * Validate that a string is a valid MySQL column name or alias.
99 public static function mysqlColumnNameOrAlias($str) {
105 // Ensure the string contains only valid characters:
106 // For column names: alphanumeric and underscores
107 // For aliases: backticks, alphanumeric hyphens and underscores.
108 if (!preg_match('/^((`[\w-]{1,64}`|[\w-]{1,64})\.)?(`[\w-]{1,64}`|[\w-]{1,64})$/i', $str)) {
116 * Validate that a string is ASC or DESC.
118 * Empty string should be treated as invalid and ignored => default = ASC.
123 public static function mysqlOrderByDirection($str) {
124 if (!preg_match('/^(asc|desc)$/i', $str)) {
132 * Validate that a string is valid order by clause.
137 public static function mysqlOrderBy($str) {
138 // Making a regex for a comma separated list is quite hard and not readable
139 // at all, so we split and loop over.
140 $parts = explode(',', $str);
141 foreach ($parts as $part) {
142 if (!preg_match('/^((`[\w-]{1,64}`|[\w-]{1,64})\.)?(`[\w-]{1,64}`|[\w-]{1,64})( (asc|desc))?$/i', trim($part))) {
155 public static function qfVariable($str) {
157 //if ( empty( $str ) || strlen( $str ) > 31 ) {
158 if (strlen(trim($str)) == 0 ||
strlen($str) > 31) {
162 // make sure it include valid characters, alpha numeric and underscores
163 // added (. and ,) option (CRM-1336)
164 if (!preg_match('/^[\w\s\.\,]+$/i', $str)) {
176 public static function phone($phone) {
178 if (empty($phone) ||
strlen($phone) > 16) {
182 // make sure it include valid characters, (, \s and numeric
183 if (preg_match('/^[\d\(\)\-\.\s]+$/', $phone)) {
194 public static function query($query) {
196 if (empty($query) ||
strlen($query) < 3 ||
strlen($query) > 127) {
200 // make sure it include valid characters, alpha numeric and underscores
201 if (!preg_match('/^[\w\s\%\'\&\,\$\#]+$/i', $query)) {
213 public static function url($url) {
214 if (preg_match('/^\//', $url)) {
215 // allow relative URL's (CRM-15598)
216 $url = 'http://' . $_SERVER['HTTP_HOST'] . $url;
218 return (bool) filter_var($url, FILTER_VALIDATE_URL
);
226 public static function wikiURL($string) {
227 $items = explode(' ', trim($string), 2);
228 return self
::url($items[0]);
236 public static function domain($domain) {
237 // not perfect, but better than the previous one; see CRM-1502
238 if (!preg_match('/^[A-Za-z0-9]([A-Za-z0-9\.\-]*[A-Za-z0-9])?$/', $domain)) {
246 * @param null $default
250 public static function date($value, $default = NULL) {
251 if (is_string($value) &&
252 preg_match('/^\d\d\d\d-?\d\d-?\d\d$/', $value)
261 * @param null $default
263 * @return null|string
265 public static function dateTime($value, $default = NULL) {
267 if (is_string($value) &&
268 preg_match('/^\d\d\d\d-?\d\d-?\d\d(\s\d\d:\d\d(:\d\d)?|\d\d\d\d(\d\d)?)?$/', $value)
277 * Check the validity of the date (in qf format)
278 * note that only a year is valid, or a mon-year is
279 * also valid in addition to day-mon-year. The date
280 * specified has to be beyond today. (i.e today or later)
283 * @param bool $monthRequired
284 * Check whether month is mandatory.
289 public static function currentDate($date, $monthRequired = TRUE) {
290 $config = CRM_Core_Config
::singleton();
292 $d = CRM_Utils_Array
::value('d', $date);
293 $m = CRM_Utils_Array
::value('M', $date);
294 $y = CRM_Utils_Array
::value('Y', $date);
296 if (!$d && !$m && !$y) {
300 // CRM-9017 CiviContribute/CiviMember form with expiration date format 'm Y'
301 if (!$m && !empty($date['m'])) {
302 $m = CRM_Utils_Array
::value('m', $date);
317 // if we have day we need mon, and if we have mon we need year
326 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
327 $result = checkdate($mon, $day, $year);
334 // ensure we have month if required
335 if ($monthRequired && !$m) {
339 // now make sure this date is greater that today
340 $currentDate = getdate();
341 if ($year > $currentDate['year']) {
344 elseif ($year < $currentDate['year']) {
349 if ($mon > $currentDate['mon']) {
352 elseif ($mon < $currentDate['mon']) {
358 if ($day > $currentDate['mday']) {
361 elseif ($day < $currentDate['mday']) {
370 * Check the validity of a date or datetime (timestamp)
371 * value which is in YYYYMMDD or YYYYMMDDHHMMSS format
373 * Uses PHP checkdate() - params are ( int $month, int $day, int $year )
375 * @param string $date
380 public static function mysqlDate($date) {
381 // allow date to be null
386 if (checkdate(substr($date, 4, 2), substr($date, 6, 2), substr($date, 0, 4))) {
398 public static function integer($value) {
399 if (is_int($value)) {
404 // ensure number passed is always a string numeral
405 if (!is_numeric($value)) {
409 // note that is_int matches only integer type
410 // and not strings which are only integers
411 // hence we do this here
412 if (preg_match('/^\d+$/', $value)) {
417 $negValue = -1 * $value;
418 if (is_int($negValue)) {
431 public static function positiveInteger($value) {
432 if (is_int($value)) {
433 return ($value < 0) ?
FALSE : TRUE;
437 // ensure number passed is always a string numeral
438 if (!is_numeric($value)) {
442 if (preg_match('/^\d+$/', $value)) {
454 public static function numeric($value) {
455 // lets use a php gatekeeper to ensure this is numeric
456 if (!is_numeric($value)) {
460 return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ?
TRUE : FALSE;
469 public static function numberOfDigit($value, $noOfDigit) {
470 return preg_match('/^\d{' . $noOfDigit . '}$/', $value) ?
TRUE : FALSE;
478 public static function cleanMoney($value) {
479 // first remove all white space
480 $value = str_replace(array(' ', "\t", "\n"), '', $value);
482 $config = CRM_Core_Config
::singleton();
485 $currencySymbols = CRM_Core_PseudoConstant
::get(
486 'CRM_Contribute_DAO_Contribution',
488 'keyColumn' => 'name',
489 'labelColumn' => 'symbol',
492 $value = str_replace($currencySymbols, '', $value);
494 if ($config->monetaryThousandSeparator
) {
495 $mon_thousands_sep = $config->monetaryThousandSeparator
;
498 $mon_thousands_sep = ',';
501 // ugly fix for CRM-6391: do not drop the thousand separator if
502 // it looks like it’s separating decimal part (because a given
503 // value undergoes a second cleanMoney() call, for example)
504 // CRM-15835 - in case the amount/value contains 0 after decimal
505 // eg 150.5 the following if condition will pass
506 if ($mon_thousands_sep != '.' or (substr($value, -3, 1) != '.' && substr($value, -2, 1) != '.')) {
507 $value = str_replace($mon_thousands_sep, '', $value);
510 if ($config->monetaryDecimalPoint
) {
511 $mon_decimal_point = $config->monetaryDecimalPoint
;
514 $mon_decimal_point = '.';
516 $value = str_replace($mon_decimal_point, '.', $value);
526 public static function money($value) {
527 $config = CRM_Core_Config
::singleton();
529 //only edge case when we have a decimal point in the input money
530 //field and not defined in the decimal Point in config settings
531 if ($config->monetaryDecimalPoint
&&
532 $config->monetaryDecimalPoint
!= '.' &&
533 /* CRM-7122 also check for Thousands Separator in config settings */
534 $config->monetaryThousandSeparator
!= '.' &&
535 substr_count($value, '.')
540 $value = self
::cleanMoney($value);
542 if (self
::integer($value)) {
546 return preg_match('/(^-?\d+\.\d?\d?$)|(^-?\.\d\d?$)/', $value) ?
TRUE : FALSE;
551 * @param int $maxLength
555 public static function string($value, $maxLength = 0) {
556 if (is_string($value) &&
557 ($maxLength === 0 ||
strlen($value) <= $maxLength)
569 public static function boolean($value) {
571 '/(^(1|0)$)|(^(Y(es)?|N(o)?)$)|(^(T(rue)?|F(alse)?)$)/i', $value
580 public static function email($value) {
581 return (bool) filter_var($value, FILTER_VALIDATE_EMAIL
);
589 public static function emailList($list) {
590 $emails = explode(',', $list);
591 foreach ($emails as $email) {
592 $email = trim($email);
593 if (!self
::email($email)) {
601 * allow between 4-6 digits as postal code since india needs 6 and US needs 5 (or
602 * if u disregard the first 0, 4 (thanx excel!)
603 * FIXME: we need to figure out how to localize such rules
608 public static function postalCode($value) {
609 if (preg_match('/^\d{4,6}(-\d{4})?$/', $value)) {
616 * See how file rules are written in HTML/QuickForm/file.php
617 * Checks to make sure the uploaded file is ascii
620 * true if file has been uploaded, false otherwise
622 public static function asciiFile($elementValue) {
623 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
624 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
626 return CRM_Utils_File
::isAscii($elementValue['tmp_name']);
632 * Checks to make sure the uploaded file is in UTF-8, recodes if it's not
635 * whether file has been uploaded properly and is now in UTF-8
637 public static function utf8File($elementValue) {
640 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
641 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
644 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
646 // if it's a file, but not UTF-8, let's try and recode it
647 // and then make sure it's an UTF-8 file in the end
649 $success = CRM_Utils_File
::toUtf8($elementValue['tmp_name']);
651 $success = CRM_Utils_File
::isAscii($elementValue['tmp_name']);
659 * See how file rules are written in HTML/QuickForm/file.php
660 * Checks to make sure the uploaded file is html
663 * true if file has been uploaded, false otherwise
665 public static function htmlFile($elementValue) {
666 if ((isset($elementValue['error']) && $elementValue['error'] == 0) ||
667 (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')
669 return CRM_Utils_File
::isHtmlFile($elementValue['tmp_name']);
675 * Check if there is a record with the same name in the db.
677 * @param string $value
678 * The value of the field we are checking.
679 * @param array $options
680 * The daoName and fieldName (optional ).
683 * true if object exists
685 public static function objectExists($value, $options) {
687 if (isset($options[2])) {
691 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));
700 public static function optionExists($value, $options) {
701 return CRM_Core_OptionValue
::optionExists($value, $options[0], $options[1], $options[2], CRM_Utils_Array
::value(3, $options, 'name'));
710 public static function creditCardNumber($value, $type) {
711 require_once 'Validate/Finance/CreditCard.php';
712 return Validate_Finance_CreditCard
::number($value, $type);
721 public static function cvv($value, $type) {
722 require_once 'Validate/Finance/CreditCard.php';
724 return Validate_Finance_CreditCard
::cvv($value, $type);
732 public static function currencyCode($value) {
733 static $currencyCodes = NULL;
734 if (!$currencyCodes) {
735 $currencyCodes = CRM_Core_PseudoConstant
::currencyCode();
737 if (in_array($value, $currencyCodes)) {
748 public static function xssString($value) {
749 if (is_string($value)) {
750 return preg_match('!<(vb)?script[^>]*>.*</(vb)?script.*>!ims',
764 public static function fileExists($path) {
765 return file_exists($path);
774 public static function autocomplete($value, $options) {
776 $selectOption = CRM_Core_BAO_CustomOption
::valuesByID($options['fieldID'], $options['optionGroupID']);
778 if (!in_array($value, $selectOption)) {
787 * @param null $actualElementValue
791 public static function validContact($value, $actualElementValue = NULL) {
792 if ($actualElementValue) {
793 $value = $actualElementValue;
796 return CRM_Utils_Rule
::positiveInteger($value);
800 * Check the validity of the date (in qf format)
801 * note that only a year is valid, or a mon-year is
802 * also valid in addition to day-mon-year
809 public static function qfDate($date) {
810 $config = CRM_Core_Config
::singleton();
812 $d = CRM_Utils_Array
::value('d', $date);
813 $m = CRM_Utils_Array
::value('M', $date);
814 $y = CRM_Utils_Array
::value('Y', $date);
815 if (isset($date['h']) ||
818 $m = CRM_Utils_Array
::value('M', $date);
821 if (!$d && !$m && !$y) {
837 // if we have day we need mon, and if we have mon we need year
845 if (!empty($day) ||
!empty($mon) ||
!empty($year)) {
846 return checkdate($mon, $day, $year);
856 public static function qfKey($key) {
857 return ($key) ? CRM_Core_Key
::valid($key) : FALSE;