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