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
42 public static function create(&$customParams) {
43 if (empty($customParams) ||
44 !is_array($customParams)
49 $paramFieldsExtendContactForEntities = [];
51 foreach ($customParams as $tableName => $tables) {
52 foreach ($tables as $index => $fields) {
61 foreach ($fields as $field) {
63 $entityID = $field['entity_id'];
64 $hookID = $field['custom_group_id'];
65 $isMultiple = $field['is_multiple'];
66 if (array_key_exists('id', $field)) {
67 $sqlOP = "UPDATE $tableName ";
68 $where = " WHERE id = %{$count}";
69 $params[$count] = [$field['id'], 'Integer'];
74 $sqlOP = "INSERT INTO $tableName ";
80 // fix the value before we store it
81 $value = $field['value'];
82 $type = $field['type'];
86 if (is_array($value)) {
87 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
90 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
91 //fix for multi select state, CRM-3437
92 $mulValues = explode(',', $value);
94 foreach ($mulValues as $key => $stateVal) {
96 $states['state_province'] = trim($stateVal);
98 CRM_Utils_Array
::lookupValue($states, 'state_province',
99 CRM_Core_PseudoConstant
::stateProvince(), TRUE
101 if (empty($states['state_province_id'])) {
102 CRM_Utils_Array
::lookupValue($states, 'state_province',
103 CRM_Core_PseudoConstant
::stateProvinceAbbreviation(), TRUE
106 $validStates[] = CRM_Utils_Array
::value('state_province_id', $states);
108 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
115 // using type of timestamp allows us to sneak in a null into db
116 // gross but effective hack
127 if (is_array($value)) {
128 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
131 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
132 //fix for multi select country, CRM-3437
133 $mulValues = explode(',', $value);
134 $validCountries = [];
135 foreach ($mulValues as $key => $countryVal) {
137 $countries['country'] = trim($countryVal);
138 CRM_Utils_Array
::lookupValue($countries, 'country',
139 CRM_Core_PseudoConstant
::country(), TRUE
141 if (empty($countries['country_id'])) {
142 CRM_Utils_Array
::lookupValue($countries, 'country',
143 CRM_Core_PseudoConstant
::countryIsoCode(), TRUE
146 $validCountries[] = CRM_Utils_Array
::value('country_id', $countries);
148 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
155 // using type of timestamp allows us to sneak in a null into db
156 // gross but effective hack
166 if (!$field['file_id']) {
167 CRM_Core_Error
::fatal();
170 // need to add/update civicrm_entity_file
171 $entityFileDAO = new CRM_Core_DAO_EntityFile();
172 $entityFileDAO->file_id
= $field['file_id'];
173 $entityFileDAO->find(TRUE);
175 $entityFileDAO->entity_table
= $field['table_name'];
176 $entityFileDAO->entity_id
= $field['entity_id'];
177 $entityFileDAO->file_id
= $field['file_id'];
178 $entityFileDAO->save();
179 $value = $field['file_id'];
184 $value = CRM_Utils_Date
::isoToMysql($value);
188 if (is_numeric($value)) {
196 case 'ContactReference':
197 if ($value == NULL) {
205 case 'RichTextEditor':
211 $value = CRM_Utils_String
::strtoboolstr($value);
212 if ($value === FALSE) {
220 if ($value === 'null') {
221 // when unsetting a value to null, we don't need to validate the type
222 // https://projectllr.atlassian.net/browse/VGQBMP-20
223 $set[$field['column_name']] = $value;
226 $set[$field['column_name']] = "%{$count}";
227 $params[$count] = [$value, $type];
231 $fieldExtends = CRM_Utils_Array
::value('extends', $field);
233 CRM_Utils_Array
::value('entity_table', $field) == 'civicrm_contact'
234 ||
$fieldExtends == 'Contact'
235 ||
$fieldExtends == 'Individual'
236 ||
$fieldExtends == 'Organization'
237 ||
$fieldExtends == 'Household'
239 $paramFieldsExtendContactForEntities[$entityID]['custom_' . CRM_Utils_Array
::value('custom_field_id', $field)] = CRM_Utils_Array
::value('custom_field_id', $field);
245 foreach ($set as $n => $v) {
246 $setClause[] = "$n = $v";
248 $setClause = implode(',', $setClause);
250 // do this only for insert
251 $set['entity_id'] = "%{$count}";
252 $params[$count] = [$entityID, 'Integer'];
255 $fieldNames = implode(',', CRM_Utils_Type
::escapeAll(array_keys($set), 'MysqlColumnNameOrAlias'));
256 $fieldValues = implode(',', array_values($set));
257 $query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
258 // for multiple values we dont do on duplicate key update
260 $query .= " ON DUPLICATE KEY UPDATE $setClause";
264 $query = "$sqlOP SET $setClause $where";
266 $dao = CRM_Core_DAO
::executeQuery($query, $params);
268 CRM_Utils_Hook
::custom($hookOP,
277 if (!empty($paramFieldsExtendContactForEntities)) {
278 CRM_Contact_BAO_Contact
::updateGreetingsOnTokenFieldChange($paramFieldsExtendContactForEntities, ['contact_id' => $entityID]);
283 * Given a field return the mysql data type associated with it.
285 * @param string $type
286 * @param int $maxLength
289 * the mysql data store placeholder
291 public static function fieldToSQLType($type, $maxLength = 255) {
292 if (!isset($maxLength) ||
293 !is_numeric($maxLength) ||
302 return "varchar($maxLength)";
310 // the below three are FK's, and have constraints added to them
312 case 'ContactReference':
313 case 'StateProvince':
316 return 'int unsigned';
322 return 'decimal(20,2)';
325 case 'RichTextEditor':
332 CRM_Core_Error
::fatal();
337 * @param array $params
338 * @param $entityTable
339 * @param int $entityID
341 public static function store(&$params, $entityTable, $entityID) {
343 foreach ($params as $fieldID => $param) {
344 foreach ($param as $index => $customValue) {
346 'entity_table' => $entityTable,
347 'entity_id' => $entityID,
348 'value' => $customValue['value'],
349 'type' => $customValue['type'],
350 'custom_field_id' => $customValue['custom_field_id'],
351 'custom_group_id' => $customValue['custom_group_id'],
352 'table_name' => $customValue['table_name'],
353 'column_name' => $customValue['column_name'],
354 'is_multiple' => CRM_Utils_Array
::value('is_multiple', $customValue),
355 'file_id' => $customValue['file_id'],
358 // Fix Date type to be timestamp, since that is how we store in db.
359 if ($cvParam['type'] == 'Date') {
360 $cvParam['type'] = 'Timestamp';
363 if (!empty($customValue['id'])) {
364 $cvParam['id'] = $customValue['id'];
366 if (!array_key_exists($customValue['table_name'], $cvParams)) {
367 $cvParams[$customValue['table_name']] = [];
370 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
371 $cvParams[$customValue['table_name']][$index] = [];
374 $cvParams[$customValue['table_name']][$index][] = $cvParam;
377 if (!empty($cvParams)) {
378 self
::create($cvParams);
383 * Post process function.
385 * @param array $params
386 * @param $entityTable
387 * @param int $entityID
388 * @param $customFieldExtends
390 public static function postProcess(&$params, $entityTable, $entityID, $customFieldExtends) {
391 $customData = CRM_Core_BAO_CustomField
::postProcess($params,
396 if (!empty($customData)) {
397 self
::store($customData, $entityTable, $entityID);
402 * Return an array of all custom values associated with an entity.
404 * @param int $entityID
405 * Identification number of the entity.
406 * @param string $entityType
407 * Type of entity that the entityID corresponds to, specified.
408 * as a string with format "'<EntityName>'". Comma separated
409 * list may be used to specify OR matches. Allowable values
410 * are enumerated types in civicrm_custom_group.extends field.
411 * Optional. Default value assumes entityID references a
413 * @param array $fieldIDs
414 * Optional list of fieldIDs that we want to retrieve. If this.
415 * is set the entityType is ignored
417 * @param bool $formatMultiRecordField
418 * @param array $DTparams - CRM-17810 dataTable params for the multiValued custom fields.
421 * Array of custom values for the entity with key=>value
422 * pairs specified as civicrm_custom_field.id => custom value.
423 * Empty array if no custom values found.
425 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE, $DTparams = NULL) {
427 // adding this here since an empty contact id could have serious repurcussions
428 // like looping forever
429 CRM_Core_Error
::fatal('Please file an issue with the backtrace');
435 $cond[] = "cg.extends IN ( '$entityType' )";
440 $fieldIDList = implode(',', $fieldIDs);
441 $cond[] = "cf.id IN ( $fieldIDList )";
444 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
446 $cond = implode(' AND ', $cond);
448 $limit = $orderBy = '';
449 if (!empty($DTparams['rowCount']) && $DTparams['rowCount'] > 0) {
450 $limit = " LIMIT " . CRM_Utils_Type
::escape($DTparams['offset'], 'Integer') . ", " . CRM_Utils_Type
::escape($DTparams['rowCount'], 'Integer');
452 if (!empty($DTparams['sort'])) {
453 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($DTparams['sort'], 'String');
456 // First find all the fields that extend this type of entity.
458 SELECT cg.table_name,
463 cf.data_type as fieldDataType
464 FROM civicrm_custom_group cg,
465 civicrm_custom_field cf
466 WHERE cf.custom_group_id = cg.id
471 $dao = CRM_Core_DAO
::executeQuery($query);
473 $select = $fields = $isMultiple = [];
475 while ($dao->fetch()) {
476 if (!array_key_exists($dao->table_name
, $select)) {
477 $fields[$dao->table_name
] = [];
478 $select[$dao->table_name
] = [];
480 $fields[$dao->table_name
][] = $dao->fieldID
;
481 $select[$dao->table_name
][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
482 $isMultiple[$dao->table_name
] = $dao->is_multiple ?
TRUE : FALSE;
483 $file[$dao->table_name
][$dao->fieldID
] = $dao->fieldDataType
;
486 $result = $sortedResult = [];
487 foreach ($select as $tableName => $clauses) {
488 if (!empty($DTparams['sort'])) {
489 $query = CRM_Core_DAO
::executeQuery("SELECT id FROM {$tableName} WHERE entity_id = {$entityID}");
491 while ($query->fetch()) {
492 $sortedResult["{$query->id}"] = $count;
497 $query = "SELECT SQL_CALC_FOUND_ROWS id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID {$orderBy} {$limit}";
498 $dao = CRM_Core_DAO
::executeQuery($query);
499 if (!empty($DTparams)) {
500 $result['count'] = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
502 while ($dao->fetch()) {
503 foreach ($fields[$tableName] as $fieldID) {
504 $fieldName = "custom_{$fieldID}";
505 if ($isMultiple[$tableName]) {
506 if ($formatMultiRecordField) {
507 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
510 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
514 $result[$fieldID] = $dao->$fieldName;
519 if (!empty($sortedResult)) {
520 $result['sortedResult'] = $sortedResult;
526 * Take in an array of entityID, custom_XXX => value
527 * and set the value in the appropriate table. Should also be able
528 * to set the value to null. Follows api parameter/return conventions
532 * @param array $params
537 public static function setValues(&$params) {
538 // For legacy reasons, accept this param in either format
539 if (empty($params['entityID']) && !empty($params['entity_id'])) {
540 $params['entityID'] = $params['entity_id'];
543 if (!isset($params['entityID']) ||
!CRM_Utils_Type
::validate($params['entityID'], 'Integer', FALSE)) {
544 return CRM_Core_Error
::createAPIError(ts('entity_id needs to be set and of type Integer'));
547 // first collect all the id/value pairs. The format is:
548 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
550 foreach ($params as $n => $v) {
551 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($n, TRUE)) {
552 $fieldID = (int ) $customFieldInfo[0];
553 if (CRM_Utils_Type
::escape($fieldID, 'Integer', FALSE) === NULL) {
554 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
558 if (!array_key_exists($fieldID, $fieldValues)) {
559 $fieldValues[$fieldID] = [];
562 if ($customFieldInfo[1]) {
563 $id = (int ) $customFieldInfo[1];
565 $fieldValues[$fieldID][] = [
572 $fieldIDList = implode(',', array_keys($fieldValues));
574 // format it so that we can just use create
576 SELECT cg.table_name as table_name ,
578 cg.is_multiple as is_multiple,
579 cg.extends as extends,
580 cf.column_name as column_name,
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 // Format null values correctly
596 if ($fieldValue['value'] === NULL ||
$fieldValue['value'] === '') {
602 $fieldValue['value'] = '';
606 $fieldValue['value'] = NULL;
609 case 'StateProvince':
613 $fieldValue['value'] = (int) 0;
617 // Ensure that value is of the right data type
618 elseif (CRM_Utils_Type
::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
619 return CRM_Core_Error
::createAPIError(ts('value: %1 is not of the right field data type: %2',
621 1 => $fieldValue['value'],
622 2 => $dao->data_type
,
628 'entity_id' => $params['entityID'],
629 'value' => $fieldValue['value'],
631 'custom_field_id' => $dao->cf_id
,
632 'custom_group_id' => $dao->cg_id
,
633 'table_name' => $dao->table_name
,
634 'column_name' => $dao->column_name
,
635 'is_multiple' => $dao->is_multiple
,
636 'extends' => $dao->extends,
639 if (!empty($params['id'])) {
640 $cvParam['id'] = $params['id'];
643 if ($cvParam['type'] == 'File') {
644 $cvParam['file_id'] = $fieldValue['value'];
647 if (!array_key_exists($dao->table_name
, $cvParams)) {
648 $cvParams[$dao->table_name
] = [];
651 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name
])) {
652 $cvParams[$dao->table_name
][$fieldValue['id']] = [];
655 if ($fieldValue['id'] > 0) {
656 $cvParam['id'] = $fieldValue['id'];
658 $cvParams[$dao->table_name
][$fieldValue['id']][] = $cvParam;
662 if (!empty($cvParams)) {
663 self
::create($cvParams);
664 return ['is_error' => 0, 'result' => 1];
667 return CRM_Core_Error
::createAPIError(ts('Unknown error'));
671 * Take in an array of entityID, custom_ID
672 * and gets the value from the appropriate table.
674 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
675 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
677 * Entity Type will be inferred by the custom fields you request
678 * Specify $params['entityType'] if you do not supply any custom fields to return
679 * and entity type is other than Contact
683 * @param array $params
688 public static function &getValues(&$params) {
689 if (empty($params)) {
692 if (!isset($params['entityID']) ||
693 CRM_Utils_Type
::escape($params['entityID'],
697 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
700 // first collect all the ids. The format is:
703 foreach ($params as $n => $v) {
705 if (substr($n, 0, 7) == 'custom_') {
706 $idx = substr($n, 7);
707 if (CRM_Utils_Type
::escape($idx, 'Integer', FALSE) === NULL) {
708 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
712 $fieldIDs[] = (int ) $idx;
716 $default = ['Contact', 'Individual', 'Household', 'Organization'];
717 if (!($type = CRM_Utils_Array
::value('entityType', $params)) ||
718 in_array($params['entityType'], $default)
723 $entities = CRM_Core_SelectValues
::customGroupExtends();
724 if (!array_key_exists($type, $entities)) {
725 if (in_array($type, $entities)) {
726 $type = $entities[$type];
727 if (in_array($type, $default)) {
732 return CRM_Core_Error
::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
737 $values = self
::getEntityValues($params['entityID'],
741 if (empty($values)) {
742 // note that this behaviour is undesirable from an API point of view - it should return an empty array
743 // since this is also called by the merger code & not sure the consequences of changing
744 // are just handling undoing this in the api layer. ie. converting the error back into a success
747 'error_message' => 'No values found for the specified entity ID and custom field(s).',
754 'entityID' => $params['entityID'],
756 foreach ($values as $id => $value) {
757 $result["custom_{$id}"] = $value;