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