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