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
{
38 * @param array $customParams
42 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)) {
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[] = $states['state_province_id'];
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
122 if (is_array($value)) {
123 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
126 elseif (!is_numeric($value)) {
127 //fix for multi select country, CRM-3437
128 $mulValues = explode(',', $value);
129 $validCountries = array();
130 foreach ($mulValues as $key => $countryVal) {
131 $countries = array();
132 $countries['country'] = trim($countryVal);
133 CRM_Utils_Array
::lookupValue($countries, 'country',
134 CRM_Core_PseudoConstant
::country(), TRUE
136 if (empty($countries['country_id'])) {
137 CRM_Utils_Array
::lookupValue($countries, 'country',
138 CRM_Core_PseudoConstant
::countryIsoCode(), TRUE
141 $validCountries[] = $countries['country_id'];
143 $value = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
150 // using type of timestamp allows us to sneak in a null into db
151 // gross but effective hack
158 if (!$field['file_id']) {
159 CRM_Core_Error
::fatal();
162 // need to add/update civicrm_entity_file
163 $entityFileDAO = new CRM_Core_DAO_EntityFile();
164 $entityFileDAO->file_id
= $field['file_id'];
165 $entityFileDAO->find(TRUE);
167 $entityFileDAO->entity_table
= $field['table_name'];
168 $entityFileDAO->entity_id
= $field['entity_id'];
169 $entityFileDAO->file_id
= $field['file_id'];
170 $entityFileDAO->save();
171 $entityFileDAO->free();
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 $set[$field['column_name']] = "%{$count}";
214 $params[$count] = array($value, $type);
219 $setClause = array();
220 foreach ($set as $n => $v) {
221 $setClause[] = "$n = $v";
223 $setClause = implode(',', $setClause);
225 // do this only for insert
226 $set['entity_id'] = "%{$count}";
227 $params[$count] = array($entityID, 'Integer');
230 $fieldNames = implode(',', array_keys($set));
231 $fieldValues = implode(',', array_values($set));
232 $query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
233 // for multiple values we dont do on duplicate key update
235 $query .= " ON DUPLICATE KEY UPDATE $setClause";
239 $query = "$sqlOP SET $setClause $where";
241 $dao = CRM_Core_DAO
::executeQuery($query, $params);
243 CRM_Utils_Hook
::custom($hookOP,
254 * Given a field return the mysql data type associated with it
256 * @param string $type the civicrm type string
258 * @param int $maxLength
260 * @return the mysql data store placeholder
264 public static function fieldToSQLType($type, $maxLength = 255) {
265 if (!isset($maxLength) ||
266 !is_numeric($maxLength) ||
275 return "varchar($maxLength)";
282 // the below three are FK's, and have constraints added to them
284 case 'ContactReference':
285 case 'StateProvince':
288 return 'int unsigned';
294 return 'decimal(20,2)';
297 case 'RichTextEditor':
304 CRM_Core_Error
::fatal();
309 * @param array $params
310 * @param $entityTable
311 * @param int $entityID
313 static function store(&$params, $entityTable, $entityID) {
315 foreach ($params as $fieldID => $param) {
316 foreach ($param as $index => $customValue) {
318 'entity_table' => $entityTable,
319 'entity_id' => $entityID,
320 'value' => $customValue['value'],
321 'type' => $customValue['type'],
322 'custom_field_id' => $customValue['custom_field_id'],
323 'custom_group_id' => $customValue['custom_group_id'],
324 'table_name' => $customValue['table_name'],
325 'column_name' => $customValue['column_name'],
326 'is_multiple' => CRM_Utils_Array
::value('is_multiple', $customValue),
327 'file_id' => $customValue['file_id'],
330 // fix Date type to be timestamp, since that is how we store in db
331 if ($cvParam['type'] == 'Date') {
332 $cvParam['type'] = 'Timestamp';
335 if (!empty($customValue['id'])) {
336 $cvParam['id'] = $customValue['id'];
338 if (!array_key_exists($customValue['table_name'], $cvParams)) {
339 $cvParams[$customValue['table_name']] = array();
342 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
343 $cvParams[$customValue['table_name']][$index] = array();
346 $cvParams[$customValue['table_name']][$index][] = $cvParam;
349 if (!empty($cvParams)) {
350 self
::create($cvParams);
355 * @param array $params
356 * @param $customFields
357 * @param $entityTable
358 * @param int $entityID
359 * @param $customFieldExtends
361 static function postProcess(&$params, &$customFields, $entityTable, $entityID, $customFieldExtends) {
362 $customData = CRM_Core_BAO_CustomField
::postProcess($params,
368 if (!empty($customData)) {
369 self
::store($customData, $entityTable, $entityID);
374 * Return an array of all custom values associated with an entity.
376 * @param int $entityID Identification number of the entity
377 * @param string $entityType Type of entity that the entityID corresponds to, specified
378 * as a string with format "'<EntityName>'". Comma separated
379 * list may be used to specify OR matches. Allowable values
380 * are enumerated types in civicrm_custom_group.extends field.
381 * Optional. Default value assumes entityID references a
383 * @param array $fieldIDs optional list of fieldIDs that we want to retrieve. If this
384 * is set the entityType is ignored
386 * @param bool $formatMultiRecordField
388 * @return array $fields Array of custom values for the entity with key=>value
389 * pairs specified as civicrm_custom_field.id => custom value.
390 * Empty array if no custom values found.
394 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE) {
396 // adding this here since an empty contact id could have serious repurcussions
397 // like looping forever
398 CRM_Core_Error
::fatal('Please file an issue with the backtrace');
404 $cond[] = "cg.extends IN ( '$entityType' )";
409 $fieldIDList = implode(',', $fieldIDs);
410 $cond[] = "cf.id IN ( $fieldIDList )";
413 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
415 $cond = implode(' AND ', $cond);
417 // first find all the fields that extend this type of entity
419 SELECT cg.table_name,
424 cf.data_type as fieldDataType
425 FROM civicrm_custom_group cg,
426 civicrm_custom_field cf
427 WHERE cf.custom_group_id = cg.id
432 $dao = CRM_Core_DAO
::executeQuery($query);
434 $select = $fields = $isMultiple = array();
436 while ($dao->fetch()) {
437 if (!array_key_exists($dao->table_name
, $select)) {
438 $fields[$dao->table_name
] = array();
439 $select[$dao->table_name
] = array();
441 $fields[$dao->table_name
][] = $dao->fieldID
;
442 $select[$dao->table_name
][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
443 $isMultiple[$dao->table_name
] = $dao->is_multiple ?
TRUE : FALSE;
444 $file[$dao->table_name
][$dao->fieldID
] = $dao->fieldDataType
;
448 foreach ($select as $tableName => $clauses) {
449 $query = "SELECT id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID";
450 $dao = CRM_Core_DAO
::executeQuery($query);
451 while ($dao->fetch()) {
452 foreach ($fields[$tableName] as $fieldID) {
453 $fieldName = "custom_{$fieldID}";
454 if ($isMultiple[$tableName]) {
455 if ($formatMultiRecordField) {
456 if($file[$tableName][$fieldID] == 'File') {
457 if($fileid = $dao->$fieldName) {
458 $fileurl = CRM_Core_BAO_File
::paperIconAttachment($tableName,$entityID);
459 $result["{$dao->id}"]["{$fieldID}"] = $fileurl[$dao->$fieldName];
463 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
466 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
470 if($file[$tableName][$fieldID] == 'File') {
471 if($fileid = $dao->$fieldName) {
472 $fileurl = CRM_Core_BAO_File
::paperIconAttachment($tableName,$entityID);
473 $result[$fieldID] = $fileurl[$dao->$fieldName];
477 $result[$fieldID] = $dao->$fieldName;
487 * Take in an array of entityID, custom_XXX => value
488 * and set the value in the appropriate table. Should also be able
489 * to set the value to null. Follows api parameter/return conventions
493 * @param array $params
499 static function setValues(&$params) {
501 if (!isset($params['entityID']) ||
502 CRM_Utils_Type
::escape($params['entityID'], 'Integer', FALSE) === NULL
504 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
507 // first collect all the id/value pairs. The format is:
508 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
510 $fieldValues = array();
511 foreach ($params as $n => $v) {
512 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($n, TRUE)) {
513 $fieldID = (int ) $customFieldInfo[0];
514 if (CRM_Utils_Type
::escape($fieldID, 'Integer', FALSE) === NULL) {
515 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
519 if (!array_key_exists($fieldID, $fieldValues)) {
520 $fieldValues[$fieldID] = array();
523 if ($customFieldInfo[1]) {
524 $id = (int ) $customFieldInfo[1];
526 $fieldValues[$fieldID][] = array(
533 $fieldIDList = implode(',', array_keys($fieldValues));
535 // format it so that we can just use create
537 SELECT cg.table_name as table_name ,
539 cg.is_multiple as is_multiple,
540 cf.column_name as column_name,
542 cf.data_type as data_type
543 FROM civicrm_custom_group cg,
544 civicrm_custom_field cf
545 WHERE cf.custom_group_id = cg.id
546 AND cf.id IN ( $fieldIDList )
549 $dao = CRM_Core_DAO
::executeQuery($sql);
552 while ($dao->fetch()) {
553 $dataType = $dao->data_type
== 'Date' ?
'Timestamp' : $dao->data_type
;
554 foreach ($fieldValues[$dao->cf_id
] as $fieldValue) {
555 // Format null values correctly
556 if ($fieldValue['value'] === NULL ||
$fieldValue['value'] === '') {
562 $fieldValue['value'] = '';
566 $fieldValue['value'] = NULL;
569 case 'StateProvince':
573 $fieldValue['value'] = (int)0;
577 // Ensure that value is of the right data type
578 elseif (CRM_Utils_Type
::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
579 return CRM_Core_Error
::createAPIError(ts('value: %1 is not of the right field data type: %2',
581 1 => $fieldValue['value'],
588 'entity_id' => $params['entityID'],
589 'value' => $fieldValue['value'],
591 'custom_field_id' => $dao->cf_id
,
592 'custom_group_id' => $dao->cg_id
,
593 'table_name' => $dao->table_name
,
594 'column_name' => $dao->column_name
,
595 'is_multiple' => $dao->is_multiple
,
598 if ($cvParam['type'] == 'File') {
599 $cvParam['file_id'] = $fieldValue['value'];
602 if (!array_key_exists($dao->table_name
, $cvParams)) {
603 $cvParams[$dao->table_name
] = array();
606 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name
])) {
607 $cvParams[$dao->table_name
][$fieldValue['id']] = array();
610 if ($fieldValue['id'] > 0) {
611 $cvParam['id'] = $fieldValue['id'];
613 $cvParams[$dao->table_name
][$fieldValue['id']][] = $cvParam;
617 if (!empty($cvParams)) {
618 self
::create($cvParams);
619 return array('is_error' => 0, 'result' => 1);
622 return CRM_Core_Error
::createAPIError(ts('Unknown error'));
626 * Take in an array of entityID, custom_ID
627 * and gets the value from the appropriate table.
629 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
630 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
632 * Entity Type will be infered by the custom fields you request
633 * Specify $params['entityType'] if you do not supply any custom fields to return
634 * and entity type is other than Contact
638 * @param array $params
644 static function &getValues(&$params) {
645 if (empty($params)) {
648 if (!isset($params['entityID']) ||
649 CRM_Utils_Type
::escape($params['entityID'],
653 return CRM_Core_Error
::createAPIError(ts('entityID needs to be set and of type Integer'));
656 // first collect all the ids. The format is:
659 foreach ($params as $n => $v) {
661 if (substr($n, 0, 7) == 'custom_') {
662 $idx = substr($n, 7);
663 if (CRM_Utils_Type
::escape($idx, 'Integer', FALSE) === NULL) {
664 return CRM_Core_Error
::createAPIError(ts('field ID needs to be of type Integer for index %1',
668 $fieldIDs[] = (int ) $idx;
672 $default = array('Contact', 'Individual', 'Household', 'Organization');
673 if (!($type = CRM_Utils_Array
::value('entityType', $params)) ||
674 in_array($params['entityType'], $default)
679 $entities = CRM_Core_SelectValues
::customGroupExtends();
680 if (!array_key_exists($type, $entities)) {
681 if (in_array($type, $entities)) {
682 $type = $entities[$type];
683 if (in_array($type, $default)) {
688 return CRM_Core_Error
::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
693 $values = self
::getEntityValues($params['entityID'],
697 if (empty($values)) {
698 // note that this behaviour is undesirable from an API point of view - it should return an empty array
699 // since this is also called by the merger code & not sure the consequences of changing
700 // are just handling undoing this in the api layer. ie. converting the error back into a success
703 'error_message' => 'No values found for the specified entity ID and custom field(s).',
710 'entityID' => $params['entityID'],
712 foreach ($values as $id => $value) {
713 $result["custom_{$id}"] = $value;