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