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