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