3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Core_BAO_CustomValueTable
{
37 static function create(&$customParams) {
38 if (empty($customParams) ||
39 !is_array($customParams)
44 foreach ($customParams as $tableName => $tables) {
45 foreach ($tables as $index => $fields) {
54 foreach ($fields as $field) {
56 $entityID = $field['entity_id'];
57 $hookID = $field['custom_group_id'];
58 $isMultiple = $field['is_multiple'];
59 if (array_key_exists('id', $field)) {
60 $sqlOP = "UPDATE $tableName ";
61 $where = " WHERE id = %{$count}";
62 $params[$count] = array($field['id'], 'Integer');
67 $sqlOP = "INSERT INTO $tableName ";
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)) {
84 //fix for multi select state, CRM-3437
85 $mulValues = explode(',', $value);
86 $validStates = array();
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'];
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
117 if (is_array($value)) {
118 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
121 elseif (!is_numeric($value)) {
122 //fix for multi select country, CRM-3437
123 $mulValues = explode(',', $value);
124 $validCountries = array();
125 foreach ($mulValues as $key => $countryVal) {
126 $countries = array();
127 $countries['country'] = trim($countryVal);
128 CRM_Utils_Array
::lookupValue($countries, 'country',
129 CRM_Core_PseudoConstant
::country(), TRUE
131 if (empty($countries['country_id'])) {
132 CRM_Utils_Array
::lookupValue($countries, 'country',
133 CRM_Core_PseudoConstant
::countryIsoCode(), TRUE
136 $validCountries[] = $countries['country_id'];
138 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
145 // using type of timestamp allows us to sneak in a null into db
146 // gross but effective hack
153 if (!$field['file_id']) {
154 CRM_Core_Error
::fatal();
157 // need to add/update civicrm_entity_file
158 $entityFileDAO = new CRM_Core_DAO_EntityFile();
159 $entityFileDAO->file_id
= $field['file_id'];
160 $entityFileDAO->find(TRUE);
162 $entityFileDAO->entity_table
= $field['table_name'];
163 $entityFileDAO->entity_id
= $field['entity_id'];
164 $entityFileDAO->file_id
= $field['file_id'];
165 $entityFileDAO->save();
166 $entityFileDAO->free();
167 $value = $field['file_id'];
172 $value = CRM_Utils_Date
::isoToMysql($value);
176 if (is_numeric($value)) {
184 case 'ContactReference':
185 if ($value == NULL) {
193 case 'RichTextEditor':
199 $value = CRM_Utils_String
::strtoboolstr($value);
200 if ($value === FALSE) {
208 $set[$field['column_name']] = "%{$count}";
209 $params[$count] = array($value, $type);
214 $setClause = array();
215 foreach ($set as $n => $v) {
216 $setClause[] = "$n = $v";
218 $setClause = implode(',', $setClause);
220 // do this only for insert
221 $set['entity_id'] = "%{$count}";
222 $params[$count] = array($entityID, 'Integer');
225 $fieldNames = implode(',', array_keys($set));
226 $fieldValues = implode(',', array_values($set));
227 $query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
228 // for multiple values we dont do on duplicate key update
230 $query .= " ON DUPLICATE KEY UPDATE $setClause";
234 $query = "$sqlOP SET $setClause $where";
236 $dao = CRM_Core_DAO
::executeQuery($query, $params);
238 CRM_Utils_Hook
::custom($hookOP,
249 * given a field return the mysql data type associated with it
251 * @param string $type the civicrm type string
253 * @param int $maxLength
255 * @return the mysql data store placeholder
259 public static function fieldToSQLType($type, $maxLength = 255) {
260 if (!isset($maxLength) ||
261 !is_numeric($maxLength) ||
270 return "varchar($maxLength)";
277 // the below three are FK's, and have constraints added to them
279 case 'ContactReference':
280 case 'StateProvince':
283 return 'int unsigned';
289 return 'decimal(20,2)';
292 case 'RichTextEditor':
299 CRM_Core_Error
::fatal();
303 static function store(&$params, $entityTable, $entityID) {
305 foreach ($params as $fieldID => $param) {
306 foreach ($param as $index => $customValue) {
308 'entity_table' => $entityTable,
309 'entity_id' => $entityID,
310 'value' => $customValue['value'],
311 'type' => $customValue['type'],
312 'custom_field_id' => $customValue['custom_field_id'],
313 'custom_group_id' => $customValue['custom_group_id'],
314 'table_name' => $customValue['table_name'],
315 'column_name' => $customValue['column_name'],
316 'is_multiple' => CRM_Utils_Array
::value('is_multiple', $customValue),
317 'file_id' => $customValue['file_id'],
320 // fix Date type to be timestamp, since that is how we store in db
321 if ($cvParam['type'] == 'Date') {
322 $cvParam['type'] = 'Timestamp';
325 if (!empty($customValue['id'])) {
326 $cvParam['id'] = $customValue['id'];
328 if (!array_key_exists($customValue['table_name'], $cvParams)) {
329 $cvParams[$customValue['table_name']] = array();
332 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
333 $cvParams[$customValue['table_name']][$index] = array();
336 $cvParams[$customValue['table_name']][$index][] = $cvParam;
339 if (!empty($cvParams)) {
340 self
::create($cvParams);
344 static function postProcess(&$params, &$customFields, $entityTable, $entityID, $customFieldExtends) {
345 $customData = CRM_Core_BAO_CustomField
::postProcess($params,
351 if (!empty($customData)) {
352 self
::store($customData, $entityTable, $entityID);
357 * Return an array of all custom values associated with an entity.
359 * @param int $entityID Identification number of the entity
360 * @param string $entityType Type of entity that the entityID corresponds to, specified
361 * as a string with format "'<EntityName>'". Comma separated
362 * list may be used to specify OR matches. Allowable values
363 * are enumerated types in civicrm_custom_group.extends field.
364 * Optional. Default value assumes entityID references a
366 * @param array $fieldIDs optional list of fieldIDs that we want to retrieve. If this
367 * is set the entityType is ignored
369 * @param bool $formatMultiRecordField
371 * @return array $fields Array of custom values for the entity with key=>value
372 * pairs specified as civicrm_custom_field.id => custom value.
373 * Empty array if no custom values found.
377 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE) {
379 // adding this here since an empty contact id could have serious repurcussions
380 // like looping forever
381 CRM_Core_Error
::fatal('Please file an issue with the backtrace');
387 $cond[] = "cg.extends IN ( '$entityType' )";
392 $fieldIDList = implode(',', $fieldIDs);
393 $cond[] = "cf.id IN ( $fieldIDList )";
396 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
398 $cond = implode(' AND ', $cond);
400 // first find all the fields that extend this type of entity
402 SELECT cg.table_name,
407 cf.data_type as fieldDataType
408 FROM civicrm_custom_group cg,
409 civicrm_custom_field cf
410 WHERE cf.custom_group_id = cg.id
415 $dao = CRM_Core_DAO
::executeQuery($query);
417 $select = $fields = $isMultiple = array();
419 while ($dao->fetch()) {
420 if (!array_key_exists($dao->table_name
, $select)) {
421 $fields[$dao->table_name
] = array();
422 $select[$dao->table_name
] = array();
424 $fields[$dao->table_name
][] = $dao->fieldID
;
425 $select[$dao->table_name
][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
426 $isMultiple[$dao->table_name
] = $dao->is_multiple ?
TRUE : FALSE;
427 $file[$dao->table_name
][$dao->fieldID
] = $dao->fieldDataType
;
431 foreach ($select as $tableName => $clauses) {
432 $query = "SELECT id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID";
433 $dao = CRM_Core_DAO
::executeQuery($query);
434 while ($dao->fetch()) {
435 foreach ($fields[$tableName] as $fieldID) {
436 $fieldName = "custom_{$fieldID}";
437 if ($isMultiple[$tableName]) {
438 if ($formatMultiRecordField) {
439 if($file[$tableName][$fieldID] == 'File') {
440 if($fileid = $dao->$fieldName) {
441 $fileurl = CRM_Core_BAO_File
::paperIconAttachment($tableName,$entityID);
442 $result["{$dao->id}"]["{$fieldID}"] = $fileurl[$dao->$fieldName];
446 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
449 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
453 if($file[$tableName][$fieldID] == 'File') {
454 if($fileid = $dao->$fieldName) {
455 $fileurl = CRM_Core_BAO_File
::paperIconAttachment($tableName,$entityID);
456 $result[$fieldID] = $fileurl[$dao->$fieldName];
460 $result[$fieldID] = $dao->$fieldName;
470 * Function to take in an array of entityID, custom_XXX => value
471 * and set the value in the appropriate table. Should also be able
472 * to set the value to null. Follows api parameter/return conventions
479 static function setValues(&$params) {
481 if (!isset($params['entityID']) ||
482 CRM_Utils_Type
::escape($params['entityID'], 'Integer', FALSE) === NULL
484 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
487 // first collect all the id/value pairs. The format is:
488 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
490 $fieldValues = array();
491 foreach ($params as $n => $v) {
492 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($n, TRUE)) {
493 $fieldID = (int ) $customFieldInfo[0];
494 if (CRM_Utils_Type
::escape($fieldID, 'Integer', FALSE) === NULL) {
495 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
499 if (!array_key_exists($fieldID, $fieldValues)) {
500 $fieldValues[$fieldID] = array();
503 if ($customFieldInfo[1]) {
504 $id = (int ) $customFieldInfo[1];
506 $fieldValues[$fieldID][] = array(
513 $fieldIDList = implode(',', array_keys($fieldValues));
515 // format it so that we can just use create
517 SELECT cg.table_name as table_name ,
519 cg.is_multiple as is_multiple,
520 cf.column_name as column_name,
522 cf.data_type as data_type
523 FROM civicrm_custom_group cg,
524 civicrm_custom_field cf
525 WHERE cf.custom_group_id = cg.id
526 AND cf.id IN ( $fieldIDList )
529 $dao = CRM_Core_DAO
::executeQuery($sql);
532 while ($dao->fetch()) {
533 $dataType = $dao->data_type
== 'Date' ?
'Timestamp' : $dao->data_type
;
534 foreach ($fieldValues[$dao->cf_id
] as $fieldValue) {
535 // Format null values correctly
536 if ($fieldValue['value'] === NULL ||
$fieldValue['value'] === '') {
542 $fieldValue['value'] = '';
546 $fieldValue['value'] = NULL;
549 case 'StateProvince':
553 $fieldValue['value'] = (int)0;
557 // Ensure that value is of the right data type
558 elseif (CRM_Utils_Type
::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
559 return CRM_Core_Error
::createAPIError(ts('value: %1 is not of the right field data type: %2',
561 1 => $fieldValue['value'],
568 'entity_id' => $params['entityID'],
569 'value' => $fieldValue['value'],
571 'custom_field_id' => $dao->cf_id
,
572 'custom_group_id' => $dao->cg_id
,
573 'table_name' => $dao->table_name
,
574 'column_name' => $dao->column_name
,
575 'is_multiple' => $dao->is_multiple
,
578 if (!array_key_exists($dao->table_name
, $cvParams)) {
579 $cvParams[$dao->table_name
] = array();
582 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name
])) {
583 $cvParams[$dao->table_name
][$fieldValue['id']] = array();
586 if ($fieldValue['id'] > 0) {
587 $cvParam['id'] = $fieldValue['id'];
589 $cvParams[$dao->table_name
][$fieldValue['id']][] = $cvParam;
593 if (!empty($cvParams)) {
594 self
::create($cvParams);
595 return array('is_error' => 0, 'result' => 1);
598 return CRM_Core_Error
::createAPIError(ts('Unknown error'));
602 * Function to take in an array of entityID, custom_ID
603 * and gets the value from the appropriate table.
605 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
606 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
608 * Entity Type will be infered by the custom fields you request
609 * Specify $params['entityType'] if you do not supply any custom fields to return
610 * and entity type is other than Contact
617 static function &getValues(&$params) {
618 if (empty($params)) {
621 if (!isset($params['entityID']) ||
622 CRM_Utils_Type
::escape($params['entityID'],
626 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
629 // first collect all the ids. The format is:
632 foreach ($params as $n => $v) {
634 if (substr($n, 0, 7) == 'custom_') {
635 $idx = substr($n, 7);
636 if (CRM_Utils_Type
::escape($idx, 'Integer', FALSE) === NULL) {
637 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
641 $fieldIDs[] = (int ) $idx;
645 $default = array('Contact', 'Individual', 'Household', 'Organization');
646 if (!($type = CRM_Utils_Array
::value('entityType', $params)) ||
647 in_array($params['entityType'], $default)
652 $entities = CRM_Core_SelectValues
::customGroupExtends();
653 if (!array_key_exists($type, $entities)) {
654 if (in_array($type, $entities)) {
655 $type = $entities[$type];
656 if (in_array($type, $default)) {
661 return CRM_Core_Error
::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
666 $values = self
::getEntityValues($params['entityID'],
670 if (empty($values)) {
671 // note that this behaviour is undesirable from an API point of view - it should return an empty array
672 // since this is also called by the merger code & not sure the consequences of changing
673 // are just handling undoing this in the api layer. ie. converting the error back into a success
676 'error_message' => 'No values found for the specified entity ID and custom field(s).',
683 'entityID' => $params['entityID'],
685 foreach ($values as $id => $value) {
686 $result["custom_{$id}"] = $value;