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