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