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 CRM_Core_Error::fatal() 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 CRM_Core_Error
::fatal(
330 $type . " is not a recognised (camel cased) data type."
335 // @todo Use exceptions instead of CRM_Core_Error::fatal().
337 $data = htmlentities($data);
339 CRM_Core_Error
::fatal("$data is not of the type $type");
345 * Verify that a variable is of a given type.
348 * The value to validate.
349 * @param string $type
350 * The type to validate against.
352 * If TRUE, the operation will CRM_Core_Error::fatal() on invalid data.
353 * @param string $name
354 * The name of the attribute
355 * @param bool $isThrowException
356 * Should an exception be thrown rather than a using a deprecated fatal error.
359 * The data, escaped if necessary
361 * @throws \CRM_Core_Exception
363 public static function validate($data, $type, $abort = TRUE, $name = 'One of parameters ', $isThrowException = TRUE) {
369 'CommaSeparatedIntegers',
380 'MysqlColumnNameOrAlias',
381 'MysqlOrderByDirection',
388 if (!in_array($type, $possibleTypes)) {
389 if ($isThrowException) {
390 throw new CRM_Core_Exception(ts('Invalid type, must be one of : ' . implode($possibleTypes)));
392 CRM_Core_Error
::fatal(ts('Invalid type, must be one of : ' . implode($possibleTypes)));
397 if (CRM_Utils_Rule
::integer($data)) {
403 if (CRM_Utils_Rule
::positiveInteger($data)) {
410 if (CRM_Utils_Rule
::numeric($data)) {
423 // a null timestamp is valid
424 if (strlen(trim($data)) == 0) {
428 if ((preg_match('/^\d{14}$/', $data) ||
429 preg_match('/^\d{8}$/', $data)
431 CRM_Utils_Rule
::mysqlDate($data)
437 case 'ContactReference':
439 if (strlen(trim($data)) == 0) {
443 if (CRM_Utils_Rule
::validContact($data)) {
448 case 'MysqlOrderByDirection':
449 if (CRM_Utils_Rule
::mysqlOrderByDirection($data)) {
450 return strtolower($data);
455 if (CRM_Utils_Rule
::checkExtensionKeyIsValid($data)) {
461 $check = lcfirst($type);
462 if (CRM_Utils_Rule
::$check($data)) {
468 $data = htmlentities($data);
469 if ($isThrowException) {
470 throw new CRM_Core_Exception("$name (value: $data) is not of the type $type");
472 CRM_Core_Error
::fatal("$name (value: $data) is not of the type $type");
479 * Preg_replace_callback for mysqlOrderByFieldFunction escape.
481 * Add backticks around the field name.
483 * @param string $clause
487 public static function mysqlOrderByFieldFunctionCallback($clause) {
488 return preg_replace('/field\((\w*)/', 'field(`${1}`', $clause);
492 * preg_replace_callback for MysqlOrderBy escape.
494 public static function mysqlOrderByCallback($matches) {
496 $matches = str_replace('`', '', $matches);
499 if (isset($matches[1]) && $matches[1]) {
500 $output .= '`' . $matches[1] . '`.';
504 if (isset($matches[2]) && $matches[2]) {
505 $output .= '`' . $matches[2] . '`';
509 if (isset($matches[3]) && $matches[3]) {
510 $output .= ' ' . $matches[3];
517 * Get list of avaliable Data Types for Option Groups
521 public static function dataTypes() {
531 return array_combine($types, $types);