Merge branch 4.5 into master
[civicrm-core.git] / CRM / Core / BAO / CustomValueTable.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Core_BAO_CustomValueTable {
36
b5c2afd0 37 /**
100fef9d 38 * @param array $customParams
b5c2afd0
EM
39 *
40 * @throws Exception
41 */
00be9182 42 public static function create(&$customParams) {
6a488035
TO
43 if (empty($customParams) ||
44 !is_array($customParams)
45 ) {
46 return;
47 }
8ef12e64 48
6a488035
TO
49 foreach ($customParams as $tableName => $tables) {
50 foreach ($tables as $index => $fields) {
353ffa53
TO
51 $sqlOP = NULL;
52 $hookID = NULL;
53 $hookOP = NULL;
54 $entityID = NULL;
6a488035 55 $isMultiple = FALSE;
353ffa53
TO
56 $set = array();
57 $params = array();
58 $count = 1;
6a488035
TO
59 foreach ($fields as $field) {
60 if (!$sqlOP) {
353ffa53
TO
61 $entityID = $field['entity_id'];
62 $hookID = $field['custom_group_id'];
6a488035
TO
63 $isMultiple = $field['is_multiple'];
64 if (array_key_exists('id', $field)) {
353ffa53
TO
65 $sqlOP = "UPDATE $tableName ";
66 $where = " WHERE id = %{$count}";
6a488035
TO
67 $params[$count] = array($field['id'], 'Integer');
68 $count++;
69 $hookOP = 'edit';
70 }
71 else {
353ffa53
TO
72 $sqlOP = "INSERT INTO $tableName ";
73 $where = NULL;
6a488035
TO
74 $hookOP = 'create';
75 }
76 }
77
78 // fix the value before we store it
79 $value = $field['value'];
80 $type = $field['type'];
81 switch ($type) {
82 case 'StateProvince':
83 $type = 'Integer';
84 if (is_array($value)) {
85 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
86 $type = 'String';
87 }
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) {
93 $states = array();
94 $states['state_province'] = trim($stateVal);
95
96 CRM_Utils_Array::lookupValue($states, 'state_province',
97 CRM_Core_PseudoConstant::stateProvince(), TRUE
98 );
a7488080 99 if (empty($states['state_province_id'])) {
6a488035
TO
100 CRM_Utils_Array::lookupValue($states, 'state_province',
101 CRM_Core_PseudoConstant::stateProvinceAbbreviation(), TRUE
102 );
103 }
104 $validStates[] = $states['state_province_id'];
105 }
106 $value = implode(CRM_Core_DAO::VALUE_SEPARATOR,
107 $validStates
108 );
109 $type = 'String';
110 }
111 elseif (!$value) {
112 // CRM-3415
113 // using type of timestamp allows us to sneak in a null into db
114 // gross but effective hack
115 $value = NULL;
116 $type = 'Timestamp';
117 }
118 break;
119
120 case 'Country':
121 $type = 'Integer';
122 if (is_array($value)) {
123 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
124 $type = 'String';
125 }
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
135 );
a7488080 136 if (empty($countries['country_id'])) {
6a488035
TO
137 CRM_Utils_Array::lookupValue($countries, 'country',
138 CRM_Core_PseudoConstant::countryIsoCode(), TRUE
139 );
140 }
141 $validCountries[] = $countries['country_id'];
142 }
143 $value = implode(CRM_Core_DAO::VALUE_SEPARATOR,
144 $validCountries
145 );
146 $type = 'String';
147 }
148 elseif (!$value) {
149 // CRM-3415
150 // using type of timestamp allows us to sneak in a null into db
151 // gross but effective hack
152 $value = NULL;
153 $type = 'Timestamp';
154 }
155 break;
156
157 case 'File':
158 if (!$field['file_id']) {
159 CRM_Core_Error::fatal();
160 }
161
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);
166
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'];
173 $type = 'String';
174 break;
175
176 case 'Date':
177 $value = CRM_Utils_Date::isoToMysql($value);
178 break;
179
180 case 'Int':
181 if (is_numeric($value)) {
182 $type = 'Integer';
183 }
184 else {
185 $type = 'Timestamp';
186 }
187 break;
188
189 case 'ContactReference':
190 if ($value == NULL) {
191 $type = 'Timestamp';
192 }
193 else {
194 $type = 'Integer';
195 }
196 break;
197
198 case 'RichTextEditor':
199 $type = 'String';
200 break;
201
202 case 'Boolean':
203 //fix for CRM-3290
204 $value = CRM_Utils_String::strtoboolstr($value);
205 if ($value === FALSE) {
206 $type = 'Timestamp';
207 }
208 break;
209
210 default:
211 break;
212 }
213 $set[$field['column_name']] = "%{$count}";
214 $params[$count] = array($value, $type);
215 $count++;
216 }
217
218 if (!empty($set)) {
219 $setClause = array();
220 foreach ($set as $n => $v) {
221 $setClause[] = "$n = $v";
222 }
223 $setClause = implode(',', $setClause);
224 if (!$where) {
225 // do this only for insert
226 $set['entity_id'] = "%{$count}";
227 $params[$count] = array($entityID, 'Integer');
228 $count++;
229
353ffa53 230 $fieldNames = implode(',', array_keys($set));
6a488035 231 $fieldValues = implode(',', array_values($set));
353ffa53 232 $query = "$sqlOP ( $fieldNames ) VALUES ( $fieldValues )";
6a488035
TO
233 // for multiple values we dont do on duplicate key update
234 if (!$isMultiple) {
235 $query .= " ON DUPLICATE KEY UPDATE $setClause";
236 }
237 }
238 else {
239 $query = "$sqlOP SET $setClause $where";
240 }
241 $dao = CRM_Core_DAO::executeQuery($query, $params);
242
243 CRM_Utils_Hook::custom($hookOP,
244 $hookID,
245 $entityID,
246 $fields
247 );
248 }
249 }
250 }
251 }
252
253 /**
100fef9d 254 * Given a field return the mysql data type associated with it
6a488035 255 *
6a0b768e 256 * @param string $type
fd31fa4c
EM
257 * @param int $maxLength
258 *
72b3a70c
CW
259 * @return string
260 * the mysql data store placeholder
6a488035
TO
261 */
262 public static function fieldToSQLType($type, $maxLength = 255) {
263 if (!isset($maxLength) ||
264 !is_numeric($maxLength) ||
265 $maxLength <= 0
266 ) {
267 $maxLength = 255;
268 }
269
270 switch ($type) {
271 case 'String':
272 case 'Link':
273 return "varchar($maxLength)";
274
275 case 'Boolean':
276 return 'tinyint';
277
278 case 'Int':
279 return 'int';
2aa397bc 280
6a488035
TO
281 // the below three are FK's, and have constraints added to them
282
283 case 'ContactReference':
284 case 'StateProvince':
285 case 'Country':
286 case 'File':
287 return 'int unsigned';
288
289 case 'Float':
290 return 'double';
291
292 case 'Money':
293 return 'decimal(20,2)';
294
295 case 'Memo':
296 case 'RichTextEditor':
297 return 'text';
298
299 case 'Date':
300 return 'datetime';
301
302 default:
303 CRM_Core_Error::fatal();
304 }
305 }
306
b5c2afd0 307 /**
c490a46a 308 * @param array $params
b5c2afd0 309 * @param $entityTable
100fef9d 310 * @param int $entityID
b5c2afd0 311 */
00be9182 312 public static function store(&$params, $entityTable, $entityID) {
6a488035
TO
313 $cvParams = array();
314 foreach ($params as $fieldID => $param) {
315 foreach ($param as $index => $customValue) {
316 $cvParam = array(
317 'entity_table' => $entityTable,
318 'entity_id' => $entityID,
319 'value' => $customValue['value'],
320 'type' => $customValue['type'],
321 'custom_field_id' => $customValue['custom_field_id'],
322 'custom_group_id' => $customValue['custom_group_id'],
323 'table_name' => $customValue['table_name'],
324 'column_name' => $customValue['column_name'],
325 'is_multiple' => CRM_Utils_Array::value('is_multiple', $customValue),
326 'file_id' => $customValue['file_id'],
327 );
328
329 // fix Date type to be timestamp, since that is how we store in db
330 if ($cvParam['type'] == 'Date') {
331 $cvParam['type'] = 'Timestamp';
332 }
333
a7488080 334 if (!empty($customValue['id'])) {
6a488035
TO
335 $cvParam['id'] = $customValue['id'];
336 }
337 if (!array_key_exists($customValue['table_name'], $cvParams)) {
338 $cvParams[$customValue['table_name']] = array();
339 }
340
341 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
342 $cvParams[$customValue['table_name']][$index] = array();
343 }
344
345 $cvParams[$customValue['table_name']][$index][] = $cvParam;
346 }
347 }
348 if (!empty($cvParams)) {
349 self::create($cvParams);
350 }
351 }
352
b5c2afd0 353 /**
c490a46a 354 * @param array $params
b5c2afd0
EM
355 * @param $customFields
356 * @param $entityTable
100fef9d 357 * @param int $entityID
b5c2afd0
EM
358 * @param $customFieldExtends
359 */
00be9182 360 public static function postProcess(&$params, &$customFields, $entityTable, $entityID, $customFieldExtends) {
6a488035
TO
361 $customData = CRM_Core_BAO_CustomField::postProcess($params,
362 $customFields,
363 $entityID,
364 $customFieldExtends
365 );
366
367 if (!empty($customData)) {
368 self::store($customData, $entityTable, $entityID);
369 }
370 }
371
372 /**
373 * Return an array of all custom values associated with an entity.
374 *
6a0b768e
TO
375 * @param int $entityID
376 * Identification number of the entity.
377 * @param string $entityType
378 * Type of entity that the entityID corresponds to, specified.
6a488035
TO
379 * as a string with format "'<EntityName>'". Comma separated
380 * list may be used to specify OR matches. Allowable values
381 * are enumerated types in civicrm_custom_group.extends field.
382 * Optional. Default value assumes entityID references a
383 * contact entity.
6a0b768e
TO
384 * @param array $fieldIDs
385 * Optional list of fieldIDs that we want to retrieve. If this.
6a488035
TO
386 * is set the entityType is ignored
387 *
77b97be7
EM
388 * @param bool $formatMultiRecordField
389 *
a6c01b45
CW
390 * @return array
391 * Array of custom values for the entity with key=>value
6a488035
TO
392 * pairs specified as civicrm_custom_field.id => custom value.
393 * Empty array if no custom values found.
6a488035
TO
394 */
395 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE) {
396 if (!$entityID) {
397 // adding this here since an empty contact id could have serious repurcussions
398 // like looping forever
399 CRM_Core_Error::fatal('Please file an issue with the backtrace');
400 return NULL;
401 }
402
403 $cond = array();
404 if ($entityType) {
405 $cond[] = "cg.extends IN ( '$entityType' )";
406 }
407 if ($fieldIDs &&
408 is_array($fieldIDs)
409 ) {
410 $fieldIDList = implode(',', $fieldIDs);
411 $cond[] = "cf.id IN ( $fieldIDList )";
412 }
413 if (empty($cond)) {
414 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
415 }
416 $cond = implode(' AND ', $cond);
417
418 // first find all the fields that extend this type of entity
419 $query = "
420SELECT cg.table_name,
421 cg.id as groupID,
422 cg.is_multiple,
423 cf.column_name,
34f51a07
N
424 cf.id as fieldID,
425 cf.data_type as fieldDataType
6a488035
TO
426FROM civicrm_custom_group cg,
427 civicrm_custom_field cf
428WHERE cf.custom_group_id = cg.id
429AND cg.is_active = 1
430AND cf.is_active = 1
431AND $cond
432";
433 $dao = CRM_Core_DAO::executeQuery($query);
434
435 $select = $fields = $isMultiple = array();
436
437 while ($dao->fetch()) {
438 if (!array_key_exists($dao->table_name, $select)) {
439 $fields[$dao->table_name] = array();
440 $select[$dao->table_name] = array();
441 }
442 $fields[$dao->table_name][] = $dao->fieldID;
443 $select[$dao->table_name][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
444 $isMultiple[$dao->table_name] = $dao->is_multiple ? TRUE : FALSE;
77b97be7 445 $file[$dao->table_name][$dao->fieldID] = $dao->fieldDataType;
6a488035
TO
446 }
447
448 $result = array();
449 foreach ($select as $tableName => $clauses) {
450 $query = "SELECT id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID";
451 $dao = CRM_Core_DAO::executeQuery($query);
452 while ($dao->fetch()) {
453 foreach ($fields[$tableName] as $fieldID) {
454 $fieldName = "custom_{$fieldID}";
455 if ($isMultiple[$tableName]) {
456 if ($formatMultiRecordField) {
d8f34a6e 457 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
6a488035
TO
458 } else {
459 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
460 }
461 }
462 else {
d8f34a6e 463 $result[$fieldID] = $dao->$fieldName;
6a488035
TO
464 }
465 }
466 }
467 }
468 return $result;
469 }
470
471 /**
100fef9d 472 * Take in an array of entityID, custom_XXX => value
6a488035
TO
473 * and set the value in the appropriate table. Should also be able
474 * to set the value to null. Follows api parameter/return conventions
475 *
476 * @array $params
477 *
c490a46a 478 * @param array $params
2a6da8d7
EM
479 *
480 * @throws Exception
6a488035 481 * @return array
6a488035 482 */
00be9182 483 public static function setValues(&$params) {
6a488035
TO
484
485 if (!isset($params['entityID']) ||
486 CRM_Utils_Type::escape($params['entityID'], 'Integer', FALSE) === NULL
487 ) {
488 return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
489 }
490
491 // first collect all the id/value pairs. The format is:
492 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
493 $values = array();
494 $fieldValues = array();
495 foreach ($params as $n => $v) {
496 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($n, TRUE)) {
497 $fieldID = (int ) $customFieldInfo[0];
498 if (CRM_Utils_Type::escape($fieldID, 'Integer', FALSE) === NULL) {
499 return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
353ffa53
TO
500 array(1 => $fieldID)
501 ));
6a488035
TO
502 }
503 if (!array_key_exists($fieldID, $fieldValues)) {
504 $fieldValues[$fieldID] = array();
505 }
506 $id = -1;
507 if ($customFieldInfo[1]) {
508 $id = (int ) $customFieldInfo[1];
509 }
510 $fieldValues[$fieldID][] = array(
511 'value' => $v,
512 'id' => $id,
513 );
514 }
515 }
516
517 $fieldIDList = implode(',', array_keys($fieldValues));
518
519 // format it so that we can just use create
520 $sql = "
521SELECT cg.table_name as table_name ,
522 cg.id as cg_id ,
523 cg.is_multiple as is_multiple,
524 cf.column_name as column_name,
525 cf.id as cf_id ,
526 cf.data_type as data_type
527FROM civicrm_custom_group cg,
528 civicrm_custom_field cf
529WHERE cf.custom_group_id = cg.id
530AND cf.id IN ( $fieldIDList )
531";
532
533 $dao = CRM_Core_DAO::executeQuery($sql);
534 $cvParams = array();
535
536 while ($dao->fetch()) {
537 $dataType = $dao->data_type == 'Date' ? 'Timestamp' : $dao->data_type;
538 foreach ($fieldValues[$dao->cf_id] as $fieldValue) {
539 // Format null values correctly
540 if ($fieldValue['value'] === NULL || $fieldValue['value'] === '') {
541 switch ($dataType) {
542 case 'String':
543 case 'Int':
544 case 'Link':
545 case 'Boolean':
546 $fieldValue['value'] = '';
547 break;
548
549 case 'Timestamp':
550 $fieldValue['value'] = NULL;
551 break;
552
553 case 'StateProvince':
554 case 'Country':
555 case 'Money':
556 case 'Float':
2aa397bc 557 $fieldValue['value'] = (int) 0;
6a488035
TO
558 break;
559 }
560 }
561 // Ensure that value is of the right data type
562 elseif (CRM_Utils_Type::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
563 return CRM_Core_Error::createAPIError(ts('value: %1 is not of the right field data type: %2',
353ffa53
TO
564 array(
565 1 => $fieldValue['value'],
566 2 => $dao->data_type,
567 )
568 ));
6a488035
TO
569 }
570
571 $cvParam = array(
572 'entity_id' => $params['entityID'],
573 'value' => $fieldValue['value'],
574 'type' => $dataType,
575 'custom_field_id' => $dao->cf_id,
576 'custom_group_id' => $dao->cg_id,
577 'table_name' => $dao->table_name,
578 'column_name' => $dao->column_name,
579 'is_multiple' => $dao->is_multiple,
580 );
581
e7dcccf0
CW
582 if ($cvParam['type'] == 'File') {
583 $cvParam['file_id'] = $fieldValue['value'];
584 }
585
6a488035
TO
586 if (!array_key_exists($dao->table_name, $cvParams)) {
587 $cvParams[$dao->table_name] = array();
588 }
589
590 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name])) {
591 $cvParams[$dao->table_name][$fieldValue['id']] = array();
592 }
593
594 if ($fieldValue['id'] > 0) {
595 $cvParam['id'] = $fieldValue['id'];
596 }
597 $cvParams[$dao->table_name][$fieldValue['id']][] = $cvParam;
598 }
599 }
600
601 if (!empty($cvParams)) {
602 self::create($cvParams);
603 return array('is_error' => 0, 'result' => 1);
604 }
605
606 return CRM_Core_Error::createAPIError(ts('Unknown error'));
607 }
608
609 /**
100fef9d 610 * Take in an array of entityID, custom_ID
6a488035
TO
611 * and gets the value from the appropriate table.
612 *
613 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
614 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
615 *
616 * Entity Type will be infered by the custom fields you request
617 * Specify $params['entityType'] if you do not supply any custom fields to return
618 * and entity type is other than Contact
619 *
620 * @array $params
621 *
c490a46a 622 * @param array $params
2a6da8d7
EM
623 *
624 * @throws Exception
6a488035 625 * @return array
6a488035 626 */
00be9182 627 public static function &getValues(&$params) {
6a488035
TO
628 if (empty($params)) {
629 return NULL;
630 }
631 if (!isset($params['entityID']) ||
632 CRM_Utils_Type::escape($params['entityID'],
633 'Integer', FALSE
634 ) === NULL
635 ) {
636 return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
637 }
638
639 // first collect all the ids. The format is:
640 // custom_ID
641 $fieldIDs = array();
642 foreach ($params as $n => $v) {
643 $key = $idx = NULL;
644 if (substr($n, 0, 7) == 'custom_') {
645 $idx = substr($n, 7);
646 if (CRM_Utils_Type::escape($idx, 'Integer', FALSE) === NULL) {
647 return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
353ffa53
TO
648 array(1 => $idx)
649 ));
6a488035
TO
650 }
651 $fieldIDs[] = (int ) $idx;
652 }
653 }
654
655 $default = array('Contact', 'Individual', 'Household', 'Organization');
656 if (!($type = CRM_Utils_Array::value('entityType', $params)) ||
657 in_array($params['entityType'], $default)
658 ) {
659 $type = NULL;
660 }
661 else {
662 $entities = CRM_Core_SelectValues::customGroupExtends();
663 if (!array_key_exists($type, $entities)) {
664 if (in_array($type, $entities)) {
665 $type = $entities[$type];
666 if (in_array($type, $default)) {
667 $type = NULL;
668 }
669 }
670 else {
671 return CRM_Core_Error::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
672 }
673 }
674 }
675
676 $values = self::getEntityValues($params['entityID'],
677 $type,
678 $fieldIDs
679 );
680 if (empty($values)) {
681 // note that this behaviour is undesirable from an API point of view - it should return an empty array
682 // since this is also called by the merger code & not sure the consequences of changing
683 // are just handling undoing this in the api layer. ie. converting the error back into a success
684 $result = array(
685 'is_error' => 1,
686 'error_message' => 'No values found for the specified entity ID and custom field(s).',
687 );
688 return $result;
689 }
690 else {
691 $result = array(
692 'is_error' => 0,
693 'entityID' => $params['entityID'],
694 );
695 foreach ($values as $id => $value) {
696 $result["custom_{$id}"] = $value;
697 }
698 return $result;
699 }
700 }
96025800 701
6a488035 702}