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