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