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