Update version numbers to 4.4 and lint php
[civicrm-core.git] / CRM / Core / BAO / CustomValueTable.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 (!CRM_Utils_Array::value('state_province_id', $states)) {
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 (!CRM_Utils_Array::value('country_id', $countries)) {
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 * @return the mysql data store placeholder
254 * @access public
255 * @static
256 */
257 public static function fieldToSQLType($type, $maxLength = 255) {
258 if (!isset($maxLength) ||
259 !is_numeric($maxLength) ||
260 $maxLength <= 0
261 ) {
262 $maxLength = 255;
263 }
264
265 switch ($type) {
266 case 'String':
267 case 'Link':
268 return "varchar($maxLength)";
269
270 case 'Boolean':
271 return 'tinyint';
272
273 case 'Int':
274 return 'int';
275 // the below three are FK's, and have constraints added to them
276
277 case 'ContactReference':
278 case 'StateProvince':
279 case 'Country':
280 case 'File':
281 return 'int unsigned';
282
283 case 'Float':
284 return 'double';
285
286 case 'Money':
287 return 'decimal(20,2)';
288
289 case 'Memo':
290 case 'RichTextEditor':
291 return 'text';
292
293 case 'Date':
294 return 'datetime';
295
296 default:
297 CRM_Core_Error::fatal();
298 }
299 }
300
301 static function store(&$params, $entityTable, $entityID) {
302 $cvParams = array();
303 foreach ($params as $fieldID => $param) {
304 foreach ($param as $index => $customValue) {
305 $cvParam = array(
306 'entity_table' => $entityTable,
307 'entity_id' => $entityID,
308 'value' => $customValue['value'],
309 'type' => $customValue['type'],
310 'custom_field_id' => $customValue['custom_field_id'],
311 'custom_group_id' => $customValue['custom_group_id'],
312 'table_name' => $customValue['table_name'],
313 'column_name' => $customValue['column_name'],
314 'is_multiple' => CRM_Utils_Array::value('is_multiple', $customValue),
315 'file_id' => $customValue['file_id'],
316 );
317
318 // fix Date type to be timestamp, since that is how we store in db
319 if ($cvParam['type'] == 'Date') {
320 $cvParam['type'] = 'Timestamp';
321 }
322
323 if (CRM_Utils_Array::value('id', $customValue)) {
324 $cvParam['id'] = $customValue['id'];
325 }
326 if (!array_key_exists($customValue['table_name'], $cvParams)) {
327 $cvParams[$customValue['table_name']] = array();
328 }
329
330 if (!array_key_exists($index, $cvParams[$customValue['table_name']])) {
331 $cvParams[$customValue['table_name']][$index] = array();
332 }
333
334 $cvParams[$customValue['table_name']][$index][] = $cvParam;
335 }
336 }
337 if (!empty($cvParams)) {
338 self::create($cvParams);
339 }
340 }
341
342 static function postProcess(&$params, &$customFields, $entityTable, $entityID, $customFieldExtends) {
343 $customData = CRM_Core_BAO_CustomField::postProcess($params,
344 $customFields,
345 $entityID,
346 $customFieldExtends
347 );
348
349 if (!empty($customData)) {
350 self::store($customData, $entityTable, $entityID);
351 }
352 }
353
354 /**
355 * Return an array of all custom values associated with an entity.
356 *
357 * @param int $entityID Identification number of the entity
358 * @param string $entityType Type of entity that the entityID corresponds to, specified
359 * as a string with format "'<EntityName>'". Comma separated
360 * list may be used to specify OR matches. Allowable values
361 * are enumerated types in civicrm_custom_group.extends field.
362 * Optional. Default value assumes entityID references a
363 * contact entity.
364 * @param array $fieldIDs optional list of fieldIDs that we want to retrieve. If this
365 * is set the entityType is ignored
366 *
367 * @return array $fields Array of custom values for the entity with key=>value
368 * pairs specified as civicrm_custom_field.id => custom value.
369 * Empty array if no custom values found.
370 * @access public
371 * @static
372 */
373 public static function &getEntityValues($entityID, $entityType = NULL, $fieldIDs = NULL, $formatMultiRecordField = FALSE) {
374 if (!$entityID) {
375 // adding this here since an empty contact id could have serious repurcussions
376 // like looping forever
377 CRM_Core_Error::fatal('Please file an issue with the backtrace');
378 return NULL;
379 }
380
381 $cond = array();
382 if ($entityType) {
383 $cond[] = "cg.extends IN ( '$entityType' )";
384 }
385 if ($fieldIDs &&
386 is_array($fieldIDs)
387 ) {
388 $fieldIDList = implode(',', $fieldIDs);
389 $cond[] = "cf.id IN ( $fieldIDList )";
390 }
391 if (empty($cond)) {
392 $cond[] = "cg.extends IN ( 'Contact', 'Individual', 'Household', 'Organization' )";
393 }
394 $cond = implode(' AND ', $cond);
395
396 // first find all the fields that extend this type of entity
397 $query = "
398 SELECT cg.table_name,
399 cg.id as groupID,
400 cg.is_multiple,
401 cf.column_name,
402 cf.id as fieldID
403 FROM civicrm_custom_group cg,
404 civicrm_custom_field cf
405 WHERE cf.custom_group_id = cg.id
406 AND cg.is_active = 1
407 AND cf.is_active = 1
408 AND $cond
409 ";
410 $dao = CRM_Core_DAO::executeQuery($query);
411
412 $select = $fields = $isMultiple = array();
413
414 while ($dao->fetch()) {
415 if (!array_key_exists($dao->table_name, $select)) {
416 $fields[$dao->table_name] = array();
417 $select[$dao->table_name] = array();
418 }
419 $fields[$dao->table_name][] = $dao->fieldID;
420 $select[$dao->table_name][] = "{$dao->column_name} AS custom_{$dao->fieldID}";
421 $isMultiple[$dao->table_name] = $dao->is_multiple ? TRUE : FALSE;
422 }
423
424 $result = array();
425 foreach ($select as $tableName => $clauses) {
426 $query = "SELECT id, " . implode(', ', $clauses) . " FROM $tableName WHERE entity_id = $entityID";
427 $dao = CRM_Core_DAO::executeQuery($query);
428 while ($dao->fetch()) {
429 foreach ($fields[$tableName] as $fieldID) {
430 $fieldName = "custom_{$fieldID}";
431 if ($isMultiple[$tableName]) {
432 if ($formatMultiRecordField) {
433 $result["{$dao->id}"]["{$fieldID}"] = $dao->$fieldName;
434 } else {
435 $result["{$fieldID}_{$dao->id}"] = $dao->$fieldName;
436 }
437 }
438 else {
439 $result[$fieldID] = $dao->$fieldName;
440 }
441 }
442 }
443 }
444 return $result;
445 }
446
447 /**
448 * Function to take in an array of entityID, custom_XXX => value
449 * and set the value in the appropriate table. Should also be able
450 * to set the value to null. Follows api parameter/return conventions
451 *
452 * @array $params
453 *
454 * @return array
455 * @static
456 */
457 static function setValues(&$params) {
458
459 if (!isset($params['entityID']) ||
460 CRM_Utils_Type::escape($params['entityID'], 'Integer', FALSE) === NULL
461 ) {
462 return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
463 }
464
465 // first collect all the id/value pairs. The format is:
466 // custom_X => value or custom_X_VALUEID => value (for multiple values), VALUEID == -1, -2 etc for new insertions
467 $values = array();
468 $fieldValues = array();
469 foreach ($params as $n => $v) {
470 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($n, TRUE)) {
471 $fieldID = (int ) $customFieldInfo[0];
472 if (CRM_Utils_Type::escape($fieldID, 'Integer', FALSE) === NULL) {
473 return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
474 array(1 => $fieldID)
475 ));
476 }
477 if (!array_key_exists($fieldID, $fieldValues)) {
478 $fieldValues[$fieldID] = array();
479 }
480 $id = -1;
481 if ($customFieldInfo[1]) {
482 $id = (int ) $customFieldInfo[1];
483 }
484 $fieldValues[$fieldID][] = array(
485 'value' => $v,
486 'id' => $id,
487 );
488 }
489 }
490
491 $fieldIDList = implode(',', array_keys($fieldValues));
492
493 // format it so that we can just use create
494 $sql = "
495 SELECT cg.table_name as table_name ,
496 cg.id as cg_id ,
497 cg.is_multiple as is_multiple,
498 cf.column_name as column_name,
499 cf.id as cf_id ,
500 cf.data_type as data_type
501 FROM civicrm_custom_group cg,
502 civicrm_custom_field cf
503 WHERE cf.custom_group_id = cg.id
504 AND cf.id IN ( $fieldIDList )
505 ";
506
507 $dao = CRM_Core_DAO::executeQuery($sql);
508 $cvParams = array();
509
510 while ($dao->fetch()) {
511 $dataType = $dao->data_type == 'Date' ? 'Timestamp' : $dao->data_type;
512 foreach ($fieldValues[$dao->cf_id] as $fieldValue) {
513 // Format null values correctly
514 if ($fieldValue['value'] === NULL || $fieldValue['value'] === '') {
515 switch ($dataType) {
516 case 'String':
517 case 'Int':
518 case 'Link':
519 case 'Boolean':
520 $fieldValue['value'] = '';
521 break;
522
523 case 'Timestamp':
524 $fieldValue['value'] = NULL;
525 break;
526
527 case 'StateProvince':
528 case 'Country':
529 case 'Money':
530 case 'Float':
531 $fieldValue['value'] = (int)0;
532 break;
533 }
534 }
535 // Ensure that value is of the right data type
536 elseif (CRM_Utils_Type::escape($fieldValue['value'], $dataType, FALSE) === NULL) {
537 return CRM_Core_Error::createAPIError(ts('value: %1 is not of the right field data type: %2',
538 array(
539 1 => $fieldValue['value'],
540 2 => $dao->data_type
541 )
542 ));
543 }
544
545 $cvParam = array(
546 'entity_id' => $params['entityID'],
547 'value' => $fieldValue['value'],
548 'type' => $dataType,
549 'custom_field_id' => $dao->cf_id,
550 'custom_group_id' => $dao->cg_id,
551 'table_name' => $dao->table_name,
552 'column_name' => $dao->column_name,
553 'is_multiple' => $dao->is_multiple,
554 );
555
556 if (!array_key_exists($dao->table_name, $cvParams)) {
557 $cvParams[$dao->table_name] = array();
558 }
559
560 if (!array_key_exists($fieldValue['id'], $cvParams[$dao->table_name])) {
561 $cvParams[$dao->table_name][$fieldValue['id']] = array();
562 }
563
564 if ($fieldValue['id'] > 0) {
565 $cvParam['id'] = $fieldValue['id'];
566 }
567 $cvParams[$dao->table_name][$fieldValue['id']][] = $cvParam;
568 }
569 }
570
571 if (!empty($cvParams)) {
572 self::create($cvParams);
573 return array('is_error' => 0, 'result' => 1);
574 }
575
576 return CRM_Core_Error::createAPIError(ts('Unknown error'));
577 }
578
579 /**
580 * Function to take in an array of entityID, custom_ID
581 * and gets the value from the appropriate table.
582 *
583 * To get the values of custom fields with IDs 13 and 43 for contact ID 1327, use:
584 * $params = array( 'entityID' => 1327, 'custom_13' => 1, 'custom_43' => 1 );
585 *
586 * Entity Type will be infered by the custom fields you request
587 * Specify $params['entityType'] if you do not supply any custom fields to return
588 * and entity type is other than Contact
589 *
590 * @array $params
591 *
592 * @return array
593 * @static
594 */
595 static function &getValues(&$params) {
596 if (empty($params)) {
597 return NULL;
598 }
599 if (!isset($params['entityID']) ||
600 CRM_Utils_Type::escape($params['entityID'],
601 'Integer', FALSE
602 ) === NULL
603 ) {
604 return CRM_Core_Error::createAPIError(ts('entityID needs to be set and of type Integer'));
605 }
606
607 // first collect all the ids. The format is:
608 // custom_ID
609 $fieldIDs = array();
610 foreach ($params as $n => $v) {
611 $key = $idx = NULL;
612 if (substr($n, 0, 7) == 'custom_') {
613 $idx = substr($n, 7);
614 if (CRM_Utils_Type::escape($idx, 'Integer', FALSE) === NULL) {
615 return CRM_Core_Error::createAPIError(ts('field ID needs to be of type Integer for index %1',
616 array(1 => $idx)
617 ));
618 }
619 $fieldIDs[] = (int ) $idx;
620 }
621 }
622
623 $default = array('Contact', 'Individual', 'Household', 'Organization');
624 if (!($type = CRM_Utils_Array::value('entityType', $params)) ||
625 in_array($params['entityType'], $default)
626 ) {
627 $type = NULL;
628 }
629 else {
630 $entities = CRM_Core_SelectValues::customGroupExtends();
631 if (!array_key_exists($type, $entities)) {
632 if (in_array($type, $entities)) {
633 $type = $entities[$type];
634 if (in_array($type, $default)) {
635 $type = NULL;
636 }
637 }
638 else {
639 return CRM_Core_Error::createAPIError(ts('Invalid entity type') . ': "' . $type . '"');
640 }
641 }
642 }
643
644 $values = self::getEntityValues($params['entityID'],
645 $type,
646 $fieldIDs
647 );
648 if (empty($values)) {
649 // note that this behaviour is undesirable from an API point of view - it should return an empty array
650 // since this is also called by the merger code & not sure the consequences of changing
651 // are just handling undoing this in the api layer. ie. converting the error back into a success
652 $result = array(
653 'is_error' => 1,
654 'error_message' => 'No values found for the specified entity ID and custom field(s).',
655 );
656 return $result;
657 }
658 else {
659 $result = array(
660 'is_error' => 0,
661 'entityID' => $params['entityID'],
662 );
663 foreach ($values as $id => $value) {
664 $result["custom_{$id}"] = $value;
665 }
666 return $result;
667 }
668 }
669 }
670