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