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