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