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