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