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