3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
33 class CRM_Utils_Type
{
52 // @TODO What's the point of these constants? Backwards compatibility?
54 // These are used for field size (<input type=text size=2>), but redundant TWO=2
55 // usages are rare and should be eliminated. See CRM-18810.
71 * Gets the string representation for a data type.
74 * Integer number identifying the data type.
77 * String identifying the data type, e.g. 'Int' or 'String'.
79 public static function typeToString($type) {
80 // @todo Use constants in the case statements, e.g. "case T_INT:".
81 // @todo return directly, instead of assigning a value.
82 // @todo Use a lookup array, as a property or as a local variable.
119 $string = 'Timestamp';
139 $string = 'Mediumblob';
143 return (isset($string)) ?
$string : "";
148 * An array of type in the form 'type name' => 'int representing type'
150 public static function getValidTypes() {
152 'Int' => self
::T_INT
,
153 'String' => self
::T_STRING
,
154 'Enum' => self
::T_ENUM
,
155 'Date' => self
::T_DATE
,
156 'Time' => self
::T_TIME
,
157 'Boolean' => self
::T_BOOLEAN
,
158 'Text' => self
::T_TEXT
,
159 'Blob' => self
::T_BLOB
,
160 'Timestamp' => self
::T_TIMESTAMP
,
161 'Float' => self
::T_FLOAT
,
162 'Money' => self
::T_MONEY
,
163 'Email' => self
::T_EMAIL
,
164 'Mediumblob' => self
::T_MEDIUMBLOB
,
169 * Get the data_type for the field.
171 * @param array $fieldMetadata
172 * Metadata about the field.
176 public static function getDataTypeFromFieldMetadata($fieldMetadata) {
177 if (isset($fieldMetadata['data_type'])) {
178 return $fieldMetadata['data_type'];
180 if (empty($fieldMetadata['type'])) {
181 // I would prefer to throw an e-notice but there is some,
182 // probably unnecessary logic, that only retrieves activity fields
183 // if they are 'in the profile' and probably they are not 'in'
184 // until they are added - which might lead to ? who knows!
187 return self
::typeToString($fieldMetadata['type']);
191 * Helper function to call escape on arrays.
195 public static function escapeAll($data, $type, $abort = TRUE) {
196 foreach ($data as $key => $value) {
197 $data[$key] = CRM_Utils_Type
::escape($value, $type, $abort);
203 * Helper function to call validate on arrays
207 public static function validateAll($data, $type, $abort = TRUE) {
208 foreach ($data as $key => $value) {
209 $data[$key] = CRM_Utils_Type
::validate($value, $type, $abort);
215 * Verify that a variable is of a given type, and apply a bit of processing.
218 * The value to be verified/escaped.
219 * @param string $type
220 * The type to verify against.
222 * If TRUE, the operation will CRM_Core_Error::fatal() on invalid data.
225 * The data, escaped if necessary.
227 public static function escape($data, $type, $abort = TRUE) {
231 if (CRM_Utils_Rule
::integer($data)) {
237 if (CRM_Utils_Rule
::positiveInteger($data)) {
242 // CRM-8925 for custom fields of this type
244 case 'StateProvince':
245 // Handle multivalued data in delimited or array format
246 if (is_array($data) ||
(strpos($data, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE)) {
248 foreach (CRM_Utils_Array
::explodePadded($data) as $item) {
249 if (!CRM_Utils_Rule
::positiveInteger($item)) {
257 elseif (CRM_Utils_Rule
::positiveInteger($data)) {
263 if (CRM_Utils_Rule
::positiveInteger($data)) {
269 if (CRM_Utils_Rule
::url($data = trim($data))) {
275 if (CRM_Utils_Rule
::boolean($data)) {
282 if (CRM_Utils_Rule
::numeric($data)) {
290 return CRM_Core_DAO
::escapeString($data);
294 // a null date or timestamp is valid
295 if (strlen(trim($data)) == 0) {
299 if ((preg_match('/^\d{8}$/', $data) ||
300 preg_match('/^\d{14}$/', $data)
302 CRM_Utils_Rule
::mysqlDate($data)
308 case 'ContactReference':
309 if (strlen(trim($data)) == 0) {
313 if (CRM_Utils_Rule
::validContact($data)) {
318 case 'MysqlColumnNameOrAlias':
319 if (CRM_Utils_Rule
::mysqlColumnNameOrAlias($data)) {
320 $data = str_replace('`', '', $data);
321 $parts = explode('.', $data);
322 $data = '`' . implode('`.`', $parts) . '`';
328 case 'MysqlOrderByDirection':
329 if (CRM_Utils_Rule
::mysqlOrderByDirection($data)) {
330 return strtolower($data);
335 if (CRM_Utils_Rule
::mysqlOrderBy($data)) {
336 $parts = explode(',', $data);
338 // The field() syntax is tricky here because it uses commas & when
339 // we separate by them we break it up. But we want to keep the clauses in order.
340 // so we just clumsily re-assemble it. Test cover exists.
341 $fieldClauseStart = NULL;
342 foreach ($parts as $index => &$part) {
343 if (substr($part, 0, 6) === 'field(') {
344 // Looking to escape a string like 'field(contribution_status_id,3,4,5) asc'
345 // to 'field(`contribution_status_id`,3,4,5) asc'
346 $fieldClauseStart = $index;
349 if ($fieldClauseStart !== NULL) {
350 // this is part of the list of field options. Concatenate it back on.
351 $parts[$fieldClauseStart] .= ',' . $part;
352 unset($parts[$index]);
353 if (!strstr($parts[$fieldClauseStart], ')')) {
354 // we have not reached the end of the list.
357 // We have the last piece of the field() clause, time to escape it.
358 $parts[$fieldClauseStart] = self
::mysqlOrderByFieldFunctionCallback($parts[$fieldClauseStart]);
359 $fieldClauseStart = NULL;
364 $part = preg_replace_callback('/^(?:(?:((?:`[\w-]{1,64}`|[\w-]{1,64}))(?:\.))?(`[\w-]{1,64}`|[\w-]{1,64})(?: (asc|desc))?)$/i', array('CRM_Utils_Type', 'mysqlOrderByCallback'), trim($part));
366 return implode(', ', $parts);
371 CRM_Core_Error
::fatal(
372 $type . " is not a recognised (camel cased) data type."
377 // @todo Use exceptions instead of CRM_Core_Error::fatal().
379 $data = htmlentities($data);
380 CRM_Core_Error
::fatal("$data is not of the type $type");
386 * Verify that a variable is of a given type.
389 * The value to validate.
390 * @param string $type
391 * The type to validate against.
393 * If TRUE, the operation will CRM_Core_Error::fatal() on invalid data.
394 * @param string $name
395 * The name of the attribute
396 * @param bool $isThrowException
397 * Should an exception be thrown rather than a using a deprecated fatal error.
400 * The data, escaped if necessary
402 * @throws \CRM_Core_Exception
404 public static function validate($data, $type, $abort = TRUE, $name = 'One of parameters ', $isThrowException = FALSE) {
406 $possibleTypes = array(
410 'CommaSeparatedIntegers',
421 'MysqlColumnNameOrAlias',
422 'MysqlOrderByDirection',
428 if (!in_array($type, $possibleTypes)) {
429 if ($isThrowException) {
430 throw new CRM_Core_Exception(ts('Invalid type, must be one of : ' . implode($possibleTypes)));
432 CRM_Core_Error
::fatal(ts('Invalid type, must be one of : ' . implode($possibleTypes)));
437 if (CRM_Utils_Rule
::integer($data)) {
443 if (CRM_Utils_Rule
::positiveInteger($data)) {
448 case 'CommaSeparatedIntegers':
449 if (CRM_Utils_Rule
::commaSeparatedIntegers($data)) {
455 if (CRM_Utils_Rule
::boolean($data)) {
462 if (CRM_Utils_Rule
::numeric($data)) {
474 // a null date is valid
475 if (strlen(trim($data)) == 0) {
479 if (preg_match('/^\d{8}$/', $data) &&
480 CRM_Utils_Rule
::mysqlDate($data)
487 // a null timestamp is valid
488 if (strlen(trim($data)) == 0) {
492 if ((preg_match('/^\d{14}$/', $data) ||
493 preg_match('/^\d{8}$/', $data)
495 CRM_Utils_Rule
::mysqlDate($data)
501 case 'ContactReference':
503 if (strlen(trim($data)) == 0) {
507 if (CRM_Utils_Rule
::validContact($data)) {
512 case 'MysqlColumnNameOrAlias':
513 if (CRM_Utils_Rule
::mysqlColumnNameOrAlias($data)) {
518 case 'MysqlOrderByDirection':
519 if (CRM_Utils_Rule
::mysqlOrderByDirection($data)) {
520 return strtolower($data);
525 if (CRM_Utils_Rule
::mysqlOrderBy($data)) {
531 if (CRM_Utils_Rule
::checkExtensionKeyIsValid($data)) {
537 if (CRM_Utils_Rule
::json($data)) {
543 if (CRM_Utils_Rule
::alphanumeric($data)) {
550 $data = htmlentities($data);
551 if ($isThrowException) {
552 throw new CRM_Core_Exception("$name (value: $data) is not of the type $type");
554 CRM_Core_Error
::fatal("$name (value: $data) is not of the type $type");
561 * Preg_replace_callback for mysqlOrderByFieldFunction escape.
563 * Add backticks around the field name.
565 * @param string $clause
569 public static function mysqlOrderByFieldFunctionCallback($clause) {
570 return preg_replace('/field\((\w*)/', 'field(`${1}`', $clause);
574 * preg_replace_callback for MysqlOrderBy escape.
576 public static function mysqlOrderByCallback($matches) {
578 $matches = str_replace('`', '', $matches);
581 if (isset($matches[1]) && $matches[1]) {
582 $output .= '`' . $matches[1] . '`.';
586 if (isset($matches[2]) && $matches[2]) {
587 $output .= '`' . $matches[2] . '`';
591 if (isset($matches[3]) && $matches[3]) {
592 $output .= ' ' . $matches[3];
599 * Get list of avaliable Data Types for Option Groups
603 public static function dataTypes() {
613 return array_combine($types, $types);