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