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