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