3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Utils_Type
{
36 // @TODO What's the point of these constants? Backwards compatibility?
38 // These are used for field size (<input type=text size=2>), but redundant TWO=2
39 // usages are rare and should be eliminated. See CRM-18810.
55 * Maximum size of a MySQL BLOB or TEXT column in bytes.
57 const BLOB_SIZE
= 65535;
60 * Maximum value of a MySQL signed INT column.
62 const INT_MAX
= 2147483647;
65 * Gets the string representation for a data type.
68 * Integer number identifying the data type.
71 * String identifying the data type, e.g. 'Int' or 'String'.
73 public static function typeToString($type) {
74 // @todo Use constants in the case statements, e.g. "case T_INT:".
75 // @todo return directly, instead of assigning a value.
76 // @todo Use a lookup array, as a property or as a local variable.
113 $string = 'Timestamp';
133 $string = 'Mediumblob';
137 return (isset($string)) ?
$string : "";
142 * An array of type in the form 'type name' => 'int representing type'
144 public static function getValidTypes() {
146 'Int' => self
::T_INT
,
147 'String' => self
::T_STRING
,
148 'Enum' => self
::T_ENUM
,
149 'Date' => self
::T_DATE
,
150 'Time' => self
::T_TIME
,
151 'Boolean' => self
::T_BOOLEAN
,
152 'Text' => self
::T_TEXT
,
153 'Blob' => self
::T_BLOB
,
154 'Timestamp' => self
::T_TIMESTAMP
,
155 'Float' => self
::T_FLOAT
,
156 'Money' => self
::T_MONEY
,
157 'Email' => self
::T_EMAIL
,
158 'Mediumblob' => self
::T_MEDIUMBLOB
,
163 * Get the data_type for the field.
165 * @param array $fieldMetadata
166 * Metadata about the field.
170 public static function getDataTypeFromFieldMetadata($fieldMetadata) {
171 if (isset($fieldMetadata['data_type'])) {
172 return $fieldMetadata['data_type'];
174 if (empty($fieldMetadata['type'])) {
175 // I would prefer to throw an e-notice but there is some,
176 // probably unnecessary logic, that only retrieves activity fields
177 // if they are 'in the profile' and probably they are not 'in'
178 // until they are added - which might lead to ? who knows!
181 return self
::typeToString($fieldMetadata['type']);
185 * Helper function to call escape on arrays.
189 public static function escapeAll($data, $type, $abort = TRUE) {
190 foreach ($data as $key => $value) {
191 $data[$key] = CRM_Utils_Type
::escape($value, $type, $abort);
197 * Helper function to call validate on arrays
201 public static function validateAll($data, $type, $abort = TRUE) {
202 foreach ($data as $key => $value) {
203 $data[$key] = CRM_Utils_Type
::validate($value, $type, $abort);
209 * Verify that a variable is of a given type, and apply a bit of processing.
212 * The value to be verified/escaped.
213 * @param string $type
214 * The type to verify against.
216 * If TRUE, the operation will throw an CRM_Core_Exception on invalid data.
219 * The data, escaped if necessary.
220 * @throws CRM_Core_Exception
222 public static function escape($data, $type, $abort = TRUE) {
231 case 'ContactReference':
232 case 'MysqlOrderByDirection':
233 $validatedData = self
::validate($data, $type, $abort);
234 if (isset($validatedData)) {
235 return $validatedData;
239 // CRM-8925 for custom fields of this type
241 case 'StateProvince':
242 // Handle multivalued data in delimited or array format
243 if (is_array($data) ||
(strpos($data, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE)) {
245 foreach (CRM_Utils_Array
::explodePadded($data) as $item) {
246 if (!CRM_Utils_Rule
::positiveInteger($item)) {
254 elseif (CRM_Utils_Rule
::positiveInteger($data)) {
260 if (CRM_Utils_Rule
::positiveInteger($data)) {
266 if (CRM_Utils_Rule
::url($data = trim($data))) {
272 if (CRM_Utils_Rule
::boolean($data)) {
280 return CRM_Core_DAO
::escapeString(self
::validate($data, $type, $abort));
282 case 'MysqlColumnNameOrAlias':
283 if (CRM_Utils_Rule
::mysqlColumnNameOrAlias($data)) {
284 $data = str_replace('`', '', $data);
285 $parts = explode('.', $data);
286 $data = '`' . implode('`.`', $parts) . '`';
293 if (CRM_Utils_Rule
::mysqlOrderBy($data)) {
294 $parts = explode(',', $data);
296 // The field() syntax is tricky here because it uses commas & when
297 // we separate by them we break it up. But we want to keep the clauses in order.
298 // so we just clumsily re-assemble it. Test cover exists.
299 $fieldClauseStart = NULL;
300 foreach ($parts as $index => &$part) {
301 if (substr($part, 0, 6) === 'field(') {
302 // Looking to escape a string like 'field(contribution_status_id,3,4,5) asc'
303 // to 'field(`contribution_status_id`,3,4,5) asc'
304 $fieldClauseStart = $index;
307 if ($fieldClauseStart !== NULL) {
308 // this is part of the list of field options. Concatenate it back on.
309 $parts[$fieldClauseStart] .= ',' . $part;
310 unset($parts[$index]);
311 if (!strstr($parts[$fieldClauseStart], ')')) {
312 // we have not reached the end of the list.
315 // We have the last piece of the field() clause, time to escape it.
316 $parts[$fieldClauseStart] = self
::mysqlOrderByFieldFunctionCallback($parts[$fieldClauseStart]);
317 $fieldClauseStart = NULL;
322 $part = preg_replace_callback('/^(?:(?:((?:`[\w-]{1,64}`|[\w-]{1,64}))(?:\.))?(`[\w-]{1,64}`|[\w-]{1,64})(?: (asc|desc))?)$/i', ['CRM_Utils_Type', 'mysqlOrderByCallback'], trim($part));
324 return implode(', ', $parts);
329 throw new CRM_Core_Exception(
330 $type . " is not a recognised (camel cased) data type."
334 // @todo Use exceptions instead of CRM_Core_Error::fatal().
336 $data = htmlentities($data);
338 throw new CRM_Core_Exception("$data is not of the type $type");
344 * Verify that a variable is of a given type.
347 * The value to validate.
348 * @param string $type
349 * The type to validate against.
351 * If TRUE, the operation will CRM_Core_Error::fatal() on invalid data.
352 * @param string $name
353 * The name of the attribute
354 * @param bool $isThrowException
355 * Should an exception be thrown rather than a using a deprecated fatal error.
358 * The data, escaped if necessary
360 * @throws \CRM_Core_Exception
362 public static function validate($data, $type, $abort = TRUE, $name = 'One of parameters ', $isThrowException = TRUE) {
368 'CommaSeparatedIntegers',
379 'MysqlColumnNameOrAlias',
380 'MysqlOrderByDirection',
387 if (!in_array($type, $possibleTypes)) {
388 if ($isThrowException) {
389 throw new CRM_Core_Exception(ts('Invalid type, must be one of : ' . implode($possibleTypes)));
391 CRM_Core_Error
::fatal(ts('Invalid type, must be one of : ' . implode($possibleTypes)));
396 if (CRM_Utils_Rule
::integer($data)) {
402 if (CRM_Utils_Rule
::positiveInteger($data)) {
409 if (CRM_Utils_Rule
::numeric($data)) {
422 // a null timestamp is valid
423 if (strlen(trim($data)) == 0) {
427 if ((preg_match('/^\d{14}$/', $data) ||
428 preg_match('/^\d{8}$/', $data)
430 CRM_Utils_Rule
::mysqlDate($data)
436 case 'ContactReference':
438 if (strlen(trim($data)) == 0) {
442 if (CRM_Utils_Rule
::validContact($data)) {
447 case 'MysqlOrderByDirection':
448 if (CRM_Utils_Rule
::mysqlOrderByDirection($data)) {
449 return strtolower($data);
454 if (CRM_Utils_Rule
::checkExtensionKeyIsValid($data)) {
460 $check = lcfirst($type);
461 if (CRM_Utils_Rule
::$check($data)) {
467 $data = htmlentities($data);
468 if ($isThrowException) {
469 throw new CRM_Core_Exception("$name (value: $data) is not of the type $type");
471 CRM_Core_Error
::fatal("$name (value: $data) is not of the type $type");
478 * Preg_replace_callback for mysqlOrderByFieldFunction escape.
480 * Add backticks around the field name.
482 * @param string $clause
486 public static function mysqlOrderByFieldFunctionCallback($clause) {
487 return preg_replace('/field\((\w*)/', 'field(`${1}`', $clause);
491 * preg_replace_callback for MysqlOrderBy escape.
493 public static function mysqlOrderByCallback($matches) {
495 $matches = str_replace('`', '', $matches);
498 if (isset($matches[1]) && $matches[1]) {
499 $output .= '`' . $matches[1] . '`.';
503 if (isset($matches[2]) && $matches[2]) {
504 $output .= '`' . $matches[2] . '`';
508 if (isset($matches[3]) && $matches[3]) {
509 $output .= ' ' . $matches[3];
516 * Get list of avaliable Data Types for Option Groups
520 public static function dataTypes() {
530 return array_combine($types, $types);