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