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