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_Core_BAO_CustomValueTable
{
20 * @param array $customParams
21 * @param string $parentOperation Operation being taken on the parent entity.
22 * If we know the parent entity is doing an insert we can skip the
23 * ON DUPLICATE UPDATE - which improves performance and reduces deadlocks.
29 public static function create($customParams, $parentOperation = NULL) {
30 if (empty($customParams) ||
31 !is_array($customParams)
36 $paramFieldsExtendContactForEntities = [];
38 foreach ($customParams as $tableName => $tables) {
39 foreach ($tables as $index => $fields) {
49 $firstField = reset($fields);
50 $entityID = $firstField['entity_id'];
51 $hookID = $firstField['custom_group_id'];
52 $isMultiple = $firstField['is_multiple'];
53 if (array_key_exists('id', $firstField)) {
54 $sqlOP = "UPDATE $tableName ";
55 $where = " WHERE id = %{$count}";
56 $params[$count] = [$firstField['id'], 'Integer'];
61 $sqlOP = "INSERT INTO $tableName ";
66 CRM_Utils_Hook
::customPre($hookOP,
72 foreach ($fields as $field) {
73 // fix the value before we store it
74 $value = $field['value'];
75 $type = $field['type'];
79 if (is_array($value)) {
80 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
83 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
84 //fix for multi select state, CRM-3437
85 $mulValues = explode(',', $value);
87 foreach ($mulValues as $key => $stateVal) {
89 $states['state_province'] = trim($stateVal);
91 CRM_Utils_Array
::lookupValue($states, 'state_province',
92 CRM_Core_PseudoConstant
::stateProvince(), TRUE
94 if (empty($states['state_province_id'])) {
95 CRM_Utils_Array
::lookupValue($states, 'state_province',
96 CRM_Core_PseudoConstant
::stateProvinceAbbreviation(), TRUE
99 $validStates[] = $states['state_province_id'] ??
NULL;
101 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
108 // using type of timestamp allows us to sneak in a null into db
109 // gross but effective hack
120 if (is_array($value)) {
121 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
124 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
125 //fix for multi select country, CRM-3437
126 $mulValues = explode(',', $value);
127 $validCountries = [];
128 foreach ($mulValues as $key => $countryVal) {
130 $countries['country'] = trim($countryVal);
131 CRM_Utils_Array
::lookupValue($countries, 'country',
132 CRM_Core_PseudoConstant
::country(), TRUE
134 if (empty($countries['country_id'])) {
135 CRM_Utils_Array
::lookupValue($countries, 'country',
136 CRM_Core_PseudoConstant
::countryIsoCode(), TRUE
139 $validCountries[] = $countries['country_id'] ??
NULL;
141 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
148 // using type of timestamp allows us to sneak in a null into db
149 // gross but effective hack
159 if (!$field['file_id']) {
160 throw new CRM_Core_Exception('Missing parameter file_id');
163 // need to add/update civicrm_entity_file
164 $entityFileDAO = new CRM_Core_DAO_EntityFile();
165 $entityFileDAO->file_id
= $field['file_id'];
166 $entityFileDAO->find(TRUE);
168 $entityFileDAO->entity_table
= $field['table_name'];
169 $entityFileDAO->entity_id
= $field['entity_id'];
170 $entityFileDAO->file_id
= $field['file_id'];
171 $entityFileDAO->save();
172 $value = $field['file_id'];
177 $value = CRM_Utils_Date
::isoToMysql($value);
181 if (is_numeric($value)) {
189 case 'ContactReference':
190 if ($value == NULL) {
198 case 'RichTextEditor':
204 $value = CRM_Utils_String
::strtoboolstr($value);
205 if ($value === FALSE) {
213 if ($value === 'null') {
214 // when unsetting a value to null, we don't need to validate the type
215 // https://projectllr.atlassian.net/browse/VGQBMP-20
216 $set[$field['column_name']] = $value;
219 $set[$field['column_name']] = "%{$count}";
220 $params[$count] = [$value, $type];
224 $fieldExtends = $field['extends'] ??
NULL;
226 CRM_Utils_Array
::value('entity_table', $field) == 'civicrm_contact'
227 ||
$fieldExtends == 'Contact'
228 ||
$fieldExtends == 'Individual'
229 ||
$fieldExtends == 'Organization'
230 ||
$fieldExtends == 'Household'
232 $paramFieldsExtendContactForEntities[$entityID]['custom_' . CRM_Utils_Array
::value('custom_field_id', $field)] = $field['custom_field_id'] ??
NULL;
238 foreach ($set as $n => $v) {
239 $setClause[] = "`$n` = $v";
241 $setClause = implode(',', $setClause);
243 // do this only for insert
244 $set['entity_id'] = "%{$count}";
245 $params[$count] = [$entityID, 'Integer'];
248 $fieldNames = implode(',', CRM_Utils_Type
::escapeAll(array_keys($set), 'MysqlColumnNameOrAlias'));
249 $fieldValues = implode(',', array_values($set));
250 $query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
251 // for multiple values we dont do on duplicate key update
252 if (!$isMultiple && $parentOperation !== 'create') {
253 $query .= " ON DUPLICATE KEY UPDATE $setClause";
257 $query = "$sqlOP SET $setClause $where";
259 $dao = CRM_Core_DAO
::executeQuery($query, $params);
261 CRM_Utils_Hook
::custom($hookOP,
270 if (!empty($paramFieldsExtendContactForEntities)) {
271 CRM_Contact_BAO_Contact
::updateGreetingsOnTokenFieldChange($paramFieldsExtendContactForEntities, ['contact_id' => $entityID]);
276 * Given a field return the mysql data type associated with it.
278 * @param string $type
279 * @param int $maxLength
282 * the mysql data store placeholder
284 public static function fieldToSQLType($type, $maxLength = 255) {
285 if (!isset($maxLength) ||
286 !is_numeric($maxLength) ||
295 return "varchar($maxLength)";
303 // the below three are FK's, and have constraints added to them
305 case 'ContactReference':
306 case 'StateProvince':
309 return 'int unsigned';
315 return 'decimal(20,2)';
318 case 'RichTextEditor':
325 throw new CRM_Core_Exception('Invalid Field Type');
330 * @param array $params
331 * @param $entityTable
332 * @param int $entityID
333 * @param string $parentOperation Operation being taken on the parent entity.
334 * If we know the parent entity is doing an insert we can skip the
335 * ON DUPLICATE UPDATE - which improves performance and reduces deadlocks.
339 public static function store($params, $entityTable, $entityID, $parentOperation = NULL) {
341 foreach ($params as $fieldID => $param) {
342 foreach ($param as $index => $customValue) {
344 'entity_table' => $entityTable,
345 'entity_id' => $entityID,
346 'value' => $customValue['value'],
347 'type' => $customValue['type'],
348 'custom_field_id' => $customValue['custom_field_id'],
349 'custom_group_id' => $customValue['custom_group_id'],
350 'table_name' => $customValue['table_name'],
351 'column_name' => $customValue['column_name'],
352 'is_multiple' => $customValue['is_multiple'] ??
NULL,
353 'file_id' => $customValue['file_id'],
356 // Fix Date type to be timestamp, since that is how we store in db.
357 if ($cvParam['type'] == 'Date') {
358 $cvParam['type'] = 'Timestamp';
361 if (!empty($customValue['id'])) {
362 $cvParam['id'] = $customValue['id'];
364 if (!array_key_exists($customValue['table_name'], $cvParams)) {
365 $cvParams[$customValue['table_name']] = [];
368 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
369 $cvParams[$customValue['table_name']][$index] = [];
372 $cvParams[$customValue['table_name']][$index][] = $cvParam;
375 if (!empty($cvParams)) {
376 self
::create($cvParams, $parentOperation);
381 * Post process function.
383 * @param array $params
384 * @param $entityTable
385 * @param int $entityID
386 * @param $customFieldExtends
388 public static function postProcess(&$params, $entityTable, $entityID, $customFieldExtends) {
389 $customData = CRM_Core_BAO_CustomField
::postProcess($params,
394 if (!empty($customData)) {
395 self
::store($customData, $entityTable, $entityID);
400 * Return an array of all custom values associated with an entity.
402 * @param int $entityID
403 * Identification number of the entity.
404 * @param string $entityType
405 * Type of entity that the entityID corresponds to, specified.
406 * as a string with format "'<EntityName>'". Comma separated
407 * list may be used to specify OR matches. Allowable values
408 * are enumerated types in civicrm_custom_group.extends field.
409 * Optional. Default value assumes entityID references a
411 * @param array $fieldIDs
412 * Optional list of fieldIDs that we want to retrieve. If this.
413 * is set the entityType is ignored
415 * @param bool $formatMultiRecordField
416 * @param array $DTparams - CRM-17810 dataTable params for the multiValued custom fields.
419 * Array of custom values for the entity with key=>value
420 * pairs specified as civicrm_custom_field.id => custom value.
421 * Empty array if no custom values found.
422 * @throws CRM_Core_Exception
424 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE, $DTparams = NULL) {
426 // adding this here since an empty contact id could have serious repurcussions
427 // like looping forever
428 throw new CRM_Core_Exception('Please file an issue with the backtrace');
434 $cond[] = "cg.extends IN ( '$entityType' )";
439 $fieldIDList = implode(',', $fieldIDs);
440 $cond[] = "cf.id IN ( $fieldIDList )";
443 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
445 $cond = implode(' AND ', $cond);
447 $limit = $orderBy = '';
448 if (!empty($DTparams['rowCount']) && $DTparams['rowCount'] > 0) {
449 $limit = " LIMIT " . CRM_Utils_Type
::escape($DTparams['offset'], 'Integer') . ", " . CRM_Utils_Type
::escape($DTparams['rowCount'], 'Integer');
451 if (!empty($DTparams['sort'])) {
452 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($DTparams['sort'], 'String');
455 // First find all the fields that extend this type of entity.
457 SELECT cg.table_name,
462 cf.data_type as fieldDataType
463 FROM civicrm_custom_group cg,
464 civicrm_custom_field cf
465 WHERE cf.custom_group_id = cg.id
470 $dao = CRM_Core_DAO
::executeQuery($query);
472 $select = $fields = $isMultiple = [];
474 while ($dao->fetch()) {
475 if (!array_key_exists($dao->table_name
, $select)) {
476 $fields[$dao->table_name
] = [];
477 $select[$dao->table_name
] = [];
479 $fields[$dao->table_name
][] = $dao->fieldID
;
480 $select[$dao->table_name
][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
481 $isMultiple[$dao->table_name
] = (bool) $dao->is_multiple
;
482 $file[$dao->table_name
][$dao->fieldID
] = $dao->fieldDataType
;
485 $result = $sortedResult = [];
486 foreach ($select as $tableName => $clauses) {
487 if (!empty($DTparams['sort'])) {
488 $query = CRM_Core_DAO
::executeQuery("SELECT id FROM {$tableName} WHERE entity_id = {$entityID}");
490 while ($query->fetch()) {
491 $sortedResult["{$query->id}"] = $count;
496 $query = "SELECT SQL_CALC_FOUND_ROWS id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID {$orderBy} {$limit}";
497 $dao = CRM_Core_DAO
::executeQuery($query);
498 if (!empty($DTparams)) {
499 $result['count'] = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
501 while ($dao->fetch()) {
502 foreach ($fields[$tableName] as $fieldID) {
503 $fieldName = "custom_{$fieldID}";
504 if ($isMultiple[$tableName]) {
505 if ($formatMultiRecordField) {
506 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
509 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
513 $result[$fieldID] = $dao->$fieldName;
518 if (!empty($sortedResult)) {
519 $result['sortedResult'] = $sortedResult;
525 * Take in an array of entityID, custom_XXX => value
526 * and set the value in the appropriate table. Should also be able
527 * to set the value to null. Follows api parameter/return conventions
531 * @param array $params
536 public static function setValues(&$params) {
537 // For legacy reasons, accept this param in either format
538 if (empty($params['entityID']) && !empty($params['entity_id'])) {
539 $params['entityID'] = $params['entity_id'];
542 if (!isset($params['entityID']) ||
!CRM_Utils_Type
::validate($params['entityID'], 'Integer', FALSE)) {
543 return CRM_Core_Error
::createAPIError(ts('entity_id needs to be set and of type Integer'));
546 // first collect all the id/value pairs. The format is:
547 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
549 foreach ($params as $n => $v) {
550 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($n, TRUE)) {
551 $fieldID = (int ) $customFieldInfo[0];
552 if (CRM_Utils_Type
::escape($fieldID, 'Integer', FALSE) === NULL) {
553 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
557 if (!array_key_exists($fieldID, $fieldValues)) {
558 $fieldValues[$fieldID] = [];
561 if ($customFieldInfo[1]) {
562 $id = (int ) $customFieldInfo[1];
564 $fieldValues[$fieldID][] = [
571 $fieldIDList = implode(',', array_keys($fieldValues));
573 // format it so that we can just use create
575 SELECT cg.table_name as table_name ,
577 cg.is_multiple as is_multiple,
578 cg.extends as extends,
579 cf.column_name as column_name,
581 cf.html_type as html_type ,
582 cf.data_type as data_type
583 FROM civicrm_custom_group cg,
584 civicrm_custom_field cf
585 WHERE cf.custom_group_id = cg.id
586 AND cf.id IN ( $fieldIDList )
589 $dao = CRM_Core_DAO
::executeQuery($sql);
592 while ($dao->fetch()) {
593 $dataType = $dao->data_type
== 'Date' ?
'Timestamp' : $dao->data_type
;
594 foreach ($fieldValues[$dao->cf_id
] as $fieldValue) {
595 // Serialize array values
596 if (is_array($fieldValue['value']) && CRM_Core_BAO_CustomField
::isSerialized($dao)) {
597 $fieldValue['value'] = CRM_Utils_Array
::implodePadded($fieldValue['value']);
599 // Format null values correctly
600 if ($fieldValue['value'] === NULL ||
$fieldValue['value'] === '') {
606 $fieldValue['value'] = '';
610 $fieldValue['value'] = NULL;
613 case 'StateProvince':
617 $fieldValue['value'] = (int) 0;
621 // Ensure that value is of the right data type
622 elseif (CRM_Utils_Type
::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
623 return CRM_Core_Error
::createAPIError(ts('value: %1 is not of the right field data type: %2',
625 1 => $fieldValue['value'],
626 2 => $dao->data_type
,
632 'entity_id' => $params['entityID'],
633 'value' => $fieldValue['value'],
635 'custom_field_id' => $dao->cf_id
,
636 'custom_group_id' => $dao->cg_id
,
637 'table_name' => $dao->table_name
,
638 'column_name' => $dao->column_name
,
639 'is_multiple' => $dao->is_multiple
,
640 'extends' => $dao->extends,
643 if (!empty($params['id'])) {
644 $cvParam['id'] = $params['id'];
647 if ($cvParam['type'] == 'File') {
648 $cvParam['file_id'] = $fieldValue['value'];
651 if (!array_key_exists($dao->table_name
, $cvParams)) {
652 $cvParams[$dao->table_name
] = [];
655 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name
])) {
656 $cvParams[$dao->table_name
][$fieldValue['id']] = [];
659 if ($fieldValue['id'] > 0) {
660 $cvParam['id'] = $fieldValue['id'];
662 $cvParams[$dao->table_name
][$fieldValue['id']][] = $cvParam;
666 if (!empty($cvParams)) {
667 self
::create($cvParams);
668 return ['is_error' => 0, 'result' => 1];
671 return CRM_Core_Error
::createAPIError(ts('Unknown error'));
675 * Take in an array of entityID, custom_ID
676 * and gets the value from the appropriate table.
678 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
679 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
681 * Entity Type will be inferred by the custom fields you request
682 * Specify $params['entityType'] if you do not supply any custom fields to return
683 * and entity type is other than Contact
687 * @param array $params
692 public static function &getValues(&$params) {
693 if (empty($params)) {
696 if (!isset($params['entityID']) ||
697 CRM_Utils_Type
::escape($params['entityID'],
701 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
704 // first collect all the ids. The format is:
707 foreach ($params as $n => $v) {
709 if (substr($n, 0, 7) == 'custom_') {
710 $idx = substr($n, 7);
711 if (CRM_Utils_Type
::escape($idx, 'Integer', FALSE) === NULL) {
712 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
716 $fieldIDs[] = (int ) $idx;
720 $default = ['Contact', 'Individual', 'Household', 'Organization'];
721 if (!($type = CRM_Utils_Array
::value('entityType', $params)) ||
722 in_array($params['entityType'], $default)
727 $entities = CRM_Core_SelectValues
::customGroupExtends();
728 if (!array_key_exists($type, $entities)) {
729 if (in_array($type, $entities)) {
730 $type = $entities[$type];
731 if (in_array($type, $default)) {
736 return CRM_Core_Error
::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
741 $values = self
::getEntityValues($params['entityID'],
745 if (empty($values)) {
746 // note that this behaviour is undesirable from an API point of view - it should return an empty array
747 // since this is also called by the merger code & not sure the consequences of changing
748 // are just handling undoing this in the api layer. ie. converting the error back into a success
751 'error_message' => 'No values found for the specified entity ID and custom field(s).',
758 'entityID' => $params['entityID'],
760 foreach ($values as $id => $value) {
761 $result["custom_{$id}"] = $value;