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