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