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