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