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