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