CRM-17646 - Refactor out CRM_Core_BAO_CustomGroup::formatCustomValues
[civicrm-core.git] / CRM / Core / BAO / CustomField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33
34 /**
35 * Business objects for managing custom data fields.
36 */
37 class CRM_Core_BAO_CustomField extends CRM_Core_DAO_CustomField {
38
39 /**
40 * Array for valid combinations of data_type & descriptions.
41 *
42 * @var array
43 */
44 public static $_dataType = NULL;
45
46 /**
47 * Array for valid combinations of data_type & html_type.
48 *
49 * @var array
50 */
51 public static $_dataToHtml = NULL;
52
53 /**
54 * Array to hold (formatted) fields for import
55 *
56 * @var array
57 */
58 public static $_importFields = NULL;
59
60 /**
61 * @var array
62 */
63 public static $displayInfoCache = array();
64
65 /**
66 * Build and retrieve the list of data types and descriptions.
67 *
68 * @return array
69 * Data type => Description
70 */
71 public static function &dataType() {
72 if (!(self::$_dataType)) {
73 self::$_dataType = array(
74 'String' => ts('Alphanumeric'),
75 'Int' => ts('Integer'),
76 'Float' => ts('Number'),
77 'Money' => ts('Money'),
78 'Memo' => ts('Note'),
79 'Date' => ts('Date'),
80 'Boolean' => ts('Yes or No'),
81 'StateProvince' => ts('State/Province'),
82 'Country' => ts('Country'),
83 'File' => ts('File'),
84 'Link' => ts('Link'),
85 'ContactReference' => ts('Contact Reference'),
86 );
87 }
88 return self::$_dataType;
89 }
90
91 /**
92 * Get data to html array.
93 *
94 * (Does this caching achieve anything?)
95 *
96 * @return array
97 */
98 public static function dataToHtml() {
99 if (!self::$_dataToHtml) {
100 self::$_dataToHtml = array(
101 array(
102 'Text' => 'Text',
103 'Select' => 'Select',
104 'Radio' => 'Radio',
105 'CheckBox' => 'CheckBox',
106 'Multi-Select' => 'Multi-Select',
107 'AdvMulti-Select' => 'AdvMulti-Select',
108 'Autocomplete-Select' => 'Autocomplete-Select',
109 ),
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
112 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
113 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
114 array('Date' => 'Select Date'),
115 array('Radio' => 'Radio'),
116 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
117 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
118 array('File' => 'File'),
119 array('Link' => 'Link'),
120 array('ContactReference' => 'Autocomplete-Select'),
121 );
122 }
123 return self::$_dataToHtml;
124 }
125
126 /**
127 * Takes an associative array and creates a custom field object.
128 *
129 * This function is invoked from within the web form layer and also from the api layer
130 *
131 * @param array $params
132 * (reference) an assoc array of name/value pairs.
133 *
134 * @return CRM_Core_DAO_CustomField
135 */
136 public static function create(&$params) {
137 $origParams = array_merge(array(), $params);
138
139 if (!isset($params['id'])) {
140 if (!isset($params['column_name'])) {
141 // if add mode & column_name not present, calculate it.
142 $params['column_name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 32));
143 }
144 if (!isset($params['name'])) {
145 $params['name'] = CRM_Utils_String::munge($params['label'], '_', 64);
146 }
147 }
148 else {
149 $params['column_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
150 $params['id'],
151 'column_name'
152 );
153 }
154 $columnName = $params['column_name'];
155
156 $indexExist = FALSE;
157 //as during create if field is_searchable we had created index.
158 if (!empty($params['id'])) {
159 $indexExist = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
160 }
161
162 switch (CRM_Utils_Array::value('html_type', $params)) {
163 case 'Select Date':
164 if (empty($params['date_format'])) {
165 $config = CRM_Core_Config::singleton();
166 $params['date_format'] = $config->dateInputFormat;
167 }
168 break;
169
170 case 'CheckBox':
171 case 'AdvMulti-Select':
172 case 'Multi-Select':
173 if (isset($params['default_checkbox_option'])) {
174 $tempArray = array_keys($params['default_checkbox_option']);
175 $defaultArray = array();
176 foreach ($tempArray as $k => $v) {
177 if ($params['option_value'][$v]) {
178 $defaultArray[] = $params['option_value'][$v];
179 }
180 }
181
182 if (!empty($defaultArray)) {
183 // also add the separator before and after the value per new convention (CRM-1604)
184 $params['default_value'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $defaultArray) . CRM_Core_DAO::VALUE_SEPARATOR;
185 }
186 }
187 else {
188 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
189 ) {
190 $params['default_value'] = $params['option_value'][$params['default_option']];
191 }
192 }
193 break;
194 }
195
196 $transaction = new CRM_Core_Transaction();
197 // create any option group & values if required
198 if ($params['html_type'] != 'Text' &&
199 in_array($params['data_type'], array(
200 'String',
201 'Int',
202 'Float',
203 'Money',
204 ))
205 ) {
206
207 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
208 $params['custom_group_id'],
209 'table_name'
210 );
211
212 //CRM-16659: if option_value then create an option group for this custom field.
213 if ($params['option_type'] == 1 && (empty($params['option_group_id']) || !empty($params['option_value']))) {
214 // first create an option group for this custom group
215 $optionGroup = new CRM_Core_DAO_OptionGroup();
216 $optionGroup->name = "{$columnName}_" . date('YmdHis');
217 $optionGroup->title = $params['label'];
218 $optionGroup->is_active = 1;
219 $optionGroup->save();
220 $params['option_group_id'] = $optionGroup->id;
221 if (!empty($params['option_value']) && is_array($params['option_value'])) {
222 foreach ($params['option_value'] as $k => $v) {
223 if (strlen(trim($v))) {
224 $optionValue = new CRM_Core_DAO_OptionValue();
225 $optionValue->option_group_id = $optionGroup->id;
226 $optionValue->label = $params['option_label'][$k];
227 $optionValue->name = CRM_Utils_String::titleToVar($params['option_label'][$k]);
228 switch ($params['data_type']) {
229 case 'Money':
230 $optionValue->value = CRM_Utils_Rule::cleanMoney($v);
231 break;
232
233 case 'Int':
234 $optionValue->value = intval($v);
235 break;
236
237 case 'Float':
238 $optionValue->value = floatval($v);
239 break;
240
241 default:
242 $optionValue->value = trim($v);
243 }
244
245 $optionValue->weight = $params['option_weight'][$k];
246 $optionValue->is_active = CRM_Utils_Array::value($k, $params['option_status'], FALSE);
247 $optionValue->save();
248 }
249 }
250 }
251 }
252 }
253
254 // check for orphan option groups
255 if (!empty($params['option_group_id'])) {
256 if (!empty($params['id'])) {
257 self::fixOptionGroups($params['id'], $params['option_group_id']);
258 }
259
260 // if we do not have a default value
261 // retrieve it from one of the other custom fields which use this option group
262 if (empty($params['default_value'])) {
263 //don't insert only value separator as default value, CRM-4579
264 $defaultValue = self::getOptionGroupDefault($params['option_group_id'],
265 $params['html_type']
266 );
267
268 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR,
269 $defaultValue
270 ))
271 ) {
272 $params['default_value'] = $defaultValue;
273 }
274 }
275 }
276
277 // since we need to save option group id :)
278 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
279 $params['attributes'] = 'rows=4, cols=60';
280 }
281
282 $customField = new CRM_Core_DAO_CustomField();
283 $customField->copyValues($params);
284 $customField->is_required = CRM_Utils_Array::value('is_required', $params, FALSE);
285 $customField->is_searchable = CRM_Utils_Array::value('is_searchable', $params, FALSE);
286 $customField->in_selector = CRM_Utils_Array::value('in_selector', $params, FALSE);
287 $customField->is_search_range = CRM_Utils_Array::value('is_search_range', $params, FALSE);
288 //CRM-15792 - Custom field gets disabled if is_active not set
289 $customField->is_active = CRM_Utils_Array::value('is_active', $params, TRUE);
290 $customField->is_view = CRM_Utils_Array::value('is_view', $params, FALSE);
291 $customField->save();
292
293 // make sure all values are present in the object for further processing
294 $customField->find(TRUE);
295
296 $triggerRebuild = CRM_Utils_Array::value('triggerRebuild', $params, TRUE);
297 //create/drop the index when we toggle the is_searchable flag
298 if (!empty($params['id'])) {
299 self::createField($customField, 'modify', $indexExist, $triggerRebuild);
300 }
301 else {
302 if (!isset($origParams['column_name'])) {
303 $columnName .= "_{$customField->id}";
304 $params['column_name'] = $columnName;
305 }
306 $customField->column_name = $columnName;
307 $customField->save();
308 // make sure all values are present in the object
309 $customField->find(TRUE);
310
311 $indexExist = FALSE;
312 self::createField($customField, 'add', $indexExist, $triggerRebuild);
313 }
314
315 // complete transaction
316 $transaction->commit();
317
318 CRM_Utils_System::flushCache();
319
320 return $customField;
321 }
322
323 /**
324 * Fetch object based on array of properties.
325 *
326 * @param array $params
327 * (reference ) an assoc array of name/value pairs.
328 * @param array $defaults
329 * (reference ) an assoc array to hold the flattened values.
330 *
331 * @return CRM_Core_DAO_CustomField
332 */
333 public static function retrieve(&$params, &$defaults) {
334 return CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
335 }
336
337 /**
338 * Update the is_active flag in the db.
339 *
340 * @param int $id
341 * Id of the database record.
342 * @param bool $is_active
343 * Value we want to set the is_active field.
344 *
345 * @return Object
346 * DAO object on success, null otherwise
347 */
348 public static function setIsActive($id, $is_active) {
349
350 CRM_Utils_System::flushCache();
351
352 //enable-disable CustomField
353 CRM_Core_BAO_UFField::setUFField($id, $is_active);
354 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
355 }
356
357 /**
358 * Get the field title.
359 *
360 * @param int $id
361 * Id of field.
362 *
363 * @return string
364 * name
365 */
366 public static function getTitle($id) {
367 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
368 }
369
370 /**
371 * @param string $context
372 * @return array|bool
373 */
374 public function getOptions($context = NULL) {
375 CRM_Core_DAO::buildOptionsContext($context);
376
377 if (!$this->id) {
378 return FALSE;
379 }
380 if (!$this->data_type || !$this->custom_group_id) {
381 $this->find(TRUE);
382 }
383
384 if (!empty($this->option_group_id)) {
385 $options = CRM_Core_OptionGroup::valuesByID(
386 $this->option_group_id,
387 FALSE,
388 FALSE,
389 FALSE,
390 'label',
391 !($context == 'validate' || $context == 'get')
392 );
393 }
394 elseif ($this->data_type === 'StateProvince') {
395 $options = CRM_Core_Pseudoconstant::stateProvince();
396 }
397 elseif ($this->data_type === 'Country') {
398 $options = $context == 'validate' ? CRM_Core_Pseudoconstant::countryIsoCode() : CRM_Core_Pseudoconstant::country();
399 }
400 elseif ($this->data_type === 'Boolean') {
401 $options = $context == 'validate' ? array(0, 1) : CRM_Core_SelectValues::boolean();
402 }
403 else {
404 return false;
405 }
406 CRM_Utils_Hook::customFieldOptions($this->id, $options, FALSE);
407 $entity = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id, 'extends');
408 $entity = in_array($entity, array('Individual', 'Household', 'Organization')) ? 'Contact' : $entity;
409 CRM_Utils_Hook::fieldOptions($entity, "custom_{$this->id}", $options, array('context' => $context));
410 return $options;
411 }
412
413 /**
414 * Store and return an array of all active custom fields.
415 *
416 * @param string $customDataType
417 * Type of Custom Data; empty is a synonym for "all contact data types".
418 * @param bool $showAll
419 * If true returns all fields (includes disabled fields).
420 * @param bool $inline
421 * If true returns all inline fields (includes disabled fields).
422 * @param int $customDataSubType
423 * Custom Data sub type value.
424 * @param int $customDataSubName
425 * Custom Data sub name value.
426 * @param bool $onlyParent
427 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
428 * @param bool $onlySubType
429 * Return only custom data for subtype.
430 * @param bool $checkPermission
431 * If false, do not include permissioning clause.
432 *
433 * @return array
434 * an array of active custom fields.
435 */
436 public static function &getFields(
437 $customDataType = 'Individual',
438 $showAll = FALSE,
439 $inline = FALSE,
440 $customDataSubType = NULL,
441 $customDataSubName = NULL,
442 $onlyParent = FALSE,
443 $onlySubType = FALSE,
444 $checkPermission = TRUE
445 ) {
446 if (empty($customDataType)) {
447 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
448 }
449 if ($customDataType && !is_array($customDataType)) {
450
451 if (in_array($customDataType, CRM_Contact_BAO_ContactType::subTypes())) {
452 // This is the case when getFieldsForImport() requires fields
453 // limited strictly to a subtype.
454 $customDataSubType = $customDataType;
455 $customDataType = CRM_Contact_BAO_ContactType::getBasicType($customDataType);
456 $onlySubType = TRUE;
457 }
458
459 if (in_array($customDataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
460 // this makes the method flexible to support retrieving fields
461 // for multiple extends value.
462 $customDataType = array($customDataType);
463 }
464 }
465
466 $customDataSubType = CRM_Utils_Array::explodePadded($customDataSubType);
467
468 if (is_array($customDataType)) {
469 $cacheKey = implode('_', $customDataType);
470 }
471 else {
472 $cacheKey = $customDataType;
473 }
474
475 $cacheKey .= !empty($customDataSubType) ? ('_' . implode('_', $customDataSubType)) : '_0';
476 $cacheKey .= $customDataSubName ? "{$customDataSubName}_" : '_0';
477 $cacheKey .= $showAll ? '_1' : '_0';
478 $cacheKey .= $inline ? '_1_' : '_0_';
479 $cacheKey .= $onlyParent ? '_1_' : '_0_';
480 $cacheKey .= $onlySubType ? '_1_' : '_0_';
481 $cacheKey .= $checkPermission ? '_1_' : '_0_';
482
483 $cgTable = CRM_Core_DAO_CustomGroup::getTableName();
484
485 // also get the permission stuff here
486 if ($checkPermission) {
487 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
488 "{$cgTable}."
489 );
490 }
491 else {
492 $permissionClause = '(1)';
493 }
494
495 // lets md5 permission clause and take first 8 characters
496 $cacheKey .= substr(md5($permissionClause), 0, 8);
497
498 if (strlen($cacheKey) > 40) {
499 $cacheKey = md5($cacheKey);
500 }
501
502 if (!self::$_importFields ||
503 CRM_Utils_Array::value($cacheKey, self::$_importFields) === NULL
504 ) {
505 if (!self::$_importFields) {
506 self::$_importFields = array();
507 }
508
509 // check if we can retrieve from database cache
510 $fields = CRM_Core_BAO_Cache::getItem('contact fields', "custom importableFields $cacheKey");
511
512 if ($fields === NULL) {
513 $cfTable = self::getTableName();
514
515 $extends = '';
516 if (is_array($customDataType)) {
517 $value = NULL;
518 foreach ($customDataType as $dataType) {
519 if (in_array($dataType, array_keys(CRM_Core_SelectValues::customGroupExtends()))) {
520 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
521 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "', 'Contact' ";
522 }
523 else {
524 $val = "'" . CRM_Utils_Type::escape($dataType, 'String') . "'";
525 }
526 $value = $value ? $value . ", {$val}" : $val;
527 }
528 }
529 if ($value) {
530 $extends = "AND $cgTable.extends IN ( $value ) ";
531 }
532 }
533
534 if (!empty($customDataType) && empty($extends)) {
535 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
536 self::$_importFields[$cacheKey] = array();
537 return self::$_importFields[$cacheKey];
538 }
539
540 if ($onlyParent) {
541 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
542 }
543
544 $query = "SELECT $cfTable.id, $cfTable.label,
545 $cgTable.title,
546 $cfTable.data_type,
547 $cfTable.html_type,
548 $cfTable.default_value,
549 $cfTable.options_per_line, $cfTable.text_length,
550 $cfTable.custom_group_id,
551 $cfTable.is_required,
552 $cgTable.extends, $cfTable.is_search_range,
553 $cgTable.extends_entity_column_value,
554 $cgTable.extends_entity_column_id,
555 $cfTable.is_view,
556 $cfTable.option_group_id,
557 $cfTable.date_format,
558 $cfTable.time_format,
559 $cgTable.is_multiple,
560 og.name as option_group_name
561 FROM $cfTable
562 INNER JOIN $cgTable
563 ON $cfTable.custom_group_id = $cgTable.id
564 LEFT JOIN civicrm_option_group og
565 ON $cfTable.option_group_id = og.id
566 WHERE ( 1 ) ";
567
568 if (!$showAll) {
569 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
570 }
571
572 if ($inline) {
573 $query .= " AND $cgTable.style = 'Inline' ";
574 }
575
576 //get the custom fields for specific type in
577 //combination with fields those support any type.
578 if (!empty($customDataSubType)) {
579 $subtypeClause = array();
580 foreach ($customDataSubType as $subtype) {
581 $subtype = CRM_Core_DAO::VALUE_SEPARATOR . $subtype . CRM_Core_DAO::VALUE_SEPARATOR;
582 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
583 }
584 if (!$onlySubType) {
585 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
586 }
587 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
588 }
589
590 if ($customDataSubName) {
591 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
592 }
593
594 // also get the permission stuff here
595 if ($checkPermission) {
596 $permissionClause = CRM_Core_Permission::customGroupClause(CRM_Core_Permission::VIEW,
597 "{$cgTable}.", TRUE
598 );
599 }
600 else {
601 $permissionClause = '(1)';
602 }
603
604 $query .= " $extends AND $permissionClause
605 ORDER BY $cgTable.weight, $cgTable.title,
606 $cfTable.weight, $cfTable.label";
607
608 $dao = CRM_Core_DAO::executeQuery($query);
609
610 $fields = array();
611 while (($dao->fetch()) != NULL) {
612 $fields[$dao->id]['label'] = $dao->label;
613 $fields[$dao->id]['groupTitle'] = $dao->title;
614 $fields[$dao->id]['data_type'] = $dao->data_type;
615 $fields[$dao->id]['html_type'] = $dao->html_type;
616 $fields[$dao->id]['default_value'] = $dao->default_value;
617 $fields[$dao->id]['text_length'] = $dao->text_length;
618 $fields[$dao->id]['options_per_line'] = $dao->options_per_line;
619 $fields[$dao->id]['custom_group_id'] = $dao->custom_group_id;
620 $fields[$dao->id]['extends'] = $dao->extends;
621 $fields[$dao->id]['is_search_range'] = $dao->is_search_range;
622 $fields[$dao->id]['extends_entity_column_value'] = $dao->extends_entity_column_value;
623 $fields[$dao->id]['extends_entity_column_id'] = $dao->extends_entity_column_id;
624 $fields[$dao->id]['is_view'] = $dao->is_view;
625 $fields[$dao->id]['is_multiple'] = $dao->is_multiple;
626 $fields[$dao->id]['option_group_id'] = $dao->option_group_id;
627 $fields[$dao->id]['date_format'] = $dao->date_format;
628 $fields[$dao->id]['time_format'] = $dao->time_format;
629 $fields[$dao->id]['is_required'] = $dao->is_required;
630 self::getOptionsForField($fields[$dao->id], $dao->option_group_name);
631 }
632
633 CRM_Core_BAO_Cache::setItem($fields,
634 'contact fields',
635 "custom importableFields $cacheKey"
636 );
637 }
638 self::$_importFields[$cacheKey] = $fields;
639 }
640
641 return self::$_importFields[$cacheKey];
642 }
643
644 /**
645 * Return the field ids and names (with groups) for import purpose.
646 *
647 * @param int|string $contactType Contact type
648 * @param bool $showAll
649 * If true returns all fields (includes disabled fields).
650 * @param bool $onlyParent
651 * Return fields ONLY related to basic types.
652 * @param bool $search
653 * When called from search and multiple records need to be returned.
654 * @param bool $checkPermission
655 * If false, do not include permissioning clause.
656 *
657 * @param bool $withMultiple
658 *
659 * @return array
660 */
661 public static function getFieldsForImport(
662 $contactType = 'Individual',
663 $showAll = FALSE,
664 $onlyParent = FALSE,
665 $search = FALSE,
666 $checkPermission = TRUE,
667 $withMultiple = FALSE
668 ) {
669 // Note: there are situations when we want getFieldsForImport() return fields related
670 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
671 $fields = &self::getFields($contactType,
672 $showAll,
673 FALSE,
674 NULL,
675 NULL,
676 $onlyParent,
677 FALSE,
678 $checkPermission
679 );
680
681 $importableFields = array();
682 foreach ($fields as $id => $values) {
683 // for now we should not allow multiple fields in profile / export etc, hence unsetting
684 if (!$search &&
685 (!empty($values['is_multiple']) && !$withMultiple)
686 ) {
687 continue;
688 }
689
690 /* generate the key for the fields array */
691
692 $key = "custom_$id";
693
694 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array::value(0, $values));
695 $importableFields[$key] = array(
696 'name' => $key,
697 'title' => CRM_Utils_Array::value('label', $values),
698 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
699 'import' => 1,
700 'custom_field_id' => $id,
701 'options_per_line' => CRM_Utils_Array::value('options_per_line', $values),
702 'text_length' => CRM_Utils_Array::value('text_length', $values, 255),
703 'data_type' => CRM_Utils_Array::value('data_type', $values),
704 'html_type' => CRM_Utils_Array::value('html_type', $values),
705 'is_search_range' => CRM_Utils_Array::value('is_search_range', $values),
706 );
707
708 // CRM-6681, pass date and time format when html_type = Select Date
709 if (CRM_Utils_Array::value('html_type', $values) == 'Select Date') {
710 $importableFields[$key]['date_format'] = CRM_Utils_Array::value('date_format', $values);
711 $importableFields[$key]['time_format'] = CRM_Utils_Array::value('time_format', $values);
712 }
713 }
714
715 return $importableFields;
716 }
717
718 /**
719 * Get the field id from an import key.
720 *
721 * @param string $key
722 * The key to parse.
723 *
724 * @param bool $all
725 *
726 * @return int|null
727 * The id (if exists)
728 */
729 public static function getKeyID($key, $all = FALSE) {
730 $match = array();
731 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
732 if (!$all) {
733 return $match[1];
734 }
735 else {
736 return array(
737 $match[1],
738 CRM_Utils_Array::value(2, $match),
739 );
740 }
741 }
742 return $all ? array(NULL, NULL) : NULL;
743 }
744
745 /**
746 * Use the cache to get all values of a specific custom field.
747 *
748 * @param int $fieldID
749 * The custom field ID.
750 *
751 * @return CRM_Core_DAO_CustomField
752 * The field object.
753 */
754 public static function getFieldObject($fieldID) {
755 $field = new CRM_Core_DAO_CustomField();
756
757 // check if we can get the field values from the system cache
758 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
759 $cache = CRM_Utils_Cache::singleton();
760 $fieldValues = $cache->get($cacheKey);
761 if (empty($fieldValues)) {
762 $field->id = $fieldID;
763 if (!$field->find(TRUE)) {
764 CRM_Core_Error::fatal();
765 }
766
767 $fieldValues = array();
768 CRM_Core_DAO::storeValues($field, $fieldValues);
769
770 $cache->set($cacheKey, $fieldValues);
771 }
772 else {
773 $field->copyValues($fieldValues);
774 }
775
776 return $field;
777 }
778
779 /**
780 * This function for building custom fields.
781 *
782 * @param CRM_Core_Form $qf
783 * Form object (reference).
784 * @param string $elementName
785 * Name of the custom field.
786 * @param int $fieldId
787 * @param bool $inactiveNeeded
788 * -deprecated.
789 * @param bool $useRequired
790 * True if required else false.
791 * @param bool $search
792 * True if used for search else false.
793 * @param string $label
794 * Label for custom field.
795 */
796 public static function addQuickFormElement(
797 &$qf,
798 $elementName,
799 $fieldId,
800 $inactiveNeeded = FALSE,
801 $useRequired = TRUE,
802 $search = FALSE,
803 $label = NULL
804 ) {
805 $field = self::getFieldObject($fieldId);
806 $widget = $field->html_type;
807
808 // Custom field HTML should indicate group+field name
809 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id);
810 $dataCrmCustomVal = $groupName . ':' . $field->name;
811 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
812 $field->attributes .= $dataCrmCustomAttr;
813
814 // Fixed for Issue CRM-2183
815 if ($widget == 'TextArea' && $search) {
816 $widget = 'Text';
817 }
818
819 $placeholder = $search ? ts('- any -') : ($useRequired ? ts('- select -') : ts('- none -'));
820
821 // FIXME: Why are select state/country separate widget types?
822 $isSelect = (in_array($widget, array(
823 'Select',
824 'Multi-Select',
825 'Select State/Province',
826 'Multi-Select State/Province',
827 'Select Country',
828 'Multi-Select Country',
829 'AdvMulti-Select',
830 'CheckBox',
831 'Radio',
832 )));
833
834 if ($isSelect) {
835 $options = CRM_Utils_Array::value('values', civicrm_api3('contact', 'getoptions', array(
836 'field' => "custom_$fieldId",
837 'context' => $search ? 'search' : 'create',
838 ), array()));
839
840 // Consolidate widget types to simplify the below switch statement
841 if ($search || ($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
842 $widget = 'Select';
843 }
844 $selectAttributes = array(
845 'data-crm-custom' => $dataCrmCustomVal,
846 'class' => 'crm-select2',
847 );
848 // Search field is always multi-select
849 if ($search || strpos($field->html_type, 'Multi') !== FALSE) {
850 $selectAttributes['class'] .= ' huge';
851 $selectAttributes['multiple'] = 'multiple';
852 $selectAttributes['placeholder'] = $placeholder;
853 }
854 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
855 if ($field->option_group_id && !$search && $widget == 'Select' && CRM_Core_Permission::check('administer CiviCRM')) {
856 $selectAttributes += array(
857 'data-api-entity' => 'contact',
858 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
859 'data-api-field' => 'custom_' . $field->id,
860 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id),
861 );
862 }
863 }
864
865 if (!isset($label)) {
866 $label = $field->label;
867 }
868
869 // at some point in time we might want to split the below into small functions
870
871 switch ($widget) {
872 case 'Text':
873 case 'Link':
874 if ($field->is_search_range && $search) {
875 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes);
876 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes);
877 }
878 else {
879 $element = &$qf->add('text', $elementName, $label,
880 $field->attributes,
881 $useRequired && !$search
882 );
883 }
884 break;
885
886 case 'TextArea':
887 $attributes = $dataCrmCustomAttr;
888 if ($field->note_rows) {
889 $attributes .= 'rows=' . $field->note_rows;
890 }
891 else {
892 $attributes .= 'rows=4';
893 }
894 if ($field->note_columns) {
895 $attributes .= ' cols=' . $field->note_columns;
896 }
897 else {
898 $attributes .= ' cols=60';
899 }
900 if ($field->text_length) {
901 $attributes .= ' maxlength=' . $field->text_length;
902 }
903 $element = &$qf->add('textarea',
904 $elementName,
905 $label,
906 $attributes,
907 $useRequired && !$search
908 );
909 break;
910
911 case 'Select Date':
912 if ($field->is_search_range && $search) {
913 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
914 array(
915 'format' => $field->date_format,
916 'timeFormat' => $field->time_format,
917 'startOffset' => $field->start_date_years,
918 'endOffset' => $field->end_date_years,
919 'data-crm-custom' => $dataCrmCustomVal,
920 )
921 );
922
923 $qf->addDate($elementName . '_to', ts('To'), FALSE,
924 array(
925 'format' => $field->date_format,
926 'timeFormat' => $field->time_format,
927 'startOffset' => $field->start_date_years,
928 'endOffset' => $field->end_date_years,
929 'data-crm-custom' => $dataCrmCustomVal,
930 )
931 );
932 }
933 else {
934 $required = $useRequired && !$search;
935
936 $qf->addDate($elementName, $label, $required, array(
937 'format' => $field->date_format,
938 'timeFormat' => $field->time_format,
939 'startOffset' => $field->start_date_years,
940 'endOffset' => $field->end_date_years,
941 'data-crm-custom' => $dataCrmCustomVal,
942 ));
943 }
944 break;
945
946 case 'Radio':
947 $choice = array();
948 foreach ($options as $v => $l) {
949 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes);
950 }
951 $group = $qf->addGroup($choice, $elementName, $label);
952 if ($useRequired && !$search) {
953 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
954 }
955 else {
956 $group->setAttribute('allowClear', TRUE);
957 }
958 break;
959
960 // For all select elements
961 case 'Select':
962 if (empty($selectAttributes['multiple'])) {
963 $options = array('' => $placeholder) + $options;
964 }
965 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
966
967 // Add and/or option for fields that store multiple values
968 if ($search && self::isSerialized($field)) {
969
970 $operators = array(
971 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
972 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
973 );
974 $qf->addGroup($operators, $elementName . '_operator');
975 $qf->setDefaults(array($elementName . '_operator' => 'or'));
976 }
977 break;
978
979 case 'AdvMulti-Select':
980 $include =& $qf->addElement(
981 'advmultiselect',
982 $elementName,
983 $label, $options,
984 array(
985 'size' => 5,
986 'style' => '',
987 'class' => 'advmultiselect',
988 'data-crm-custom' => $dataCrmCustomVal,
989 )
990 );
991
992 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
993 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
994
995 if ($useRequired && !$search) {
996 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
997 }
998 break;
999
1000 case 'CheckBox':
1001 $check = array();
1002 foreach ($options as $v => $l) {
1003 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
1004 }
1005 $qf->addGroup($check, $elementName, $label);
1006 if ($useRequired && !$search) {
1007 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1008 }
1009 break;
1010
1011 case 'File':
1012 // we should not build upload file in search mode
1013 if ($search) {
1014 return;
1015 }
1016 $qf->add(
1017 strtolower($field->html_type),
1018 $elementName,
1019 $label,
1020 $field->attributes,
1021 $useRequired && !$search
1022 );
1023 $qf->addUploadElement($elementName);
1024 break;
1025
1026 case 'RichTextEditor':
1027 $attributes = array(
1028 'rows' => $field->note_rows,
1029 'cols' => $field->note_columns,
1030 'data-crm-custom' => $dataCrmCustomVal,
1031 );
1032 if ($field->text_length) {
1033 $attributes['maxlength'] = $field->text_length;
1034 }
1035 $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
1036 break;
1037
1038 case 'Autocomplete-Select':
1039 static $customUrls = array();
1040 // Fixme: why is this a string in the first place??
1041 $attributes = array();
1042 if ($field->attributes) {
1043 foreach (explode(' ', $field->attributes) as $at) {
1044 if (strpos($at, '=')) {
1045 list($k, $v) = explode('=', $at);
1046 $attributes[$k] = trim($v, ' "');
1047 }
1048 }
1049 }
1050 if ($field->data_type == 'ContactReference') {
1051 $attributes['class'] = (isset($attributes['class']) ? $attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1052 $attributes['data-api-entity'] = 'contact';
1053 $qf->add('text', $elementName, $label, $attributes,
1054 $useRequired && !$search
1055 );
1056
1057 $urlParams = "context=customfield&id={$field->id}";
1058
1059 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/contactref',
1060 $urlParams,
1061 FALSE, NULL, FALSE
1062 );
1063
1064 }
1065 else {
1066 // FIXME: This won't work with customFieldOptions hook
1067 $attributes += array(
1068 'entity' => 'option_value',
1069 'placeholder' => $placeholder,
1070 'multiple' => $search,
1071 'api' => array(
1072 'params' => array('option_group_id' => $field->option_group_id),
1073 ),
1074 );
1075 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1076 }
1077
1078 $qf->assign('customUrls', $customUrls);
1079 break;
1080 }
1081
1082 switch ($field->data_type) {
1083 case 'Int':
1084 // integers will have numeric rule applied to them.
1085 if ($field->is_search_range && $search) {
1086 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1087 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1088 }
1089 elseif ($widget == 'Text') {
1090 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1091 }
1092 break;
1093
1094 case 'Float':
1095 if ($field->is_search_range && $search) {
1096 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1097 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1098 }
1099 elseif ($widget == 'Text') {
1100 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1101 }
1102 break;
1103
1104 case 'Money':
1105 if ($field->is_search_range && $search) {
1106 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1107 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1108 }
1109 elseif ($widget == 'Text') {
1110 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1111 }
1112 break;
1113
1114 case 'Link':
1115 $element->setAttribute('class', "url");
1116 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1117 break;
1118 }
1119 if ($field->is_view && !$search) {
1120 $qf->freeze($elementName);
1121 }
1122 }
1123
1124 /**
1125 * Delete the Custom Field.
1126 *
1127 * @param object $field
1128 * The field object.
1129 */
1130 public static function deleteField($field) {
1131 CRM_Utils_System::flushCache();
1132
1133 // first delete the custom option group and values associated with this field
1134 if ($field->option_group_id) {
1135 //check if option group is related to any other field, if
1136 //not delete the option group and related option values
1137 self::checkOptionGroup($field->option_group_id);
1138 }
1139
1140 // next drop the column from the custom value table
1141 self::createField($field, 'delete');
1142
1143 $field->delete();
1144 CRM_Core_BAO_UFField::delUFField($field->id);
1145 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1146 }
1147
1148 /**
1149 * @param string|int|array|null $value
1150 * @param CRM_Core_BAO_CustomField|int|string $field
1151 * @param $contactId
1152 *
1153 * @return string
1154 * @throws \Exception
1155 */
1156 public static function displayValue($value, $field, $contactId = NULL) {
1157 $fieldId = is_object($field) ? $field->id : (int) str_replace('custom_', '', $field);
1158
1159 if (!$fieldId) {
1160 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1161 }
1162
1163 if (!isset(self::$displayInfoCache[$fieldId])) {
1164 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1165 $field = new CRM_Core_BAO_CustomField();
1166 $field->id = $fieldId;
1167 }
1168 $options = $field->getOptions();
1169 self::$displayInfoCache[$fieldId] = array(
1170 'id' => $fieldId,
1171 'html_type' => $field->html_type,
1172 'data_type' => $field->data_type,
1173 'date_format' => $field->date_format,
1174 'time_format' => $field->time_format,
1175 'options' => $options,
1176 );
1177 }
1178 return self::formatDisplayValue($value, self::$displayInfoCache[$fieldId], $contactId);
1179 }
1180
1181 /**
1182 * Legacy display value formatter.
1183 *
1184 * @deprecated
1185 *
1186 * @param string $value
1187 * @param array $option
1188 * @param string $html_type
1189 * @param string $data_type
1190 * @param int $contactID
1191 * @param int $fieldID
1192 *
1193 * @return array|mixed|null|string
1194 */
1195 public static function getDisplayValueCommon(
1196 $value,
1197 $option,
1198 $html_type,
1199 $data_type,
1200 $contactID = NULL,
1201 $fieldID = NULL
1202 ) {
1203
1204 if ($fieldID &&
1205 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1206 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1207 $html_type == 'Select' ||
1208 $html_type == 'CheckBox' ||
1209 $html_type == 'AdvMulti-Select' ||
1210 $html_type == 'Multi-Select'
1211 )
1212 ) {
1213 CRM_Utils_Hook::customFieldOptions($fieldID, $option);
1214 }
1215
1216 if ($data_type == 'Boolean') {
1217 $option = CRM_Core_SelectValues::boolean();
1218 }
1219
1220 if ($data_type == 'Country') {
1221 $option = CRM_Core_PseudoConstant::country(FALSE, FALSE);
1222 }
1223
1224 if ($data_type == 'StateProvince') {
1225 $option = CRM_Core_PseudoConstant::stateProvince(FALSE, FALSE);
1226 }
1227
1228 $field = array(
1229 'id' => $fieldID,
1230 'html_type' => $html_type,
1231 'data_type' => $data_type,
1232 'options' => $option,
1233 );
1234
1235 return self::formatDisplayValue($value, $field, $contactID);
1236 }
1237
1238
1239 /**
1240 * Lower-level logic for rendering a custom field value
1241 *
1242 * @param string|array $value
1243 * @param array $field
1244 * @param int|null $contactID
1245 *
1246 * @return string
1247 */
1248 private static function formatDisplayValue($value, $field, $contactID = NULL) {
1249
1250 if (self::isSerialized($field) && !is_array($value)) {
1251 $value = (array) CRM_Utils_Array::explodePadded($value);
1252 }
1253 // CRM-12989 fix
1254 if ($field['html_type'] == 'CheckBox') {
1255 CRM_Utils_Array::formatArrayKeys($value);
1256 }
1257
1258 $display = is_array($value) ? implode(', ', $value) : (string) $value;
1259
1260 switch ($field['html_type']) {
1261
1262 case 'Select':
1263 case 'Autocomplete-Select':
1264 case 'Radio':
1265 case 'Select Country':
1266 case 'Select State/Province':
1267 case 'CheckBox':
1268 case 'AdvMulti-Select':
1269 case 'Multi-Select':
1270 case 'Multi-Select State/Province':
1271 case 'Multi-Select Country':
1272 if ($field['data_type'] == 'ContactReference' && $value) {
1273 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1274 }
1275 elseif (is_array($value)) {
1276 $v = array();
1277 foreach ($value as $key => $val) {
1278 $v[] = CRM_Utils_Array::value($val, $field['options']);
1279 }
1280 $display = implode(', ', $v);
1281 }
1282 else {
1283 $display = CRM_Utils_Array::value($value, $field['options'], '');
1284 }
1285 break;
1286
1287 case 'Select Date':
1288 $customFormat = NULL;
1289
1290 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats();
1291 $format = CRM_Utils_Array::value('date_format', $field);
1292
1293 if ($format) {
1294 if (array_key_exists($format, $actualPHPFormats)) {
1295 $customTimeFormat = (array) $actualPHPFormats[$format];
1296 switch (CRM_Utils_Array::value('time_format', $field)) {
1297 case 1:
1298 $customTimeFormat[] = 'g:iA';
1299 break;
1300
1301 case 2:
1302 $customTimeFormat[] = 'G:i';
1303 break;
1304
1305 default:
1306 // if time is not selected remove time from value
1307 $value = substr($value, 0, 10);
1308 }
1309 $customFormat = implode(" ", $customTimeFormat);
1310 }
1311 }
1312 $display = CRM_Utils_Date::processDate($value, NULL, FALSE, $customFormat);
1313 break;
1314
1315 case 'File':
1316 // In the context of displaying a profile, show file/image
1317 if ($contactID && $value) {
1318 $url = self::getFileURL($contactID, $field['id'], $value);
1319 if ($url) {
1320 $display = $url['file_url'];
1321 }
1322 }
1323 // In other contexts show a paperclip icon
1324 elseif ($value) {
1325 $icons = CRM_Core_BAO_File::paperIconAttachment('*', $value);
1326 $display = $icons[$value];
1327 }
1328 break;
1329
1330 case 'TextArea':
1331 $display = nl2br($display);
1332 break;
1333 }
1334 return $display;
1335 }
1336
1337 /**
1338 * Set default values for custom data used in profile.
1339 *
1340 * @param int $customFieldId
1341 * Custom field id.
1342 * @param string $elementName
1343 * Custom field name.
1344 * @param array $defaults
1345 * Associated array of fields.
1346 * @param int $contactId
1347 * Contact id.
1348 * @param int $mode
1349 * Profile mode.
1350 * @param mixed $value
1351 * If passed - dont fetch value from db,.
1352 * just format the given value
1353 */
1354 public static function setProfileDefaults(
1355 $customFieldId,
1356 $elementName,
1357 &$defaults,
1358 $contactId = NULL,
1359 $mode = NULL,
1360 $value = NULL
1361 ) {
1362 //get the type of custom field
1363 $customField = new CRM_Core_BAO_CustomField();
1364 $customField->id = $customFieldId;
1365 $customField->find(TRUE);
1366
1367 if (!$contactId) {
1368 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1369 $value = $customField->default_value;
1370 }
1371 }
1372 else {
1373 if (!isset($value)) {
1374 $info = self::getTableColumnGroup($customFieldId);
1375 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1376 $result = CRM_Core_DAO::executeQuery($query);
1377 if ($result->fetch()) {
1378 $value = $result->value;
1379 }
1380 }
1381
1382 if ($customField->data_type == 'Country') {
1383 if (!$value) {
1384 $config = CRM_Core_Config::singleton();
1385 if ($config->defaultContactCountry) {
1386 $value = $config->defaultContactCountry();
1387 }
1388 }
1389 }
1390 }
1391
1392 //set defaults if mode is registration
1393 if (!trim($value) &&
1394 ($value !== 0) &&
1395 (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)))
1396 ) {
1397 $value = $customField->default_value;
1398 }
1399
1400 if ($customField->data_type == 'Money' && isset($value)) {
1401 $value = number_format($value, 2);
1402 }
1403 switch ($customField->html_type) {
1404 case 'CheckBox':
1405 case 'AdvMulti-Select':
1406 case 'Multi-Select':
1407 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1408 $defaults[$elementName] = array();
1409 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1410 substr($value, 1, -1)
1411 );
1412 foreach ($customOption as $val) {
1413 if (in_array($val['value'], $checkedValue)) {
1414 if ($customField->html_type == 'CheckBox') {
1415 $defaults[$elementName][$val['value']] = 1;
1416 }
1417 elseif ($customField->html_type == 'Multi-Select' ||
1418 $customField->html_type == 'AdvMulti-Select'
1419 ) {
1420 $defaults[$elementName][$val['value']] = $val['value'];
1421 }
1422 }
1423 }
1424 break;
1425
1426 case 'Select Date':
1427 if ($value) {
1428 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults(
1429 $value,
1430 NULL,
1431 $customField->date_format,
1432 $customField->time_format
1433 );
1434 }
1435 break;
1436
1437 case 'Autocomplete-Select':
1438 if ($customField->data_type == 'ContactReference') {
1439 if (is_numeric($value)) {
1440 $defaults[$elementName . '_id'] = $value;
1441 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1442 }
1443 }
1444 else {
1445 $defaults[$elementName] = $value;
1446 }
1447 break;
1448
1449 default:
1450 $defaults[$elementName] = $value;
1451 }
1452 }
1453
1454 /**
1455 * Get file url.
1456 *
1457 * @param int $contactID
1458 * @param int $cfID
1459 * @param int $fileID
1460 * @param bool $absolute
1461 *
1462 * @param string $multiRecordWhereClause
1463 *
1464 * @return array
1465 */
1466 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1467 if ($contactID) {
1468 if (!$fileID) {
1469 $params = array('id' => $cfID);
1470 $defaults = array();
1471 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1472 $columnName = $defaults['column_name'];
1473
1474 //table name of custom data
1475 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1476 $defaults['custom_group_id'],
1477 'table_name', 'id'
1478 );
1479
1480 //query to fetch id from civicrm_file
1481 if ($multiRecordWhereClause) {
1482 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1483 }
1484 else {
1485 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1486 }
1487 $fileID = CRM_Core_DAO::singleValueQuery($query);
1488 }
1489
1490 $result = array();
1491 if ($fileID) {
1492 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1493 $fileID,
1494 'mime_type',
1495 'id'
1496 );
1497 $result['file_id'] = $fileID;
1498
1499 if ($fileType == 'image/jpeg' ||
1500 $fileType == 'image/pjpeg' ||
1501 $fileType == 'image/gif' ||
1502 $fileType == 'image/x-png' ||
1503 $fileType == 'image/png'
1504 ) {
1505 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1506 $fileID,
1507 'entity_id',
1508 'id'
1509 );
1510 list($path) = CRM_Core_BAO_File::path($fileID, $entityId, NULL, NULL);
1511 list($imageWidth, $imageHeight) = getimagesize($path);
1512 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
1513 $url = CRM_Utils_System::url('civicrm/file',
1514 "reset=1&id=$fileID&eid=$contactID",
1515 $absolute, NULL, TRUE, TRUE
1516 );
1517 $result['file_url'] = "
1518 <a href=\"$url\" class='crm-image-popup'>
1519 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1520 </a>";
1521 // for non image files
1522 }
1523 else {
1524 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1525 $fileID,
1526 'uri'
1527 );
1528 $url = CRM_Utils_System::url('civicrm/file',
1529 "reset=1&id=$fileID&eid=$contactID",
1530 $absolute, NULL, TRUE, TRUE
1531 );
1532 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1533 }
1534 }
1535 return $result;
1536 }
1537 }
1538
1539 /**
1540 * Format custom fields before inserting.
1541 *
1542 * @param int $customFieldId
1543 * Custom field id.
1544 * @param array $customFormatted
1545 * Formatted array.
1546 * @param mixed $value
1547 * Value of custom field.
1548 * @param string $customFieldExtend
1549 * Custom field extends.
1550 * @param int $customValueId
1551 * Custom option value id.
1552 * @param int $entityId
1553 * Entity id (contribution, membership...).
1554 * @param bool $inline
1555 * Consider inline custom groups only.
1556 * @param bool $checkPermission
1557 * If false, do not include permissioning clause.
1558 * @param bool $includeViewOnly
1559 * If true, fields marked 'View Only' are included. Required for APIv3.
1560 *
1561 * @return array|NULL
1562 * formatted custom field array
1563 */
1564 public static function formatCustomField(
1565 $customFieldId, &$customFormatted, $value,
1566 $customFieldExtend, $customValueId = NULL,
1567 $entityId = NULL,
1568 $inline = FALSE,
1569 $checkPermission = TRUE,
1570 $includeViewOnly = FALSE
1571 ) {
1572 //get the custom fields for the entity
1573 //subtype and basic type
1574 $customDataSubType = NULL;
1575 if ($customFieldExtend) {
1576 // This is the case when getFieldsForImport() requires fields
1577 // of subtype and its parent.CRM-5143
1578 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1579 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType::subTypes(), (array) $customFieldExtend);
1580 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1581 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1582 if (is_array($customFieldExtend)) {
1583 $customFieldExtend = array_unique(array_values($customFieldExtend));
1584 }
1585 }
1586 }
1587
1588 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1589 FALSE,
1590 $inline,
1591 $customDataSubType,
1592 NULL,
1593 FALSE,
1594 FALSE,
1595 $checkPermission
1596 );
1597
1598 if (!array_key_exists($customFieldId, $customFields)) {
1599 return NULL;
1600 }
1601
1602 // return if field is a 'code' field
1603 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1604 return NULL;
1605 }
1606
1607 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1608
1609 if (!$customValueId &&
1610 // we always create new entites for is_multiple unless specified
1611 !$customFields[$customFieldId]['is_multiple'] &&
1612 $entityId
1613 ) {
1614 $query = "
1615 SELECT id
1616 FROM $tableName
1617 WHERE entity_id={$entityId}";
1618
1619 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1620 }
1621
1622 //fix checkbox, now check box always submits values
1623 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1624 if ($value) {
1625 // Note that only during merge this is not an array, and you can directly use value
1626 if (is_array($value)) {
1627 $selectedValues = array();
1628 foreach ($value as $selId => $val) {
1629 if ($val) {
1630 $selectedValues[] = $selId;
1631 }
1632 }
1633 if (!empty($selectedValues)) {
1634 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1635 $selectedValues
1636 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1637 }
1638 else {
1639 $value = '';
1640 }
1641 }
1642 }
1643 }
1644
1645 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1646 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1647 ) {
1648 if ($value) {
1649 $value = CRM_Utils_Array::implodePadded($value);
1650 }
1651 else {
1652 $value = '';
1653 }
1654 }
1655
1656 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1657 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1658 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1659 ) &&
1660 $customFields[$customFieldId]['data_type'] == 'String' &&
1661 !empty($customFields[$customFieldId]['text_length']) &&
1662 !empty($value)
1663 ) {
1664 // lets make sure that value is less than the length, else we'll
1665 // be losing some data, CRM-7481
1666 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1667 // need to do a few things here
1668
1669 // 1. lets find a new length
1670 $newLength = $customFields[$customFieldId]['text_length'];
1671 $minLength = strlen($value);
1672 while ($newLength < $minLength) {
1673 $newLength = $newLength * 2;
1674 }
1675
1676 // set the custom field meta data to have a length larger than value
1677 // alter the custom value table column to match this length
1678 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1679 }
1680 }
1681
1682 $date = NULL;
1683 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1684 if (!CRM_Utils_System::isNull($value)) {
1685 $format = $customFields[$customFieldId]['date_format'];
1686 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1687 }
1688 $value = $date;
1689 }
1690
1691 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1692 $customFields[$customFieldId]['data_type'] == 'Money'
1693 ) {
1694 if (!$value) {
1695 $value = 0;
1696 }
1697
1698 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1699 $value = CRM_Utils_Rule::cleanMoney($value);
1700 }
1701 }
1702
1703 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1704 $customFields[$customFieldId]['data_type'] == 'Country'
1705 ) &&
1706 empty($value)
1707 ) {
1708 // CRM-3415
1709 $value = 0;
1710 }
1711
1712 $fileId = NULL;
1713
1714 if ($customFields[$customFieldId]['data_type'] == 'File') {
1715 if (empty($value)) {
1716 return;
1717 }
1718
1719 $config = CRM_Core_Config::singleton();
1720
1721 $fName = $value['name'];
1722 $mimeType = $value['type'];
1723
1724 $filename = pathinfo($fName, PATHINFO_BASENAME);
1725
1726 // rename this file to go into the secure directory
1727 if (!rename($fName, $config->customFileUploadDir . $filename)) {
1728 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1729 }
1730
1731 if ($customValueId) {
1732 $query = "
1733 SELECT $columnName
1734 FROM $tableName
1735 WHERE id = %1";
1736 $params = array(1 => array($customValueId, 'Integer'));
1737 $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
1738 }
1739
1740 $fileDAO = new CRM_Core_DAO_File();
1741
1742 if ($fileId) {
1743 $fileDAO->id = $fileId;
1744 }
1745
1746 $fileDAO->uri = $filename;
1747 $fileDAO->mime_type = $mimeType;
1748 $fileDAO->upload_date = date('Ymdhis');
1749 $fileDAO->save();
1750 $fileId = $fileDAO->id;
1751 $value = $filename;
1752 }
1753
1754 if (!is_array($customFormatted)) {
1755 $customFormatted = array();
1756 }
1757
1758 if (!array_key_exists($customFieldId, $customFormatted)) {
1759 $customFormatted[$customFieldId] = array();
1760 }
1761
1762 $index = -1;
1763 if ($customValueId) {
1764 $index = $customValueId;
1765 }
1766
1767 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1768 $customFormatted[$customFieldId][$index] = array();
1769 }
1770 $customFormatted[$customFieldId][$index] = array(
1771 'id' => $customValueId > 0 ? $customValueId : NULL,
1772 'value' => $value,
1773 'type' => $customFields[$customFieldId]['data_type'],
1774 'custom_field_id' => $customFieldId,
1775 'custom_group_id' => $groupID,
1776 'table_name' => $tableName,
1777 'column_name' => $columnName,
1778 'file_id' => $fileId,
1779 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1780 );
1781
1782 //we need to sort so that custom fields are created in the order of entry
1783 krsort($customFormatted[$customFieldId]);
1784 return $customFormatted;
1785 }
1786
1787 /**
1788 * Get default custom table schema.
1789 *
1790 * @param array $params
1791 *
1792 * @return array
1793 */
1794 public static function defaultCustomTableSchema($params) {
1795 // add the id and extends_id
1796 $table = array(
1797 'name' => $params['name'],
1798 'is_multiple' => $params['is_multiple'],
1799 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1800 'fields' => array(
1801 array(
1802 'name' => 'id',
1803 'type' => 'int unsigned',
1804 'primary' => TRUE,
1805 'required' => TRUE,
1806 'attributes' => 'AUTO_INCREMENT',
1807 'comment' => 'Default MySQL primary key',
1808 ),
1809 array(
1810 'name' => 'entity_id',
1811 'type' => 'int unsigned',
1812 'required' => TRUE,
1813 'comment' => 'Table that this extends',
1814 'fk_table_name' => $params['extends_name'],
1815 'fk_field_name' => 'id',
1816 'fk_attributes' => 'ON DELETE CASCADE',
1817 ),
1818 ),
1819 );
1820
1821 if (!$params['is_multiple']) {
1822 $table['indexes'] = array(
1823 array(
1824 'unique' => TRUE,
1825 'field_name_1' => 'entity_id',
1826 ),
1827 );
1828 }
1829 return $table;
1830 }
1831
1832 /**
1833 * Create custom field.
1834 *
1835 * @param CRM_Core_DAO_CustomField $field
1836 * @param string $operation
1837 * @param bool $indexExist
1838 * @param bool $triggerRebuild
1839 */
1840 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1841 $tableName = CRM_Core_DAO::getFieldValue(
1842 'CRM_Core_DAO_CustomGroup',
1843 $field->custom_group_id,
1844 'table_name'
1845 );
1846
1847 $params = array(
1848 'table_name' => $tableName,
1849 'operation' => $operation,
1850 'name' => $field->column_name,
1851 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
1852 $field->data_type,
1853 $field->text_length
1854 ),
1855 'required' => $field->is_required,
1856 'searchable' => $field->is_searchable,
1857 );
1858
1859 if ($operation == 'delete') {
1860 $fkName = "{$tableName}_{$field->column_name}";
1861 if (strlen($fkName) >= 48) {
1862 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1863 }
1864 $params['fkName'] = $fkName;
1865 }
1866 if ($field->data_type == 'Country' && $field->html_type == 'Select Country') {
1867 $params['fk_table_name'] = 'civicrm_country';
1868 $params['fk_field_name'] = 'id';
1869 $params['fk_attributes'] = 'ON DELETE SET NULL';
1870 }
1871 elseif ($field->data_type == 'Country' && $field->html_type == 'Multi-Select Country') {
1872 $params['type'] = 'varchar(255)';
1873 }
1874 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Select State/Province') {
1875 $params['fk_table_name'] = 'civicrm_state_province';
1876 $params['fk_field_name'] = 'id';
1877 $params['fk_attributes'] = 'ON DELETE SET NULL';
1878 }
1879 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Multi-Select State/Province') {
1880 $params['type'] = 'varchar(255)';
1881 }
1882 elseif ($field->data_type == 'File') {
1883 $params['fk_table_name'] = 'civicrm_file';
1884 $params['fk_field_name'] = 'id';
1885 $params['fk_attributes'] = 'ON DELETE SET NULL';
1886 }
1887 elseif ($field->data_type == 'ContactReference') {
1888 $params['fk_table_name'] = 'civicrm_contact';
1889 $params['fk_field_name'] = 'id';
1890 $params['fk_attributes'] = 'ON DELETE SET NULL';
1891 }
1892 if (isset($field->default_value)) {
1893 $params['default'] = "'{$field->default_value}'";
1894 }
1895
1896 CRM_Core_BAO_SchemaHandler::alterFieldSQL($params, $indexExist, $triggerRebuild);
1897 }
1898
1899 /**
1900 * Determine whether it would be safe to move a field.
1901 *
1902 * @param int $fieldID
1903 * FK to civicrm_custom_field.
1904 * @param int $newGroupID
1905 * FK to civicrm_custom_group.
1906 *
1907 * @return array
1908 * array(string) or TRUE
1909 */
1910 public static function _moveFieldValidate($fieldID, $newGroupID) {
1911 $errors = array();
1912
1913 $field = new CRM_Core_DAO_CustomField();
1914 $field->id = $fieldID;
1915 if (!$field->find(TRUE)) {
1916 $errors['fieldID'] = 'Invalid ID for custom field';
1917 return $errors;
1918 }
1919
1920 $oldGroup = new CRM_Core_DAO_CustomGroup();
1921 $oldGroup->id = $field->custom_group_id;
1922 if (!$oldGroup->find(TRUE)) {
1923 $errors['fieldID'] = 'Invalid ID for old custom group';
1924 return $errors;
1925 }
1926
1927 $newGroup = new CRM_Core_DAO_CustomGroup();
1928 $newGroup->id = $newGroupID;
1929 if (!$newGroup->find(TRUE)) {
1930 $errors['newGroupID'] = 'Invalid ID for new custom group';
1931 return $errors;
1932 }
1933
1934 $query = "
1935 SELECT b.id
1936 FROM civicrm_custom_field a
1937 INNER JOIN civicrm_custom_field b
1938 WHERE a.id = %1
1939 AND a.label = b.label
1940 AND b.custom_group_id = %2
1941 ";
1942 $params = array(
1943 1 => array($field->id, 'Integer'),
1944 2 => array($newGroup->id, 'Integer'),
1945 );
1946 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1947 if ($count > 0) {
1948 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1949 }
1950
1951 $tableName = $oldGroup->table_name;
1952 $columnName = $field->column_name;
1953
1954 $query = "
1955 SELECT count(*)
1956 FROM $tableName
1957 WHERE $columnName is not null
1958 ";
1959 $count = CRM_Core_DAO::singleValueQuery($query,
1960 CRM_Core_DAO::$_nullArray
1961 );
1962 if ($count > 0) {
1963 $query = "
1964 SELECT extends
1965 FROM civicrm_custom_group
1966 WHERE id IN ( %1, %2 )
1967 ";
1968 $params = array(
1969 1 => array($oldGroup->id, 'Integer'),
1970 2 => array($newGroup->id, 'Integer'),
1971 );
1972
1973 $dao = CRM_Core_DAO::executeQuery($query, $params);
1974 $extends = array();
1975 while ($dao->fetch()) {
1976 $extends[] = $dao->extends;
1977 }
1978 if ($extends[0] != $extends[1]) {
1979 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1980 }
1981 }
1982
1983 return empty($errors) ? TRUE : $errors;
1984 }
1985
1986 /**
1987 * Move a custom data field from one group (table) to another.
1988 *
1989 * @param int $fieldID
1990 * FK to civicrm_custom_field.
1991 * @param int $newGroupID
1992 * FK to civicrm_custom_group.
1993 */
1994 public static function moveField($fieldID, $newGroupID) {
1995 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1996 if (TRUE !== $validation) {
1997 CRM_Core_Error::fatal(implode(' ', $validation));
1998 }
1999 $field = new CRM_Core_DAO_CustomField();
2000 $field->id = $fieldID;
2001 $field->find(TRUE);
2002
2003 $newGroup = new CRM_Core_DAO_CustomGroup();
2004 $newGroup->id = $newGroupID;
2005 $newGroup->find(TRUE);
2006
2007 $oldGroup = new CRM_Core_DAO_CustomGroup();
2008 $oldGroup->id = $field->custom_group_id;
2009 $oldGroup->find(TRUE);
2010
2011 $add = clone$field;
2012 $add->custom_group_id = $newGroup->id;
2013 self::createField($add, 'add');
2014
2015 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2016 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2017 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2018 ";
2019 CRM_Core_DAO::executeQuery($sql);
2020
2021 $del = clone$field;
2022 $del->custom_group_id = $oldGroup->id;
2023 self::createField($del, 'delete');
2024
2025 $add->save();
2026
2027 CRM_Utils_System::flushCache();
2028 }
2029
2030 /**
2031 * Get the database table name and column name for a custom field.
2032 *
2033 * @param int $fieldID
2034 * The fieldID of the custom field.
2035 * @param bool $force
2036 * Force the sql to be run again (primarily used for tests).
2037 *
2038 * @return array
2039 * fatal is fieldID does not exists, else array of tableName, columnName
2040 */
2041 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2042 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2043 $cache = CRM_Utils_Cache::singleton();
2044 $fieldValues = $cache->get($cacheKey);
2045 if (empty($fieldValues) || $force) {
2046 $query = "
2047 SELECT cg.table_name, cf.column_name, cg.id
2048 FROM civicrm_custom_group cg,
2049 civicrm_custom_field cf
2050 WHERE cf.custom_group_id = cg.id
2051 AND cf.id = %1";
2052 $params = array(1 => array($fieldID, 'Integer'));
2053 $dao = CRM_Core_DAO::executeQuery($query, $params);
2054
2055 if (!$dao->fetch()) {
2056 CRM_Core_Error::fatal();
2057 }
2058 $dao->free();
2059 $fieldValues = array($dao->table_name, $dao->column_name, $dao->id);
2060 $cache->set($cacheKey, $fieldValues);
2061 }
2062 return $fieldValues;
2063 }
2064
2065 /**
2066 * Get custom option groups.
2067 *
2068 * @param array $includeFieldIds
2069 * Ids of custom fields for which option groups must be included.
2070 *
2071 * Currently this is required in the cases where option groups are to be included
2072 * for inactive fields : CRM-5369
2073 *
2074 * @return mixed
2075 */
2076 public static function customOptionGroup($includeFieldIds = NULL) {
2077 static $customOptionGroup = NULL;
2078
2079 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2080 if ($cacheKey == 'force') {
2081 $customOptionGroup[$cacheKey] = NULL;
2082 }
2083
2084 if (empty($customOptionGroup[$cacheKey])) {
2085 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2086
2087 //support for single as well as array format.
2088 if (!empty($includeFieldIds)) {
2089 if (is_array($includeFieldIds)) {
2090 $includeFieldIds = implode(',', $includeFieldIds);
2091 }
2092 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2093 }
2094
2095 $query = "
2096 SELECT g.id, g.title
2097 FROM civicrm_option_group g
2098 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2099 WHERE {$whereClause}";
2100
2101 $dao = CRM_Core_DAO::executeQuery($query);
2102 while ($dao->fetch()) {
2103 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2104 }
2105 }
2106
2107 return $customOptionGroup[$cacheKey];
2108 }
2109
2110 /**
2111 * Fix orphan groups.
2112 *
2113 * @param int $customFieldId
2114 * Custom field id.
2115 * @param int $optionGroupId
2116 * Option group id.
2117 */
2118 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2119 // check if option group belongs to any custom Field else delete
2120 // get the current option group
2121 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2122 $customFieldId,
2123 'option_group_id'
2124 );
2125 // get the updated option group
2126 // if both are same return
2127 if ($currentOptionGroupId == $optionGroupId) {
2128 return;
2129 }
2130
2131 // check if option group is related to any other field
2132 self::checkOptionGroup($currentOptionGroupId);
2133 }
2134
2135 /**
2136 * Check if option group is related to more than one custom field.
2137 *
2138 * @param int $optionGroupId
2139 * Option group id.
2140 */
2141 public static function checkOptionGroup($optionGroupId) {
2142 $query = "
2143 SELECT count(*)
2144 FROM civicrm_custom_field
2145 WHERE option_group_id = {$optionGroupId}";
2146
2147 $count = CRM_Core_DAO::singleValueQuery($query);
2148
2149 if ($count < 2) {
2150 //delete the option group
2151 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2152 }
2153 }
2154
2155 /**
2156 * Get option group default.
2157 *
2158 * @param int $optionGroupId
2159 * @param string $htmlType
2160 *
2161 * @return null|string
2162 */
2163 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2164 $query = "
2165 SELECT default_value, html_type
2166 FROM civicrm_custom_field
2167 WHERE option_group_id = {$optionGroupId}
2168 AND default_value IS NOT NULL
2169 ORDER BY html_type";
2170
2171 $dao = CRM_Core_DAO::executeQuery($query);
2172 $defaultValue = NULL;
2173 $defaultHTMLType = NULL;
2174 while ($dao->fetch()) {
2175 if ($dao->html_type == $htmlType) {
2176 return $dao->default_value;
2177 }
2178 if ($defaultValue == NULL) {
2179 $defaultValue = $dao->default_value;
2180 $defaultHTMLType = $dao->html_type;
2181 }
2182 }
2183
2184 // some conversions are needed if either the old or new has a html type which has potential
2185 // multiple default values.
2186 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2187 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2188 ) {
2189 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2190 }
2191 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2192 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2193 ) {
2194 $defaultValue = substr($defaultValue, 1, -1);
2195 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2196 substr($defaultValue, 1, -1)
2197 );
2198 $defaultValue = $values[0];
2199 }
2200
2201 return $defaultValue;
2202 }
2203
2204 /**
2205 * Post process function.
2206 *
2207 * @param array $params
2208 * @param int $entityID
2209 * @param string $customFieldExtends
2210 * @param bool $inline
2211 * @param bool $checkPermissions
2212 *
2213 * @return array
2214 */
2215 public static function postProcess(
2216 &$params,
2217 $entityID,
2218 $customFieldExtends,
2219 $inline = FALSE,
2220 $checkPermissions = TRUE
2221 ) {
2222 $customData = array();
2223
2224 foreach ($params as $key => $value) {
2225 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2226
2227 // for autocomplete transfer hidden value instead of label
2228 if ($params[$key] && isset($params[$key . '_id'])) {
2229 $value = $params[$key . '_id'];
2230 }
2231
2232 // we need to append time with date
2233 if ($params[$key] && isset($params[$key . '_time'])) {
2234 $value .= ' ' . $params[$key . '_time'];
2235 }
2236
2237 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2238 $customData,
2239 $value,
2240 $customFieldExtends,
2241 $customFieldInfo[1],
2242 $entityID,
2243 $inline,
2244 $checkPermissions
2245 );
2246 }
2247 }
2248 return $customData;
2249 }
2250
2251 /**
2252 *
2253 */
2254
2255 /**
2256 * Get custom field ID.
2257 *
2258 * @param string $fieldLabel
2259 * @param null $groupTitle
2260 *
2261 * @return int|null
2262 */
2263 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2264 $params = array(1 => array($fieldLabel, 'String'));
2265 if ($groupTitle) {
2266 $params[2] = array($groupTitle, 'String');
2267 $sql = "
2268 SELECT f.id
2269 FROM civicrm_custom_field f
2270 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2271 WHERE ( f.label = %1 OR f.name = %1 )
2272 AND ( g.title = %2 OR g.name = %2 )
2273 ";
2274 }
2275 else {
2276 $sql = "
2277 SELECT f.id
2278 FROM civicrm_custom_field f
2279 WHERE ( f.label = %1 OR f.name = %1 )
2280 ";
2281 }
2282
2283 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2284 if ($dao->fetch() &&
2285 $dao->N == 1
2286 ) {
2287 return $dao->id;
2288 }
2289 else {
2290 return NULL;
2291 }
2292 }
2293
2294 /**
2295 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2296 *
2297 * @param array $ids
2298 *
2299 * @return array
2300 */
2301 public static function getNameFromID($ids) {
2302 if (is_array($ids)) {
2303 $ids = implode(',', $ids);
2304 }
2305 $sql = "
2306 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2307 FROM civicrm_custom_field f
2308 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2309 WHERE f.id IN ($ids)";
2310
2311 $dao = CRM_Core_DAO::executeQuery($sql);
2312 $result = array();
2313 while ($dao->fetch()) {
2314 $result[$dao->id] = array(
2315 'field_name' => $dao->field_name,
2316 'field_label' => $dao->field_label,
2317 'group_name' => $dao->group_name,
2318 'group_title' => $dao->group_title,
2319 );
2320 }
2321 return $result;
2322 }
2323
2324 /**
2325 * Validate custom data.
2326 *
2327 * @param array $params
2328 * Custom data submitted.
2329 * ie array( 'custom_1' => 'validate me' );
2330 *
2331 * @return array
2332 * validation errors.
2333 */
2334 public static function validateCustomData($params) {
2335 $errors = array();
2336 if (!is_array($params) || empty($params)) {
2337 return $errors;
2338 }
2339
2340 //pick up profile fields.
2341 $profileFields = array();
2342 $ufGroupId = CRM_Utils_Array::value('ufGroupId', $params);
2343 if ($ufGroupId) {
2344 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2345 FALSE,
2346 CRM_Core_Action::VIEW
2347 );
2348 }
2349
2350 //lets start w/ params.
2351 foreach ($params as $key => $value) {
2352 $customFieldID = self::getKeyID($key);
2353 if (!$customFieldID) {
2354 continue;
2355 }
2356
2357 //load the structural info for given field.
2358 $field = new CRM_Core_DAO_CustomField();
2359 $field->id = $customFieldID;
2360 if (!$field->find(TRUE)) {
2361 continue;
2362 }
2363 $dataType = $field->data_type;
2364
2365 $profileField = CRM_Utils_Array::value($key, $profileFields, array());
2366 $fieldTitle = CRM_Utils_Array::value('title', $profileField);
2367 $isRequired = CRM_Utils_Array::value('is_required', $profileField);
2368 if (!$fieldTitle) {
2369 $fieldTitle = $field->label;
2370 }
2371
2372 //no need to validate.
2373 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2374 continue;
2375 }
2376
2377 //lets validate first for required field.
2378 if ($isRequired && CRM_Utils_System::isNull($value)) {
2379 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2380 continue;
2381 }
2382
2383 //now time to take care of custom field form rules.
2384 $ruleName = $errorMsg = NULL;
2385 switch ($dataType) {
2386 case 'Int':
2387 $ruleName = 'integer';
2388 $errorMsg = ts('%1 must be an integer (whole number).',
2389 array(1 => $fieldTitle)
2390 );
2391 break;
2392
2393 case 'Money':
2394 $ruleName = 'money';
2395 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2396 array(1 => $fieldTitle)
2397 );
2398 break;
2399
2400 case 'Float':
2401 $ruleName = 'numeric';
2402 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2403 array(1 => $fieldTitle)
2404 );
2405 break;
2406
2407 case 'Link':
2408 $ruleName = 'wikiURL';
2409 $errorMsg = ts('%1 must be valid Website.',
2410 array(1 => $fieldTitle)
2411 );
2412 break;
2413 }
2414
2415 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2416 $valid = FALSE;
2417 $funName = "CRM_Utils_Rule::{$ruleName}";
2418 if (is_callable($funName)) {
2419 $valid = call_user_func($funName, $value);
2420 }
2421 if (!$valid) {
2422 $errors[$key] = $errorMsg;
2423 }
2424 }
2425 }
2426
2427 return $errors;
2428 }
2429
2430 /**
2431 * Is this field a multi record field.
2432 *
2433 * @param int $customId
2434 *
2435 * @return bool
2436 */
2437 public static function isMultiRecordField($customId) {
2438 $isMultipleWithGid = FALSE;
2439 if (!is_numeric($customId)) {
2440 $customId = self::getKeyID($customId);
2441 }
2442 if (is_numeric($customId)) {
2443 $sql = "SELECT cg.id cgId
2444 FROM civicrm_custom_group cg
2445 INNER JOIN civicrm_custom_field cf
2446 ON cg.id = cf.custom_group_id
2447 WHERE cf.id = %1 AND cg.is_multiple = 1";
2448 $params[1] = array($customId, 'Integer');
2449 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2450 if ($dao->fetch()) {
2451 if ($dao->cgId) {
2452 $isMultipleWithGid = $dao->cgId;
2453 }
2454 }
2455 }
2456
2457 return $isMultipleWithGid;
2458 }
2459
2460 /**
2461 * Does this field store a serialized string?
2462 *
2463 * @param array $field
2464 *
2465 * @return bool
2466 */
2467 public static function isSerialized($field) {
2468 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2469 $field = (array) $field;
2470 // FIXME: Currently the only way to know if data is serialized is by looking at the html_type. It would be cleaner to decouple this.
2471 return ($field['html_type'] == 'CheckBox' || strpos($field['html_type'], 'Multi') !== FALSE);
2472 }
2473
2474 /**
2475 * Set pseudoconstant properties for field metadata.
2476 *
2477 * @param array $field
2478 * @param string|null $optionGroupName
2479 */
2480 private static function getOptionsForField(&$field, $optionGroupName) {
2481 if ($optionGroupName) {
2482 $field['pseudoconstant'] = array(
2483 'optionGroupName' => $optionGroupName,
2484 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2485 );
2486 }
2487 elseif ($field['data_type'] == 'Boolean') {
2488 $field['pseudoconstant'] = array(
2489 'callback' => 'CRM_Core_SelectValues::boolean',
2490 );
2491 }
2492 elseif ($field['data_type'] == 'Country') {
2493 $field['pseudoconstant'] = array(
2494 'table' => 'civicrm_country',
2495 'keyColumn' => 'id',
2496 'labelColumn' => 'name',
2497 'nameColumn' => 'iso_code',
2498 );
2499 }
2500 elseif ($field['data_type'] == 'StateProvince') {
2501 $field['pseudoconstant'] = array(
2502 'table' => 'civicrm_state_province',
2503 'keyColumn' => 'id',
2504 'labelColumn' => 'name',
2505 );
2506 }
2507 }
2508
2509 }