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