3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
35 class CRM_Core_BAO_CustomValueTable
{
38 * @param array $customParams
39 * @param string $parentOperation Operation being taken on the parent entity.
40 * If we know the parent entity is doing an insert we can skip the
41 * ON DUPLICATE UPDATE - which improves performance and reduces deadlocks.
47 public static function create($customParams, $parentOperation = NULL) {
48 if (empty($customParams) ||
49 !is_array($customParams)
54 $paramFieldsExtendContactForEntities = [];
56 foreach ($customParams as $tableName => $tables) {
57 foreach ($tables as $index => $fields) {
66 foreach ($fields as $field) {
68 $entityID = $field['entity_id'];
69 $hookID = $field['custom_group_id'];
70 $isMultiple = $field['is_multiple'];
71 if (array_key_exists('id', $field)) {
72 $sqlOP = "UPDATE $tableName ";
73 $where = " WHERE id = %{$count}";
74 $params[$count] = [$field['id'], 'Integer'];
79 $sqlOP = "INSERT INTO $tableName ";
85 // fix the value before we store it
86 $value = $field['value'];
87 $type = $field['type'];
91 if (is_array($value)) {
92 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
95 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
96 //fix for multi select state, CRM-3437
97 $mulValues = explode(',', $value);
99 foreach ($mulValues as $key => $stateVal) {
101 $states['state_province'] = trim($stateVal);
103 CRM_Utils_Array
::lookupValue($states, 'state_province',
104 CRM_Core_PseudoConstant
::stateProvince(), TRUE
106 if (empty($states['state_province_id'])) {
107 CRM_Utils_Array
::lookupValue($states, 'state_province',
108 CRM_Core_PseudoConstant
::stateProvinceAbbreviation(), TRUE
111 $validStates[] = CRM_Utils_Array
::value('state_province_id', $states);
113 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
120 // using type of timestamp allows us to sneak in a null into db
121 // gross but effective hack
132 if (is_array($value)) {
133 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
136 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
137 //fix for multi select country, CRM-3437
138 $mulValues = explode(',', $value);
139 $validCountries = [];
140 foreach ($mulValues as $key => $countryVal) {
142 $countries['country'] = trim($countryVal);
143 CRM_Utils_Array
::lookupValue($countries, 'country',
144 CRM_Core_PseudoConstant
::country(), TRUE
146 if (empty($countries['country_id'])) {
147 CRM_Utils_Array
::lookupValue($countries, 'country',
148 CRM_Core_PseudoConstant
::countryIsoCode(), TRUE
151 $validCountries[] = CRM_Utils_Array
::value('country_id', $countries);
153 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
160 // using type of timestamp allows us to sneak in a null into db
161 // gross but effective hack
171 if (!$field['file_id']) {
172 CRM_Core_Error
::fatal();
175 // need to add/update civicrm_entity_file
176 $entityFileDAO = new CRM_Core_DAO_EntityFile();
177 $entityFileDAO->file_id
= $field['file_id'];
178 $entityFileDAO->find(TRUE);
180 $entityFileDAO->entity_table
= $field['table_name'];
181 $entityFileDAO->entity_id
= $field['entity_id'];
182 $entityFileDAO->file_id
= $field['file_id'];
183 $entityFileDAO->save();
184 $value = $field['file_id'];
189 $value = CRM_Utils_Date
::isoToMysql($value);
193 if (is_numeric($value)) {
201 case 'ContactReference':
202 if ($value == NULL) {
210 case 'RichTextEditor':
216 $value = CRM_Utils_String
::strtoboolstr($value);
217 if ($value === FALSE) {
225 if ($value === 'null') {
226 // when unsetting a value to null, we don't need to validate the type
227 // https://projectllr.atlassian.net/browse/VGQBMP-20
228 $set[$field['column_name']] = $value;
231 $set[$field['column_name']] = "%{$count}";
232 $params[$count] = [$value, $type];
236 $fieldExtends = CRM_Utils_Array
::value('extends', $field);
238 CRM_Utils_Array
::value('entity_table', $field) == 'civicrm_contact'
239 ||
$fieldExtends == 'Contact'
240 ||
$fieldExtends == 'Individual'
241 ||
$fieldExtends == 'Organization'
242 ||
$fieldExtends == 'Household'
244 $paramFieldsExtendContactForEntities[$entityID]['custom_' . CRM_Utils_Array
::value('custom_field_id', $field)] = CRM_Utils_Array
::value('custom_field_id', $field);
250 foreach ($set as $n => $v) {
251 $setClause[] = "$n = $v";
253 $setClause = implode(',', $setClause);
255 // do this only for insert
256 $set['entity_id'] = "%{$count}";
257 $params[$count] = [$entityID, 'Integer'];
260 $fieldNames = implode(',', CRM_Utils_Type
::escapeAll(array_keys($set), 'MysqlColumnNameOrAlias'));
261 $fieldValues = implode(',', array_values($set));
262 $query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
263 // for multiple values we dont do on duplicate key update
264 if (!$isMultiple && $parentOperation !== 'create') {
265 $query .= " ON DUPLICATE KEY UPDATE $setClause";
269 $query = "$sqlOP SET $setClause $where";
271 $dao = CRM_Core_DAO
::executeQuery($query, $params);
273 CRM_Utils_Hook
::custom($hookOP,
282 if (!empty($paramFieldsExtendContactForEntities)) {
283 CRM_Contact_BAO_Contact
::updateGreetingsOnTokenFieldChange($paramFieldsExtendContactForEntities, ['contact_id' => $entityID]);
288 * Given a field return the mysql data type associated with it.
290 * @param string $type
291 * @param int $maxLength
294 * the mysql data store placeholder
296 public static function fieldToSQLType($type, $maxLength = 255) {
297 if (!isset($maxLength) ||
298 !is_numeric($maxLength) ||
307 return "varchar($maxLength)";
315 // the below three are FK's, and have constraints added to them
317 case 'ContactReference':
318 case 'StateProvince':
321 return 'int unsigned';
327 return 'decimal(20,2)';
330 case 'RichTextEditor':
337 CRM_Core_Error
::fatal();
342 * @param array $params
343 * @param $entityTable
344 * @param int $entityID
345 * @param string $parentOperation Operation being taken on the parent entity.
346 * If we know the parent entity is doing an insert we can skip the
347 * ON DUPLICATE UPDATE - which improves performance and reduces deadlocks.
351 public static function store($params, $entityTable, $entityID, $parentOperation = NULL) {
353 foreach ($params as $fieldID => $param) {
354 foreach ($param as $index => $customValue) {
356 'entity_table' => $entityTable,
357 'entity_id' => $entityID,
358 'value' => $customValue['value'],
359 'type' => $customValue['type'],
360 'custom_field_id' => $customValue['custom_field_id'],
361 'custom_group_id' => $customValue['custom_group_id'],
362 'table_name' => $customValue['table_name'],
363 'column_name' => $customValue['column_name'],
364 'is_multiple' => CRM_Utils_Array
::value('is_multiple', $customValue),
365 'file_id' => $customValue['file_id'],
368 // Fix Date type to be timestamp, since that is how we store in db.
369 if ($cvParam['type'] == 'Date') {
370 $cvParam['type'] = 'Timestamp';
373 if (!empty($customValue['id'])) {
374 $cvParam['id'] = $customValue['id'];
376 if (!array_key_exists($customValue['table_name'], $cvParams)) {
377 $cvParams[$customValue['table_name']] = [];
380 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
381 $cvParams[$customValue['table_name']][$index] = [];
384 $cvParams[$customValue['table_name']][$index][] = $cvParam;
387 if (!empty($cvParams)) {
388 self
::create($cvParams, $parentOperation);
393 * Post process function.
395 * @param array $params
396 * @param $entityTable
397 * @param int $entityID
398 * @param $customFieldExtends
400 public static function postProcess(&$params, $entityTable, $entityID, $customFieldExtends) {
401 $customData = CRM_Core_BAO_CustomField
::postProcess($params,
406 if (!empty($customData)) {
407 self
::store($customData, $entityTable, $entityID);
412 * Return an array of all custom values associated with an entity.
414 * @param int $entityID
415 * Identification number of the entity.
416 * @param string $entityType
417 * Type of entity that the entityID corresponds to, specified.
418 * as a string with format "'<EntityName>'". Comma separated
419 * list may be used to specify OR matches. Allowable values
420 * are enumerated types in civicrm_custom_group.extends field.
421 * Optional. Default value assumes entityID references a
423 * @param array $fieldIDs
424 * Optional list of fieldIDs that we want to retrieve. If this.
425 * is set the entityType is ignored
427 * @param bool $formatMultiRecordField
428 * @param array $DTparams - CRM-17810 dataTable params for the multiValued custom fields.
431 * Array of custom values for the entity with key=>value
432 * pairs specified as civicrm_custom_field.id => custom value.
433 * Empty array if no custom values found.
435 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE, $DTparams = NULL) {
437 // adding this here since an empty contact id could have serious repurcussions
438 // like looping forever
439 CRM_Core_Error
::fatal('Please file an issue with the backtrace');
445 $cond[] = "cg.extends IN ( '$entityType' )";
450 $fieldIDList = implode(',', $fieldIDs);
451 $cond[] = "cf.id IN ( $fieldIDList )";
454 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
456 $cond = implode(' AND ', $cond);
458 $limit = $orderBy = '';
459 if (!empty($DTparams['rowCount']) && $DTparams['rowCount'] > 0) {
460 $limit = " LIMIT " . CRM_Utils_Type
::escape($DTparams['offset'], 'Integer') . ", " . CRM_Utils_Type
::escape($DTparams['rowCount'], 'Integer');
462 if (!empty($DTparams['sort'])) {
463 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($DTparams['sort'], 'String');
466 // First find all the fields that extend this type of entity.
468 SELECT cg.table_name,
473 cf.data_type as fieldDataType
474 FROM civicrm_custom_group cg,
475 civicrm_custom_field cf
476 WHERE cf.custom_group_id = cg.id
481 $dao = CRM_Core_DAO
::executeQuery($query);
483 $select = $fields = $isMultiple = [];
485 while ($dao->fetch()) {
486 if (!array_key_exists($dao->table_name
, $select)) {
487 $fields[$dao->table_name
] = [];
488 $select[$dao->table_name
] = [];
490 $fields[$dao->table_name
][] = $dao->fieldID
;
491 $select[$dao->table_name
][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
492 $isMultiple[$dao->table_name
] = $dao->is_multiple ?
TRUE : FALSE;
493 $file[$dao->table_name
][$dao->fieldID
] = $dao->fieldDataType
;
496 $result = $sortedResult = [];
497 foreach ($select as $tableName => $clauses) {
498 if (!empty($DTparams['sort'])) {
499 $query = CRM_Core_DAO
::executeQuery("SELECT id FROM {$tableName} WHERE entity_id = {$entityID}");
501 while ($query->fetch()) {
502 $sortedResult["{$query->id}"] = $count;
507 $query = "SELECT SQL_CALC_FOUND_ROWS id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID {$orderBy} {$limit}";
508 $dao = CRM_Core_DAO
::executeQuery($query);
509 if (!empty($DTparams)) {
510 $result['count'] = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
512 while ($dao->fetch()) {
513 foreach ($fields[$tableName] as $fieldID) {
514 $fieldName = "custom_{$fieldID}";
515 if ($isMultiple[$tableName]) {
516 if ($formatMultiRecordField) {
517 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
520 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
524 $result[$fieldID] = $dao->$fieldName;
529 if (!empty($sortedResult)) {
530 $result['sortedResult'] = $sortedResult;
536 * Take in an array of entityID, custom_XXX => value
537 * and set the value in the appropriate table. Should also be able
538 * to set the value to null. Follows api parameter/return conventions
542 * @param array $params
547 public static function setValues(&$params) {
548 // For legacy reasons, accept this param in either format
549 if (empty($params['entityID']) && !empty($params['entity_id'])) {
550 $params['entityID'] = $params['entity_id'];
553 if (!isset($params['entityID']) ||
!CRM_Utils_Type
::validate($params['entityID'], 'Integer', FALSE)) {
554 return CRM_Core_Error
::createAPIError(ts('entity_id needs to be set and of type Integer'));
557 // first collect all the id/value pairs. The format is:
558 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
560 foreach ($params as $n => $v) {
561 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($n, TRUE)) {
562 $fieldID = (int ) $customFieldInfo[0];
563 if (CRM_Utils_Type
::escape($fieldID, 'Integer', FALSE) === NULL) {
564 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
568 if (!array_key_exists($fieldID, $fieldValues)) {
569 $fieldValues[$fieldID] = [];
572 if ($customFieldInfo[1]) {
573 $id = (int ) $customFieldInfo[1];
575 $fieldValues[$fieldID][] = [
582 $fieldIDList = implode(',', array_keys($fieldValues));
584 // format it so that we can just use create
586 SELECT cg.table_name as table_name ,
588 cg.is_multiple as is_multiple,
589 cg.extends as extends,
590 cf.column_name as column_name,
592 cf.data_type as data_type
593 FROM civicrm_custom_group cg,
594 civicrm_custom_field cf
595 WHERE cf.custom_group_id = cg.id
596 AND cf.id IN ( $fieldIDList )
599 $dao = CRM_Core_DAO
::executeQuery($sql);
602 while ($dao->fetch()) {
603 $dataType = $dao->data_type
== 'Date' ?
'Timestamp' : $dao->data_type
;
604 foreach ($fieldValues[$dao->cf_id
] as $fieldValue) {
605 // Format null values correctly
606 if ($fieldValue['value'] === NULL ||
$fieldValue['value'] === '') {
612 $fieldValue['value'] = '';
616 $fieldValue['value'] = NULL;
619 case 'StateProvince':
623 $fieldValue['value'] = (int) 0;
627 // Ensure that value is of the right data type
628 elseif (CRM_Utils_Type
::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
629 return CRM_Core_Error
::createAPIError(ts('value: %1 is not of the right field data type: %2',
631 1 => $fieldValue['value'],
632 2 => $dao->data_type
,
638 'entity_id' => $params['entityID'],
639 'value' => $fieldValue['value'],
641 'custom_field_id' => $dao->cf_id
,
642 'custom_group_id' => $dao->cg_id
,
643 'table_name' => $dao->table_name
,
644 'column_name' => $dao->column_name
,
645 'is_multiple' => $dao->is_multiple
,
646 'extends' => $dao->extends,
649 if (!empty($params['id'])) {
650 $cvParam['id'] = $params['id'];
653 if ($cvParam['type'] == 'File') {
654 $cvParam['file_id'] = $fieldValue['value'];
657 if (!array_key_exists($dao->table_name
, $cvParams)) {
658 $cvParams[$dao->table_name
] = [];
661 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name
])) {
662 $cvParams[$dao->table_name
][$fieldValue['id']] = [];
665 if ($fieldValue['id'] > 0) {
666 $cvParam['id'] = $fieldValue['id'];
668 $cvParams[$dao->table_name
][$fieldValue['id']][] = $cvParam;
672 if (!empty($cvParams)) {
673 self
::create($cvParams);
674 return ['is_error' => 0, 'result' => 1];
677 return CRM_Core_Error
::createAPIError(ts('Unknown error'));
681 * Take in an array of entityID, custom_ID
682 * and gets the value from the appropriate table.
684 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
685 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
687 * Entity Type will be inferred by the custom fields you request
688 * Specify $params['entityType'] if you do not supply any custom fields to return
689 * and entity type is other than Contact
693 * @param array $params
698 public static function &getValues(&$params) {
699 if (empty($params)) {
702 if (!isset($params['entityID']) ||
703 CRM_Utils_Type
::escape($params['entityID'],
707 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
710 // first collect all the ids. The format is:
713 foreach ($params as $n => $v) {
715 if (substr($n, 0, 7) == 'custom_') {
716 $idx = substr($n, 7);
717 if (CRM_Utils_Type
::escape($idx, 'Integer', FALSE) === NULL) {
718 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
722 $fieldIDs[] = (int ) $idx;
726 $default = ['Contact', 'Individual', 'Household', 'Organization'];
727 if (!($type = CRM_Utils_Array
::value('entityType', $params)) ||
728 in_array($params['entityType'], $default)
733 $entities = CRM_Core_SelectValues
::customGroupExtends();
734 if (!array_key_exists($type, $entities)) {
735 if (in_array($type, $entities)) {
736 $type = $entities[$type];
737 if (in_array($type, $default)) {
742 return CRM_Core_Error
::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
747 $values = self
::getEntityValues($params['entityID'],
751 if (empty($values)) {
752 // note that this behaviour is undesirable from an API point of view - it should return an empty array
753 // since this is also called by the merger code & not sure the consequences of changing
754 // are just handling undoing this in the api layer. ie. converting the error back into a success
757 'error_message' => 'No values found for the specified entity ID and custom field(s).',
764 'entityID' => $params['entityID'],
766 foreach ($values as $id => $value) {
767 $result["custom_{$id}"] = $value;