3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 foreach ($customParams as $tableName => $tables) {
50 foreach ($tables as $index => $fields) {
59 foreach ($fields as $field) {
61 $entityID = $field['entity_id'];
62 $hookID = $field['custom_group_id'];
63 $isMultiple = $field['is_multiple'];
64 if (array_key_exists('id', $field)) {
65 $sqlOP = "UPDATE $tableName ";
66 $where = " WHERE id = %{$count}";
67 $params[$count] = array($field['id'], 'Integer');
72 $sqlOP = "INSERT INTO $tableName ";
78 // fix the value before we store it
79 $value = $field['value'];
80 $type = $field['type'];
84 if (is_array($value)) {
85 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
88 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
89 //fix for multi select state, CRM-3437
90 $mulValues = explode(',', $value);
91 $validStates = array();
92 foreach ($mulValues as $key => $stateVal) {
94 $states['state_province'] = trim($stateVal);
96 CRM_Utils_Array
::lookupValue($states, 'state_province',
97 CRM_Core_PseudoConstant
::stateProvince(), TRUE
99 if (empty($states['state_province_id'])) {
100 CRM_Utils_Array
::lookupValue($states, 'state_province',
101 CRM_Core_PseudoConstant
::stateProvinceAbbreviation(), TRUE
104 $validStates[] = CRM_Utils_Array
::value('state_province_id', $states);
106 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
113 // using type of timestamp allows us to sneak in a null into db
114 // gross but effective hack
125 $mulValues = explode(',', $value);
126 if (is_array($value)) {
127 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
130 elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
131 //fix for multi select country, CRM-3437
132 $mulValues = explode(',', $value);
133 $validCountries = array();
134 foreach ($mulValues as $key => $countryVal) {
135 $countries = array();
136 $countries['country'] = trim($countryVal);
137 CRM_Utils_Array
::lookupValue($countries, 'country',
138 CRM_Core_PseudoConstant
::country(), TRUE
140 if (empty($countries['country_id'])) {
141 CRM_Utils_Array
::lookupValue($countries, 'country',
142 CRM_Core_PseudoConstant
::countryIsoCode(), TRUE
145 $validCountries[] = CRM_Utils_Array
::value('country_id', $states);
147 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
154 // using type of timestamp allows us to sneak in a null into db
155 // gross but effective hack
165 if (!$field['file_id']) {
166 CRM_Core_Error
::fatal();
169 // need to add/update civicrm_entity_file
170 $entityFileDAO = new CRM_Core_DAO_EntityFile();
171 $entityFileDAO->file_id
= $field['file_id'];
172 $entityFileDAO->find(TRUE);
174 $entityFileDAO->entity_table
= $field['table_name'];
175 $entityFileDAO->entity_id
= $field['entity_id'];
176 $entityFileDAO->file_id
= $field['file_id'];
177 $entityFileDAO->save();
178 $entityFileDAO->free();
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 (strtolower($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] = array($value, $type);
233 $setClause = array();
234 foreach ($set as $n => $v) {
235 $setClause[] = "$n = $v";
237 $setClause = implode(',', $setClause);
239 // do this only for insert
240 $set['entity_id'] = "%{$count}";
241 $params[$count] = array($entityID, 'Integer');
244 $fieldNames = implode(',', array_keys($set));
245 $fieldValues = implode(',', array_values($set));
246 $query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
247 // for multiple values we dont do on duplicate key update
249 $query .= " ON DUPLICATE KEY UPDATE $setClause";
253 $query = "$sqlOP SET $setClause $where";
255 $dao = CRM_Core_DAO
::executeQuery($query, $params);
257 CRM_Utils_Hook
::custom($hookOP,
268 * Given a field return the mysql data type associated with it.
270 * @param string $type
271 * @param int $maxLength
274 * the mysql data store placeholder
276 public static function fieldToSQLType($type, $maxLength = 255) {
277 if (!isset($maxLength) ||
278 !is_numeric($maxLength) ||
287 return "varchar($maxLength)";
295 // the below three are FK's, and have constraints added to them
297 case 'ContactReference':
298 case 'StateProvince':
301 return 'int unsigned';
307 return 'decimal(20,2)';
310 case 'RichTextEditor':
317 CRM_Core_Error
::fatal();
322 * @param array $params
323 * @param $entityTable
324 * @param int $entityID
326 public static function store(&$params, $entityTable, $entityID) {
328 foreach ($params as $fieldID => $param) {
329 foreach ($param as $index => $customValue) {
331 'entity_table' => $entityTable,
332 'entity_id' => $entityID,
333 'value' => $customValue['value'],
334 'type' => $customValue['type'],
335 'custom_field_id' => $customValue['custom_field_id'],
336 'custom_group_id' => $customValue['custom_group_id'],
337 'table_name' => $customValue['table_name'],
338 'column_name' => $customValue['column_name'],
339 'is_multiple' => CRM_Utils_Array
::value('is_multiple', $customValue),
340 'file_id' => $customValue['file_id'],
343 // Fix Date type to be timestamp, since that is how we store in db.
344 if ($cvParam['type'] == 'Date') {
345 $cvParam['type'] = 'Timestamp';
348 if (!empty($customValue['id'])) {
349 $cvParam['id'] = $customValue['id'];
351 if (!array_key_exists($customValue['table_name'], $cvParams)) {
352 $cvParams[$customValue['table_name']] = array();
355 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
356 $cvParams[$customValue['table_name']][$index] = array();
359 $cvParams[$customValue['table_name']][$index][] = $cvParam;
362 if (!empty($cvParams)) {
363 self
::create($cvParams);
368 * Post process function.
370 * @param array $params
371 * @param $entityTable
372 * @param int $entityID
373 * @param $customFieldExtends
375 public static function postProcess(&$params, $entityTable, $entityID, $customFieldExtends) {
376 $customData = CRM_Core_BAO_CustomField
::postProcess($params,
381 if (!empty($customData)) {
382 self
::store($customData, $entityTable, $entityID);
387 * Return an array of all custom values associated with an entity.
389 * @param int $entityID
390 * Identification number of the entity.
391 * @param string $entityType
392 * Type of entity that the entityID corresponds to, specified.
393 * as a string with format "'<EntityName>'". Comma separated
394 * list may be used to specify OR matches. Allowable values
395 * are enumerated types in civicrm_custom_group.extends field.
396 * Optional. Default value assumes entityID references a
398 * @param array $fieldIDs
399 * Optional list of fieldIDs that we want to retrieve. If this.
400 * is set the entityType is ignored
402 * @param bool $formatMultiRecordField
403 * @param array $DTparams - CRM-17810 dataTable params for the multiValued custom fields.
406 * Array of custom values for the entity with key=>value
407 * pairs specified as civicrm_custom_field.id => custom value.
408 * Empty array if no custom values found.
410 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE, $DTparams = NULL) {
412 // adding this here since an empty contact id could have serious repurcussions
413 // like looping forever
414 CRM_Core_Error
::fatal('Please file an issue with the backtrace');
420 $cond[] = "cg.extends IN ( '$entityType' )";
425 $fieldIDList = implode(',', $fieldIDs);
426 $cond[] = "cf.id IN ( $fieldIDList )";
429 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
431 $cond = implode(' AND ', $cond);
434 if (!empty($DTparams['rowCount']) && $DTparams['rowCount'] > 0) {
435 $limit = " LIMIT " . CRM_Utils_Type
::escape($DTparams['offset'], 'Integer') . ", " . CRM_Utils_Type
::escape($DTparams['rowCount'], 'Integer');
439 if (!empty($DTparams['sort'])) {
440 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($DTparams['sort'], 'String');
443 // First find all the fields that extend this type of entity.
445 SELECT cg.table_name,
450 cf.data_type as fieldDataType
451 FROM civicrm_custom_group cg,
452 civicrm_custom_field cf
453 WHERE cf.custom_group_id = cg.id
458 $dao = CRM_Core_DAO
::executeQuery($query);
460 $select = $fields = $isMultiple = array();
462 while ($dao->fetch()) {
463 if (!array_key_exists($dao->table_name
, $select)) {
464 $fields[$dao->table_name
] = array();
465 $select[$dao->table_name
] = array();
467 $fields[$dao->table_name
][] = $dao->fieldID
;
468 $select[$dao->table_name
][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
469 $isMultiple[$dao->table_name
] = $dao->is_multiple ?
TRUE : FALSE;
470 $file[$dao->table_name
][$dao->fieldID
] = $dao->fieldDataType
;
474 foreach ($select as $tableName => $clauses) {
475 $query = "SELECT SQL_CALC_FOUND_ROWS id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID {$orderBy} {$limit}";
476 $dao = CRM_Core_DAO
::executeQuery($query);
477 $result['count'] = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
478 while ($dao->fetch()) {
479 foreach ($fields[$tableName] as $fieldID) {
480 $fieldName = "custom_{$fieldID}";
481 if ($isMultiple[$tableName]) {
482 if ($formatMultiRecordField) {
483 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
486 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
490 $result[$fieldID] = $dao->$fieldName;
499 * Take in an array of entityID, custom_XXX => value
500 * and set the value in the appropriate table. Should also be able
501 * to set the value to null. Follows api parameter/return conventions
505 * @param array $params
510 public static function setValues(&$params) {
512 if (!isset($params['entityID']) ||
513 CRM_Utils_Type
::escape($params['entityID'], 'Integer', FALSE) === NULL
515 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
518 // first collect all the id/value pairs. The format is:
519 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
521 $fieldValues = array();
522 foreach ($params as $n => $v) {
523 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($n, TRUE)) {
524 $fieldID = (int ) $customFieldInfo[0];
525 if (CRM_Utils_Type
::escape($fieldID, 'Integer', FALSE) === NULL) {
526 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
530 if (!array_key_exists($fieldID, $fieldValues)) {
531 $fieldValues[$fieldID] = array();
534 if ($customFieldInfo[1]) {
535 $id = (int ) $customFieldInfo[1];
537 $fieldValues[$fieldID][] = array(
544 $fieldIDList = implode(',', array_keys($fieldValues));
546 // format it so that we can just use create
548 SELECT cg.table_name as table_name ,
550 cg.is_multiple as is_multiple,
551 cf.column_name as column_name,
553 cf.data_type as data_type
554 FROM civicrm_custom_group cg,
555 civicrm_custom_field cf
556 WHERE cf.custom_group_id = cg.id
557 AND cf.id IN ( $fieldIDList )
560 $dao = CRM_Core_DAO
::executeQuery($sql);
563 while ($dao->fetch()) {
564 $dataType = $dao->data_type
== 'Date' ?
'Timestamp' : $dao->data_type
;
565 foreach ($fieldValues[$dao->cf_id
] as $fieldValue) {
566 // Format null values correctly
567 if ($fieldValue['value'] === NULL ||
$fieldValue['value'] === '') {
573 $fieldValue['value'] = '';
577 $fieldValue['value'] = NULL;
580 case 'StateProvince':
584 $fieldValue['value'] = (int) 0;
588 // Ensure that value is of the right data type
589 elseif (CRM_Utils_Type
::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
590 return CRM_Core_Error
::createAPIError(ts('value: %1 is not of the right field data type: %2',
592 1 => $fieldValue['value'],
593 2 => $dao->data_type
,
599 'entity_id' => $params['entityID'],
600 'value' => $fieldValue['value'],
602 'custom_field_id' => $dao->cf_id
,
603 'custom_group_id' => $dao->cg_id
,
604 'table_name' => $dao->table_name
,
605 'column_name' => $dao->column_name
,
606 'is_multiple' => $dao->is_multiple
,
609 if ($cvParam['type'] == 'File') {
610 $cvParam['file_id'] = $fieldValue['value'];
613 if (!array_key_exists($dao->table_name
, $cvParams)) {
614 $cvParams[$dao->table_name
] = array();
617 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name
])) {
618 $cvParams[$dao->table_name
][$fieldValue['id']] = array();
621 if ($fieldValue['id'] > 0) {
622 $cvParam['id'] = $fieldValue['id'];
624 $cvParams[$dao->table_name
][$fieldValue['id']][] = $cvParam;
628 if (!empty($cvParams)) {
629 self
::create($cvParams);
630 return array('is_error' => 0, 'result' => 1);
633 return CRM_Core_Error
::createAPIError(ts('Unknown error'));
637 * Take in an array of entityID, custom_ID
638 * and gets the value from the appropriate table.
640 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
641 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
643 * Entity Type will be inferred by the custom fields you request
644 * Specify $params['entityType'] if you do not supply any custom fields to return
645 * and entity type is other than Contact
649 * @param array $params
654 public static function &getValues(&$params) {
655 if (empty($params)) {
658 if (!isset($params['entityID']) ||
659 CRM_Utils_Type
::escape($params['entityID'],
663 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
666 // first collect all the ids. The format is:
669 foreach ($params as $n => $v) {
671 if (substr($n, 0, 7) == 'custom_') {
672 $idx = substr($n, 7);
673 if (CRM_Utils_Type
::escape($idx, 'Integer', FALSE) === NULL) {
674 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
678 $fieldIDs[] = (int ) $idx;
682 $default = array('Contact', 'Individual', 'Household', 'Organization');
683 if (!($type = CRM_Utils_Array
::value('entityType', $params)) ||
684 in_array($params['entityType'], $default)
689 $entities = CRM_Core_SelectValues
::customGroupExtends();
690 if (!array_key_exists($type, $entities)) {
691 if (in_array($type, $entities)) {
692 $type = $entities[$type];
693 if (in_array($type, $default)) {
698 return CRM_Core_Error
::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
703 $values = self
::getEntityValues($params['entityID'],
707 if (empty($values)) {
708 // note that this behaviour is undesirable from an API point of view - it should return an empty array
709 // since this is also called by the merger code & not sure the consequences of changing
710 // are just handling undoing this in the api layer. ie. converting the error back into a success
713 'error_message' => 'No values found for the specified entity ID and custom field(s).',
720 'entityID' => $params['entityID'],
722 foreach ($values as $id => $value) {
723 $result["custom_{$id}"] = $value;