bulk comment fix
[civicrm-core.git] / CRM / Core / BAO / CustomValueTable.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Core_BAO_CustomValueTable {
36
37 static function create(&$customParams) {
38 if (empty($customParams) ||
39 !is_array($customParams)
40 ) {
41 return;
42 }
43
44 foreach ($customParams as $tableName => $tables) {
45 foreach ($tables as $index => $fields) {
46 $sqlOP = NULL;
47 $hookID = NULL;
48 $hookOP = NULL;
49 $entityID = NULL;
50 $isMultiple = FALSE;
51 $set = array();
52 $params = array();
53 $count = 1;
54 foreach ($fields as $field) {
55 if (!$sqlOP) {
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');
63 $count++;
64 $hookOP = 'edit';
65 }
66 else {
67 $sqlOP = "INSERT INTO $tableName ";
68 $where = NULL;
69 $hookOP = 'create';
70 }
71 }
72
73 // fix the value before we store it
74 $value = $field['value'];
75 $type = $field['type'];
76 switch ($type) {
77 case 'StateProvince':
78 $type = 'Integer';
79 if (is_array($value)) {
80 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
81 $type = 'String';
82 }
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) {
88 $states = array();
89 $states['state_province'] = trim($stateVal);
90
91 CRM_Utils_Array::lookupValue($states, 'state_province',
92 CRM_Core_PseudoConstant::stateProvince(), TRUE
93 );
94 if (empty($states['state_province_id'])) {
95 CRM_Utils_Array::lookupValue($states, 'state_province',
96 CRM_Core_PseudoConstant::stateProvinceAbbreviation(), TRUE
97 );
98 }
99 $validStates[] = $states['state_province_id'];
100 }
101 $value = implode(CRM_Core_DAO::VALUE_SEPARATOR,
102 $validStates
103 );
104 $type = 'String';
105 }
106 elseif (!$value) {
107 // CRM-3415
108 // using type of timestamp allows us to sneak in a null into db
109 // gross but effective hack
110 $value = NULL;
111 $type = 'Timestamp';
112 }
113 break;
114
115 case 'Country':
116 $type = 'Integer';
117 if (is_array($value)) {
118 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
119 $type = 'String';
120 }
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
130 );
131 if (empty($countries['country_id'])) {
132 CRM_Utils_Array::lookupValue($countries, 'country',
133 CRM_Core_PseudoConstant::countryIsoCode(), TRUE
134 );
135 }
136 $validCountries[] = $countries['country_id'];
137 }
138 $value = implode(CRM_Core_DAO::VALUE_SEPARATOR,
139 $validCountries
140 );
141 $type = 'String';
142 }
143 elseif (!$value) {
144 // CRM-3415
145 // using type of timestamp allows us to sneak in a null into db
146 // gross but effective hack
147 $value = NULL;
148 $type = 'Timestamp';
149 }
150 break;
151
152 case 'File':
153 if (!$field['file_id']) {
154 CRM_Core_Error::fatal();
155 }
156
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);
161
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'];
168 $type = 'String';
169 break;
170
171 case 'Date':
172 $value = CRM_Utils_Date::isoToMysql($value);
173 break;
174
175 case 'Int':
176 if (is_numeric($value)) {
177 $type = 'Integer';
178 }
179 else {
180 $type = 'Timestamp';
181 }
182 break;
183
184 case 'ContactReference':
185 if ($value == NULL) {
186 $type = 'Timestamp';
187 }
188 else {
189 $type = 'Integer';
190 }
191 break;
192
193 case 'RichTextEditor':
194 $type = 'String';
195 break;
196
197 case 'Boolean':
198 //fix for CRM-3290
199 $value = CRM_Utils_String::strtoboolstr($value);
200 if ($value === FALSE) {
201 $type = 'Timestamp';
202 }
203 break;
204
205 default:
206 break;
207 }
208 $set[$field['column_name']] = "%{$count}";
209 $params[$count] = array($value, $type);
210 $count++;
211 }
212
213 if (!empty($set)) {
214 $setClause = array();
215 foreach ($set as $n => $v) {
216 $setClause[] = "$n = $v";
217 }
218 $setClause = implode(',', $setClause);
219 if (!$where) {
220 // do this only for insert
221 $set['entity_id'] = "%{$count}";
222 $params[$count] = array($entityID, 'Integer');
223 $count++;
224
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
229 if (!$isMultiple) {
230 $query .= " ON DUPLICATE KEY UPDATE $setClause";
231 }
232 }
233 else {
234 $query = "$sqlOP SET $setClause $where";
235 }
236 $dao = CRM_Core_DAO::executeQuery($query, $params);
237
238 CRM_Utils_Hook::custom($hookOP,
239 $hookID,
240 $entityID,
241 $fields
242 );
243 }
244 }
245 }
246 }
247
248 /**
249 * given a field return the mysql data type associated with it
250 *
251 * @param string $type the civicrm type string
252 *
253 * @param int $maxLength
254 *
255 * @return the mysql data store placeholder
256 * @access public
257 * @static
258 */
259 public static function fieldToSQLType($type, $maxLength = 255) {
260 if (!isset($maxLength) ||
261 !is_numeric($maxLength) ||
262 $maxLength <= 0
263 ) {
264 $maxLength = 255;
265 }
266
267 switch ($type) {
268 case 'String':
269 case 'Link':
270 return "varchar($maxLength)";
271
272 case 'Boolean':
273 return 'tinyint';
274
275 case 'Int':
276 return 'int';
277 // the below three are FK's, and have constraints added to them
278
279 case 'ContactReference':
280 case 'StateProvince':
281 case 'Country':
282 case 'File':
283 return 'int unsigned';
284
285 case 'Float':
286 return 'double';
287
288 case 'Money':
289 return 'decimal(20,2)';
290
291 case 'Memo':
292 case 'RichTextEditor':
293 return 'text';
294
295 case 'Date':
296 return 'datetime';
297
298 default:
299 CRM_Core_Error::fatal();
300 }
301 }
302
303 static function store(&$params, $entityTable, $entityID) {
304 $cvParams = array();
305 foreach ($params as $fieldID => $param) {
306 foreach ($param as $index => $customValue) {
307 $cvParam = array(
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'],
318 );
319
320 // fix Date type to be timestamp, since that is how we store in db
321 if ($cvParam['type'] == 'Date') {
322 $cvParam['type'] = 'Timestamp';
323 }
324
325 if (!empty($customValue['id'])) {
326 $cvParam['id'] = $customValue['id'];
327 }
328 if (!array_key_exists($customValue['table_name'], $cvParams)) {
329 $cvParams[$customValue['table_name']] = array();
330 }
331
332 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
333 $cvParams[$customValue['table_name']][$index] = array();
334 }
335
336 $cvParams[$customValue['table_name']][$index][] = $cvParam;
337 }
338 }
339 if (!empty($cvParams)) {
340 self::create($cvParams);
341 }
342 }
343
344 static function postProcess(&$params, &$customFields, $entityTable, $entityID, $customFieldExtends) {
345 $customData = CRM_Core_BAO_CustomField::postProcess($params,
346 $customFields,
347 $entityID,
348 $customFieldExtends
349 );
350
351 if (!empty($customData)) {
352 self::store($customData, $entityTable, $entityID);
353 }
354 }
355
356 /**
357 * Return an array of all custom values associated with an entity.
358 *
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
365 * contact entity.
366 * @param array $fieldIDs optional list of fieldIDs that we want to retrieve. If this
367 * is set the entityType is ignored
368 *
369 * @param bool $formatMultiRecordField
370 *
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.
374 * @access public
375 * @static
376 */
377 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE) {
378 if (!$entityID) {
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');
382 return NULL;
383 }
384
385 $cond = array();
386 if ($entityType) {
387 $cond[] = "cg.extends IN ( '$entityType' )";
388 }
389 if ($fieldIDs &&
390 is_array($fieldIDs)
391 ) {
392 $fieldIDList = implode(',', $fieldIDs);
393 $cond[] = "cf.id IN ( $fieldIDList )";
394 }
395 if (empty($cond)) {
396 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
397 }
398 $cond = implode(' AND ', $cond);
399
400 // first find all the fields that extend this type of entity
401 $query = "
402 SELECT cg.table_name,
403 cg.id as groupID,
404 cg.is_multiple,
405 cf.column_name,
406 cf.id as fieldID,
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
411 AND cg.is_active = 1
412 AND cf.is_active = 1
413 AND $cond
414 ";
415 $dao = CRM_Core_DAO::executeQuery($query);
416
417 $select = $fields = $isMultiple = array();
418
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();
423 }
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;
428 }
429
430 $result = array();
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];
443 }
444 }
445 else {
446 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
447 }
448 } else {
449 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
450 }
451 }
452 else {
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];
457 }
458 }
459 else {
460 $result[$fieldID] = $dao->$fieldName;
461 }
462 }
463 }
464 }
465 }
466 return $result;
467 }
468
469 /**
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
473 *
474 * @array $params
475 *
476 * @return array
477 * @static
478 */
479 static function setValues(&$params) {
480
481 if (!isset($params['entityID']) ||
482 CRM_Utils_Type::escape($params['entityID'], 'Integer', FALSE) === NULL
483 ) {
484 return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
485 }
486
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
489 $values = array();
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',
496 array(1 => $fieldID)
497 ));
498 }
499 if (!array_key_exists($fieldID, $fieldValues)) {
500 $fieldValues[$fieldID] = array();
501 }
502 $id = -1;
503 if ($customFieldInfo[1]) {
504 $id = (int ) $customFieldInfo[1];
505 }
506 $fieldValues[$fieldID][] = array(
507 'value' => $v,
508 'id' => $id,
509 );
510 }
511 }
512
513 $fieldIDList = implode(',', array_keys($fieldValues));
514
515 // format it so that we can just use create
516 $sql = "
517 SELECT cg.table_name as table_name ,
518 cg.id as cg_id ,
519 cg.is_multiple as is_multiple,
520 cf.column_name as column_name,
521 cf.id as cf_id ,
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 )
527 ";
528
529 $dao = CRM_Core_DAO::executeQuery($sql);
530 $cvParams = array();
531
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'] === '') {
537 switch ($dataType) {
538 case 'String':
539 case 'Int':
540 case 'Link':
541 case 'Boolean':
542 $fieldValue['value'] = '';
543 break;
544
545 case 'Timestamp':
546 $fieldValue['value'] = NULL;
547 break;
548
549 case 'StateProvince':
550 case 'Country':
551 case 'Money':
552 case 'Float':
553 $fieldValue['value'] = (int)0;
554 break;
555 }
556 }
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',
560 array(
561 1 => $fieldValue['value'],
562 2 => $dao->data_type
563 )
564 ));
565 }
566
567 $cvParam = array(
568 'entity_id' => $params['entityID'],
569 'value' => $fieldValue['value'],
570 'type' => $dataType,
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,
576 );
577
578 if (!array_key_exists($dao->table_name, $cvParams)) {
579 $cvParams[$dao->table_name] = array();
580 }
581
582 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name])) {
583 $cvParams[$dao->table_name][$fieldValue['id']] = array();
584 }
585
586 if ($fieldValue['id'] > 0) {
587 $cvParam['id'] = $fieldValue['id'];
588 }
589 $cvParams[$dao->table_name][$fieldValue['id']][] = $cvParam;
590 }
591 }
592
593 if (!empty($cvParams)) {
594 self::create($cvParams);
595 return array('is_error' => 0, 'result' => 1);
596 }
597
598 return CRM_Core_Error::createAPIError(ts('Unknown error'));
599 }
600
601 /**
602 * Function to take in an array of entityID, custom_ID
603 * and gets the value from the appropriate table.
604 *
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 );
607 *
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
611 *
612 * @array $params
613 *
614 * @return array
615 * @static
616 */
617 static function &getValues(&$params) {
618 if (empty($params)) {
619 return NULL;
620 }
621 if (!isset($params['entityID']) ||
622 CRM_Utils_Type::escape($params['entityID'],
623 'Integer', FALSE
624 ) === NULL
625 ) {
626 return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
627 }
628
629 // first collect all the ids. The format is:
630 // custom_ID
631 $fieldIDs = array();
632 foreach ($params as $n => $v) {
633 $key = $idx = NULL;
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',
638 array(1 => $idx)
639 ));
640 }
641 $fieldIDs[] = (int ) $idx;
642 }
643 }
644
645 $default = array('Contact', 'Individual', 'Household', 'Organization');
646 if (!($type = CRM_Utils_Array::value('entityType', $params)) ||
647 in_array($params['entityType'], $default)
648 ) {
649 $type = NULL;
650 }
651 else {
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)) {
657 $type = NULL;
658 }
659 }
660 else {
661 return CRM_Core_Error::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
662 }
663 }
664 }
665
666 $values = self::getEntityValues($params['entityID'],
667 $type,
668 $fieldIDs
669 );
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
674 $result = array(
675 'is_error' => 1,
676 'error_message' => 'No values found for the specified entity ID and custom field(s).',
677 );
678 return $result;
679 }
680 else {
681 $result = array(
682 'is_error' => 0,
683 'entityID' => $params['entityID'],
684 );
685 foreach ($values as $id => $value) {
686 $result["custom_{$id}"] = $value;
687 }
688 return $result;
689 }
690 }
691 }
692