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