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