Merge pull request #938 from totten/master-restore-api_v3
[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 }
6a488035
TO
765 if ($field->note_columns) {
766 $attributes .= ' cols=' . $field->note_columns;
767 }
768 else {
769 $attributes .= ' cols=60';
770 }
2f940a36
NG
771 if ($field->text_length) {
772 $attributes .= ' maxlength=' . $field->text_length;
773 }
6a488035
TO
774 $element = &$qf->add(strtolower($field->html_type),
775 $elementName,
776 $label,
777 $attributes,
778 $useRequired && !$search
779 );
780 break;
781
782 case 'Select Date':
783 if ($field->is_search_range && $search) {
784 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
785 array(
786 'format' => $field->date_format,
787 'timeFormat' => $field->time_format,
788 'startOffset' => $field->start_date_years,
789 'endOffset' => $field->end_date_years,
790 )
791 );
792
793 $qf->addDate($elementName . '_to', ts('To'), FALSE,
794 array(
795 'format' => $field->date_format,
796 'timeFormat' => $field->time_format,
797 'startOffset' => $field->start_date_years,
798 'endOffset' => $field->end_date_years,
799 )
800 );
801 }
802 else {
803 $required = $useRequired && !$search;
804
805 $qf->addDate($elementName, $label, $required, array(
806 'format' => $field->date_format,
807 'timeFormat' => $field->time_format,
808 'startOffset' => $field->start_date_years,
809 'endOffset' => $field->end_date_years,
810 ));
811 }
812 break;
813
814 case 'Radio':
815 $choice = array();
816 if ($field->data_type != 'Boolean') {
817 $customOption = &CRM_Core_BAO_CustomOption::valuesByID($field->id,
818 $field->option_group_id
819 );
820 foreach ($customOption as $v => $l) {
821 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes);
822 }
823 $qf->addGroup($choice, $elementName, $label);
824 }
825 else {
826 $choice[] = $qf->createElement('radio', NULL, '', ts('Yes'), '1', $field->attributes);
827 $choice[] = $qf->createElement('radio', NULL, '', ts('No'), '0', $field->attributes);
828 $qf->addGroup($choice, $elementName, $label);
829 }
830 if ($useRequired && !$search) {
831 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
832 }
833 break;
834
835 case 'Select':
836 $selectOption = &CRM_Core_BAO_CustomOption::valuesByID($field->id,
837 $field->option_group_id
838 );
839 $qf->add('select', $elementName, $label,
840 array(
841 '' => ts('- select -')) + $selectOption,
842 $useRequired && !$search
843 );
844 break;
845
846 //added for select multiple
847
848 case 'AdvMulti-Select':
849 $selectOption = &CRM_Core_BAO_CustomOption::valuesByID($field->id,
850 $field->option_group_id
851 );
852 if ($search &&
853 count($selectOption) > 1
854 ) {
855 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
856 }
857
858 $include =& $qf->addElement(
859 'advmultiselect',
860 $elementName,
861 $label, $selectOption,
862 array(
863 'size' => 5,
864 'style' => '',
865 'class' => 'advmultiselect',
866 )
867 );
868
869 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
870 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
871
872 if ($useRequired && !$search) {
873 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
874 }
875 break;
876
877 case 'Multi-Select':
878 $selectOption = &CRM_Core_BAO_CustomOption::valuesByID($field->id,
879 $field->option_group_id
880 );
881 if ($search &&
882 count($selectOption) > 1
883 ) {
884 $selectOption['CiviCRM_OP_OR'] = ts('Select to match ANY; unselect to match ALL');
885 }
886 $qf->addElement('select', $elementName, $label, $selectOption, array('size' => '5', 'multiple'));
887
888 if ($useRequired && !$search) {
889 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
890 }
891 break;
892
893 case 'CheckBox':
894 $customOption = CRM_Core_BAO_CustomOption::valuesByID($field->id,
895 $field->option_group_id
896 );
897 $check = array();
898 foreach ($customOption as $v => $l) {
899 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l);
900 }
901 if ($search &&
902 count($check) > 1
903 ) {
904 $check[] = &$qf->addElement('advcheckbox', 'CiviCRM_OP_OR', NULL, ts('Check to match ANY; uncheck to match ALL'));
905 }
906 $qf->addGroup($check, $elementName, $label);
907 if ($useRequired && !$search) {
908 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
909 }
910 break;
911
912 case 'File':
913 // we should not build upload file in search mode
914 if ($search) {
915 return;
916 }
917 $qf->add(
918 strtolower($field->html_type),
919 $elementName,
920 $label,
921 $field->attributes,
922 $useRequired && !$search
923 );
924 $qf->addUploadElement($elementName);
925 break;
926
927 case 'Select State/Province':
928 //Add State
929 $stateOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince();
930 $qf->add('select', $elementName, $label, $stateOption,
931 $useRequired && !$search
932 );
933 break;
934
935 case 'Multi-Select State/Province':
936 //Add Multi-select State/Province
937 $stateOption = CRM_Core_PseudoConstant::stateProvince();
938
939 $qf->addElement('select', $elementName, $label, $stateOption, array('size' => '5', 'multiple'));
940 if ($useRequired && !$search) {
941 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
942 }
943 break;
944
945 case 'Select Country':
946 //Add Country
947 $countryOption = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country();
948 $qf->add('select', $elementName, $label, $countryOption,
949 $useRequired && !$search
950 );
951 break;
952
953 case 'Multi-Select Country':
954 //Add Country
955 $countryOption = CRM_Core_PseudoConstant::country();
956 $qf->addElement('select', $elementName, $label, $countryOption, array('size' => '5', 'multiple'));
957 if ($useRequired && !$search) {
958 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
959 }
960 break;
961
962 case 'RichTextEditor':
2f940a36
NG
963 $attributes = array('rows' => $field->note_rows, 'cols' => $field->note_columns);
964 if ($field->text_length) {
965 $attributes['maxlength'] = $field->text_length;
966 }
967 $qf->addWysiwyg($elementName, $label, $attributes, $search);
6a488035
TO
968 break;
969
970 case 'Autocomplete-Select':
971 $qf->add('text', $elementName, $label, $field->attributes,
972 $useRequired && !$search
973 );
974
975 $hiddenEleName = $elementName . '_id';
976 if (substr($elementName, -1) == ']') {
977 $hiddenEleName = substr($elementName, 0, -1) . '_id]';
978 }
979 $qf->addElement('hidden', $hiddenEleName, '', array('id' => str_replace(array(']', '['), array('', '_'), $hiddenEleName)));
980
981 static $customUrls = array();
982 if ($field->data_type == 'ContactReference') {
983 //$urlParams = "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&reset=1&context=customfield&id={$field->id}";
984 $urlParams = "context=customfield&id={$field->id}";
985
986 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/contactref',
987 $urlParams,
988 FALSE, NULL, FALSE
989 );
990
991 $actualElementValue = $qf->getSubmitValue($hiddenEleName);
992 $qf->addRule($elementName, ts('Select a valid contact for %1.', array(1 => $label)), 'validContact', $actualElementValue);
993 }
994 else {
995 $customUrls[$elementName] = CRM_Utils_System::url('civicrm/ajax/auto',
996 "reset=1&ogid={$field->option_group_id}&cfid={$field->id}",
997 FALSE, NULL, FALSE
998 );
999 $qf->addRule($elementName, ts('Select a valid value for %1.', array(1 => $label)),
1000 'autocomplete', array(
1001 'fieldID' => $field->id,
1002 'optionGroupID' => $field->option_group_id,
1003 )
1004 );
1005 }
1006
1007 $qf->assign('customUrls', $customUrls);
1008 break;
1009 }
1010
1011 switch ($field->data_type) {
1012 case 'Int':
1013 // integers will have numeric rule applied to them.
1014 if ($field->is_search_range && $search) {
1015 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1016 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1017 }
1018 else {
1019 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1020 }
1021 break;
1022
1023 case 'Float':
1024 if ($field->is_search_range && $search) {
1025 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1026 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1027 }
1028 else {
1029 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1030 }
1031 break;
1032
1033 case 'Money':
1034 if ($field->is_search_range && $search) {
1035 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1036 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1037 }
1038 else {
1039 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1040 }
1041 break;
1042
1043 case 'Link':
1044 $qf->add(
1045 'text',
1046 $elementName,
1047 $label,
1048 array(
1049 'onfocus' => "if (!this.value) { this.value='http://';} else return false",
1050 'onblur' => "if ( this.value == 'http://') { this.value='';} else return false",
1051 ),
1052 $useRequired && !$search
1053 );
1054 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1055 break;
1056 }
1057 if ($field->is_view && !$search) {
1058 $qf->freeze($elementName);
1059 }
1060 }
1061
1062 /**
1063 * Delete the Custom Field.
1064 *
1065 * @param object $field - the field object
1066 *
1067 * @return boolean
1068 *
1069 * @access public
1070 * @static
1071 *
1072 */
1073 public static function deleteField($field) {
1074 CRM_Utils_System::flushCache();
1075
1076 // first delete the custom option group and values associated with this field
1077 if ($field->option_group_id) {
1078 //check if option group is related to any other field, if
1079 //not delete the option group and related option values
1080 self::checkOptionGroup($field->option_group_id);
1081 }
1082
1083 // next drop the column from the custom value table
1084 self::createField($field, 'delete');
1085
1086 $field->delete();
1087 CRM_Core_BAO_UFField::delUFField($field->id);
1088 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1089
1090 return;
1091 }
1092
1093 /**
1094 * Given a custom field value, its id and the set of options
1095 * find the display value for this field
1096 *
1097 * @param mixed $value the custom field value
1098 * @param int $id the custom field id
1099 * @param int $options the assoc array of option name/value pairs
1100 *
1101 * @return string the display value
1102 *
1103 * @static
1104 * @access public
1105 */
1106 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1107 $option = &$options[$id];
1108 $attributes = &$option['attributes'];
1109 $html_type = $attributes['html_type'];
1110 $data_type = $attributes['data_type'];
1111 $format = CRM_Utils_Array::value('format', $attributes);
1112
1113 return self::getDisplayValueCommon($value,
1114 $option,
1115 $html_type,
1116 $data_type,
1117 $format,
1118 $contactID,
1119 $fieldID
1120 );
1121 }
1122
1123 static function getDisplayValueCommon($value,
1124 &$option,
1125 $html_type,
1126 $data_type,
1127 $format = NULL,
1128 $contactID = NULL,
1129 $fieldID = NULL
1130 ) {
1131 $display = $value;
1132
1133 if ($fieldID &&
1134 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1135 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1136 $html_type == 'Select' ||
1137 $html_type == 'CheckBox' ||
1138 $html_type == 'AdvMulti-Select' ||
1139 $html_type == 'Multi-Select'
1140 )
1141 ) {
1142 CRM_Utils_Hook::customFieldOptions($fieldID, $option);
1143 }
1144
1145 switch ($html_type) {
1146 case 'Radio':
1147 if ($data_type == 'Boolean') {
1148 $display = $value ? ts('Yes') : ts('No');
1149 }
1150 else {
1151 $display = CRM_Utils_Array::value($value, $option);
1152 }
1153 break;
1154
1155 case 'Autocomplete-Select':
1156 if ($data_type == 'ContactReference' &&
1157 $value
1158 ) {
1159 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1160 }
1161 else {
1162 $display = CRM_Utils_Array::value($value, $option);
1163 }
1164 break;
1165
1166 case 'Select':
1167 $display = CRM_Utils_Array::value($value, $option);
1168 break;
1169
1170 case 'CheckBox':
1171 case 'AdvMulti-Select':
1172 case 'Multi-Select':
1173 if (is_array($value)) {
1174 $checkedData = $value;
1175 }
1176 else {
1177 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1178 substr($value, 1, -1)
1179 );
1180 if ($html_type == 'CheckBox') {
1181 $newData = array();
1182 foreach ($checkedData as $v) {
1183 $newData[$v] = 1;
1184 }
1185 $checkedData = $newData;
1186 }
1187 }
1188
1189 $v = array();
1190 $p = array();
1191 foreach ($checkedData as $key => $val) {
1192 if ($key === 'CiviCRM_OP_OR') {
1193 continue;
1194 }
1195
1196 if ($html_type == 'CheckBox') {
1197 if ($val) {
1198 $p[] = $key;
1199 $v[] = CRM_Utils_Array::value($key, $option);
1200 }
1201 }
1202 else {
1203 $p[] = $val;
1204 $v[] = CRM_Utils_Array::value($val, $option);
1205 }
1206 }
1207 if (!empty($v)) {
1208 $display = implode(', ', $v);
1209 }
1210 break;
1211
1212 case 'Select Date':
1213 if (is_array($value)) {
1214 foreach ($value as $key => $val) {
1215 $display[$key] = CRM_Utils_Date::customFormat($val);
1216 }
1217 }
1218 else {
1219 // remove time element display if time is not set
1220 if (empty($option['attributes']['time_format'])) {
1221 $value = substr($value, 0, 10);
1222 }
1223 $display = CRM_Utils_Date::customFormat($value);
1224 }
1225 break;
1226
1227 case 'Select State/Province':
1228 if (empty($value)) {
1229 $display = '';
1230 }
1231 else {
1232 $display = CRM_Core_PseudoConstant::stateProvince($value);
1233 }
1234 break;
1235
1236 case 'Multi-Select State/Province':
1237 if (is_array($value)) {
1238 $checkedData = $value;
1239 }
1240 else {
1241 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1242 substr($value, 1, -1)
1243 );
1244 }
1245
1246 $states = CRM_Core_PseudoConstant::stateProvince();
1247 $display = NULL;
1248 foreach ($checkedData as $stateID) {
1249 if ($display) {
1250 $display .= ', ';
1251 }
1252 $display .= $states[$stateID];
1253 }
1254 break;
1255
1256 case 'Select Country':
1257 if (empty($value)) {
1258 $display = '';
1259 }
1260 else {
1261 $display = CRM_Core_PseudoConstant::country($value);
1262 }
1263 break;
1264
1265 case 'Multi-Select Country':
1266 if (is_array($value)) {
1267 $checkedData = $value;
1268 }
1269 else {
1270 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1271 substr($value, 1, -1)
1272 );
1273 }
1274
1275 $countries = CRM_Core_PseudoConstant::country();
1276 $display = NULL;
1277 foreach ($checkedData as $countryID) {
1278 if ($display) {
1279 $display .= ', ';
1280 }
1281 $display .= $countries[$countryID];
1282 }
1283 break;
1284
1285 case 'File':
1286 if ($contactID) {
1287 $url = self::getFileURL($contactID, $fieldID, $value);
1288 if ($url) {
1289 $display = $url['file_url'];
1290 }
1291 }
1292 break;
1293
1294 case 'TextArea':
1295 if (empty($value)) {
1296 $display = '';
1297 }
1298 else {
1299 $display = nl2br($value);
1300 }
1301 break;
1302
1303 case 'Link':
1304 if (empty($value)) {
1305 $display = '';
1306 }
1307 else {
1308 $display = $value;
1309 }
1310 }
1311
1312 return $display ? $display : $value;
1313 }
1314
1315 /**
1316 * Function to set default values for custom data used in profile
1317 *
1318 * @params int $customFieldId custom field id
1319 * @params string $elementName custom field name
1320 * @params array $defaults associated array of fields
1321 * @params int $contactId contact id
1322 * @param int $mode profile mode
1323 * @param mixed $value if passed - dont fetch value from db,
1324 * just format the given value
1325 * @static
1326 * @access public
1327 */
1328 static function setProfileDefaults($customFieldId,
1329 $elementName,
1330 &$defaults,
1331 $contactId = NULL,
1332 $mode = NULL,
1333 $value = NULL
1334 ) {
1335 //get the type of custom field
1336 $customField = new CRM_Core_BAO_CustomField();
1337 $customField->id = $customFieldId;
1338 $customField->find(TRUE);
1339
1340 if (!$contactId) {
1341 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1342 $value = $customField->default_value;
1343 }
1344 }
1345 else {
1346 if (!isset($value)) {
1347 $info = self::getTableColumnGroup($customFieldId);
1348 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1349 $result = CRM_Core_DAO::executeQuery($query);
1350 if ($result->fetch()) {
1351 $value = $result->value;
1352 }
1353 }
1354
1355 if ($customField->data_type == 'Country') {
1356 if (!$value) {
1357 $config = CRM_Core_Config::singleton();
1358 if ($config->defaultContactCountry) {
1359 $value = $config->defaultContactCountry();
1360 }
1361 }
1362 }
1363 }
1364
1365 //set defaults if mode is registration
1366 if (!trim($value) &&
1367 ($value !== 0) &&
1368 (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)))
1369 ) {
1370 $value = $customField->default_value;
1371 }
1372
1373 if ($customField->data_type == 'Money' && isset($value)) {
1374 $value = number_format($value, 2);
1375 }
1376 switch ($customField->html_type) {
1377 case 'CheckBox':
1378 case 'AdvMulti-Select':
1379 case 'Multi-Select':
1380 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1381 $defaults[$elementName] = array();
1382 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1383 substr($value, 1, -1)
1384 );
1385 foreach ($customOption as $val) {
1386 if (in_array($val['value'], $checkedValue)) {
1387 if ($customField->html_type == 'CheckBox') {
1388 $defaults[$elementName][$val['value']] = 1;
1389 }
1390 elseif ($customField->html_type == 'Multi-Select' ||
1391 $customField->html_type == 'AdvMulti-Select'
1392 ) {
1393 $defaults[$elementName][$val['value']] = $val['value'];
1394 }
1395 }
1396 }
1397 break;
1398
1399 case 'Select Date':
1400 if ($value) {
1401 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults(
1402 $value,
1403 NULL,
1404 $customField->date_format,
1405 $customField->time_format
1406 );
1407 }
1408 break;
1409
1410 case 'Autocomplete-Select':
1411 if ($customField->data_type == 'ContactReference') {
1412 if (is_numeric($value)) {
1413 $defaults[$elementName . '_id'] = $value;
1414 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1415 }
1416 }
1417 else {
1418 $label = CRM_Core_BAO_CustomOption::getOptionLabel($customField->id, $value);
1419 $defaults[$elementName . '_id'] = $value;
1420 $defaults[$elementName] = $label;
1421 }
1422 break;
1423
1424 default:
1425 $defaults[$elementName] = $value;
1426 }
1427 }
1428
1429 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1430 if ($contactID) {
1431 if (!$fileID) {
1432 $params = array('id' => $cfID);
1433 $defaults = array();
1434 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1435 $columnName = $defaults['column_name'];
1436
1437 //table name of custom data
1438 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1439 $defaults['custom_group_id'],
1440 'table_name', 'id'
1441 );
1442
1443 //query to fetch id from civicrm_file
1444 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1445 $fileID = CRM_Core_DAO::singleValueQuery($query);
1446 }
1447
1448 $result = array();
1449 if ($fileID) {
1450 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1451 $fileID,
1452 'mime_type',
1453 'id'
1454 );
1455 $result['file_id'] = $fileID;
1456
1457 if ($fileType == 'image/jpeg' ||
1458 $fileType == 'image/pjpeg' ||
1459 $fileType == 'image/gif' ||
1460 $fileType == 'image/x-png' ||
1461 $fileType == 'image/png'
1462 ) {
1463 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1464 $fileID,
1465 'entity_id',
1466 'id'
1467 );
1468 list($path) = CRM_Core_BAO_File::path($fileID, $entityId, NULL, NULL);
1469 list($imageWidth, $imageHeight) = getimagesize($path);
1470 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
1471 $url = CRM_Utils_System::url('civicrm/file',
1472 "reset=1&id=$fileID&eid=$contactID",
1473 $absolute, NULL, TRUE, TRUE
1474 );
1475 $result['file_url'] = "<a href='javascript:imagePopUp(\"$url\");'><img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/></a>";
1476 // for non image files
1477 }
1478 else {
1479 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1480 $fileID,
1481 'uri'
1482 );
1483 $url = CRM_Utils_System::url('civicrm/file',
1484 "reset=1&id=$fileID&eid=$contactID",
1485 $absolute, NULL, TRUE, TRUE
1486 );
1487 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1488 }
1489 }
1490 return $result;
1491 }
1492 }
1493
1494 /**
1495 * Format custom fields before inserting
1496 *
1497 * @param int $customFieldId custom field id
1498 * @param array $customFormatted formatted array
1499 * @param mix $value value of custom field
1500 * @param string $customFieldExtend custom field extends
1501 * @param int $customValueId custom option value id
1502 * @param int $entityId entity id (contribution, membership...)
1503 * @param boolean $inline consider inline custom groups only
1504 * @param boolean $checkPermission if false, do not include permissioning clause
1505 *
1506 * @return array $customFormatted formatted custom field array
1507 * @static
1508 */
1509 static function formatCustomField($customFieldId, &$customFormatted, $value,
1510 $customFieldExtend, $customValueId = NULL,
1511 $entityId = NULL,
1512 $inline = FALSE,
1513 $checkPermission = TRUE
1514 ) {
1515 //get the custom fields for the entity
1516 //subtype and basic type
1517 $customDataSubType = NULL;
1518 if (in_array($customFieldExtend,
1519 CRM_Contact_BAO_ContactType::subTypes()
1520 )) {
1521 // This is the case when getFieldsForImport() requires fields
1522 // of subtype and its parent.CRM-5143
1523 $customDataSubType = $customFieldExtend;
1524 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1525 }
1526
1527 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1528 FALSE,
1529 $inline,
1530 $customDataSubType,
1531 NULL,
1532 FALSE,
1533 FALSE,
1534 $checkPermission
1535 );
1536
1537 if (!array_key_exists($customFieldId, $customFields)) {
1538 return;
1539 }
1540
1541 // return if field is a 'code' field
1542 if (CRM_Utils_Array::value('is_view', $customFields[$customFieldId])) {
1543 return;
1544 }
1545
1546 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1547
1548 if (is_array($customFieldExtend)) {
1549 $customFieldExtend = $customFieldExtend[0];
1550 }
1551 if (!$customValueId &&
1552 // we always create new entites for is_multiple unless specified
1553 !$customFields[$customFieldId]['is_multiple'] &&
1554 $entityId
1555 ) {
1556 $query = "
1557SELECT id
1558 FROM $tableName
1559 WHERE entity_id={$entityId}";
1560
1561 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1562 }
1563
1564 //fix checkbox, now check box always submits values
1565 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1566 if ($value) {
1567 // Note that only during merge this is not an array, and you can directly use value
1568 if (is_array($value)) {
1569 $selectedValues = array();
1570 foreach ($value as $selId => $val) {
1571 if ($val) {
1572 $selectedValues[] = $selId;
1573 }
1574 }
1575 if (!empty($selectedValues)) {
1576 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1577 $selectedValues
1578 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1579 }
1580 else {
1581 $value = '';
1582 }
1583 }
1584 }
1585 }
1586
1587 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1588 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1589 ) {
1590 if ($value) {
1591 // Note that only during merge this is not an array,
1592 // and you can directly use value, CRM-4385
1593 if (is_array($value)) {
1594 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1595 array_values($value)
1596 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1597 }
1598 }
1599 else {
1600 $value = '';
1601 }
1602 }
1603
1604 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1605 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1606 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1607 ) &&
1608 $customFields[$customFieldId]['data_type'] == 'String' &&
1609 !empty($customFields[$customFieldId]['text_length']) &&
1610 !empty($value)
1611 ) {
1612 // lets make sure that value is less than the length, else we'll
1613 // be losing some data, CRM-7481
1614 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1615 // need to do a few things here
1616
1617 // 1. lets find a new length
1618 $newLength = $customFields[$customFieldId]['text_length'];
1619 $minLength = strlen($value);
1620 while ($newLength < $minLength) {
1621 $newLength = $newLength * 2;
1622 }
1623
1624 // set the custom field meta data to have a length larger than value
1625 // alter the custom value table column to match this length
1626 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1627 }
1628 }
1629
1630 $date = NULL;
1631 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1632 if (!CRM_Utils_System::isNull($value)) {
1633 $format = $customFields[$customFieldId]['date_format'];
1634 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1635 }
1636 $value = $date;
1637 }
1638
1639 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1640 $customFields[$customFieldId]['data_type'] == 'Money'
1641 ) {
1642 if (!$value) {
1643 $value = 0;
1644 }
1645
1646 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1647 $value = CRM_Utils_Rule::cleanMoney($value);
1648 }
1649 }
1650
1651 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1652 $customFields[$customFieldId]['data_type'] == 'Country'
1653 ) &&
1654 empty($value)
1655 ) {
1656 // CRM-3415
1657 $value = 0;
1658 }
1659
1660 $fileId = NULL;
1661
1662 if ($customFields[$customFieldId]['data_type'] == 'File') {
1663 if (empty($value)) {
1664 return;
1665 }
1666
1667 $config = CRM_Core_Config::singleton();
1668
1669 $fName = $value['name'];
1670 $mimeType = $value['type'];
1671
1672 $filename = pathinfo($fName, PATHINFO_BASENAME);
1673
1674 // rename this file to go into the secure directory
1675 if (!rename($fName, $config->customFileUploadDir . $filename)) {
1676 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1677 break;
1678 }
1679
1680 if ($customValueId) {
1681 $query = "
1682SELECT $columnName
1683 FROM $tableName
1684 WHERE id = %1";
1685 $params = array(1 => array($customValueId, 'Integer'));
1686 $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
1687 }
1688
1689 $fileDAO = new CRM_Core_DAO_File();
1690
1691 if ($fileId) {
1692 $fileDAO->id = $fileId;
1693 }
1694
1695 $fileDAO->uri = $filename;
1696 $fileDAO->mime_type = $mimeType;
1697 $fileDAO->upload_date = date('Ymdhis');
1698 $fileDAO->save();
1699 $fileId = $fileDAO->id;
1700 $value = $filename;
1701 }
1702
1703 if (!is_array($customFormatted)) {
1704 $customFormatted = array();
1705 }
1706
1707 if (!array_key_exists($customFieldId, $customFormatted)) {
1708 $customFormatted[$customFieldId] = array();
1709 }
1710
1711 $index = -1;
1712 if ($customValueId) {
1713 $index = $customValueId;
1714 }
1715
1716 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1717 $customFormatted[$customFieldId][$index] = array();
1718 }
1719 $customFormatted[$customFieldId][$index] = array(
1720 'id' => $customValueId > 0 ? $customValueId : NULL,
1721 'value' => $value,
1722 'type' => $customFields[$customFieldId]['data_type'],
1723 'custom_field_id' => $customFieldId,
1724 'custom_group_id' => $groupID,
1725 'table_name' => $tableName,
1726 'column_name' => $columnName,
1727 'file_id' => $fileId,
1728 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1729 );
1730
1731 //we need to sort so that custom fields are created in the order of entry
1732 krsort($customFormatted[$customFieldId]);
1733 return $customFormatted;
1734 }
1735
1736 static function &defaultCustomTableSchema(&$params) {
1737 // add the id and extends_id
1738 $table = array(
1739 'name' => $params['name'],
1740 'is_multiple' => $params['is_multiple'],
1741 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1742 'fields' => array(
1743 array(
1744 'name' => 'id',
1745 'type' => 'int unsigned',
1746 'primary' => TRUE,
1747 'required' => TRUE,
1748 'attributes' => 'AUTO_INCREMENT',
1749 'comment' => 'Default MySQL primary key',
1750 ),
1751 array(
1752 'name' => 'entity_id',
1753 'type' => 'int unsigned',
1754 'required' => TRUE,
1755 'comment' => 'Table that this extends',
1756 'fk_table_name' => $params['extends_name'],
1757 'fk_field_name' => 'id',
1758 'fk_attributes' => 'ON DELETE CASCADE',
1759 ),
1760 ),
1761 );
1762
1763 if (!$params['is_multiple']) {
1764 $table['indexes'] = array(
1765 array(
1766 'unique' => TRUE,
1767 'field_name_1' => 'entity_id',
1768 ),
1769 );
1770 }
1771 return $table;
1772 }
1773
1774 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1775 $tableName = CRM_Core_DAO::getFieldValue(
1776 'CRM_Core_DAO_CustomGroup',
1777 $field->custom_group_id,
1778 'table_name'
1779 );
1780
1781 $params = array(
1782 'table_name' => $tableName,
1783 'operation' => $operation,
1784 'name' => $field->column_name,
1785 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
1786 $field->data_type,
1787 $field->text_length
1788 ),
1789 'required' => $field->is_required,
1790 'searchable' => $field->is_searchable,
1791 );
1792
1793 if ($operation == 'delete') {
1794 $fkName = "{$tableName}_{$field->column_name}";
1795 if (strlen($fkName) >= 48) {
1796 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1797 }
1798 $params['fkName'] = $fkName;
1799 }
1800 if ($field->data_type == 'Country' && $field->html_type == 'Select Country') {
1801 $params['fk_table_name'] = 'civicrm_country';
1802 $params['fk_field_name'] = 'id';
1803 $params['fk_attributes'] = 'ON DELETE SET NULL';
1804 }
1805 elseif ($field->data_type == 'Country' && $field->html_type == 'Multi-Select Country') {
1806 $params['type'] = 'varchar(255)';
1807 }
1808 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Select State/Province') {
1809 $params['fk_table_name'] = 'civicrm_state_province';
1810 $params['fk_field_name'] = 'id';
1811 $params['fk_attributes'] = 'ON DELETE SET NULL';
1812 }
1813 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Multi-Select State/Province') {
1814 $params['type'] = 'varchar(255)';
1815 }
1816 elseif ($field->data_type == 'File') {
1817 $params['fk_table_name'] = 'civicrm_file';
1818 $params['fk_field_name'] = 'id';
1819 $params['fk_attributes'] = 'ON DELETE SET NULL';
1820 }
1821 elseif ($field->data_type == 'ContactReference') {
1822 $params['fk_table_name'] = 'civicrm_contact';
1823 $params['fk_field_name'] = 'id';
1824 $params['fk_attributes'] = 'ON DELETE SET NULL';
1825 }
1826 if ($field->default_value) {
1827 $params['default'] = "'{$field->default_value}'";
1828 }
1829
1830 CRM_Core_BAO_SchemaHandler::alterFieldSQL($params, $indexExist, $triggerRebuild);
1831 }
1832
1833 /**
1834 * Determine whether it would be safe to move a field
1835 *
1836 * @param int $fieldID FK to civicrm_custom_field
1837 * @param int $newGroupID FK to civicrm_custom_group
1838 *
1839 * @return array(
1840 string) or TRUE
1841 */
1842 static function _moveFieldValidate($fieldID, $newGroupID) {
1843 $errors = array();
1844
1845 $field = new CRM_Core_DAO_CustomField();
1846 $field->id = $fieldID;
1847 if (!$field->find(TRUE)) {
1848 $errors['fieldID'] = 'Invalid ID for custom field';
1849 return $errors;
1850 }
1851
1852 $oldGroup = new CRM_Core_DAO_CustomGroup();
1853 $oldGroup->id = $field->custom_group_id;
1854 if (!$oldGroup->find(TRUE)) {
1855 $errors['fieldID'] = 'Invalid ID for old custom group';
1856 return $errors;
1857 }
1858
1859 $newGroup = new CRM_Core_DAO_CustomGroup();
1860 $newGroup->id = $newGroupID;
1861 if (!$newGroup->find(TRUE)) {
1862 $errors['newGroupID'] = 'Invalid ID for new custom group';
1863 return $errors;
1864 }
1865
1866 $query = "
1867SELECT b.id
1868FROM civicrm_custom_field a
1869INNER JOIN civicrm_custom_field b
1870WHERE a.id = %1
1871AND a.label = b.label
1872AND b.custom_group_id = %2
1873";
1874 $params = array(
1875 1 => array($field->id, 'Integer'),
1876 2 => array($newGroup->id, 'Integer'),
1877 );
1878 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1879 if ($count > 0) {
1880 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1881 }
1882
1883 $tableName = $oldGroup->table_name;
1884 $columnName = $field->column_name;
1885
1886 $query = "
1887SELECT count(*)
1888FROM $tableName
1889WHERE $columnName is not null
1890";
1891 $count = CRM_Core_DAO::singleValueQuery($query,
1892 CRM_Core_DAO::$_nullArray
1893 );
1894 if ($count > 0) {
1895 $query = "
1896SELECT extends
1897FROM civicrm_custom_group
1898WHERE id IN ( %1, %2 )
1899";
1900 $params = array(1 => array($oldGroup->id, 'Integer'),
1901 2 => array($newGroup->id, 'Integer'),
1902 );
1903
1904 $dao = CRM_Core_DAO::executeQuery($query, $params);
1905 $extends = array();
1906 while ($dao->fetch()) {
1907 $extends[] = $dao->extends;
1908 }
1909 if ($extends[0] != $extends[1]) {
1910 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1911 }
1912 }
1913
1914 return empty($errors) ? TRUE : $errors;
1915 }
1916
1917 /**
1918 * Move a custom data field from one group (table) to another
1919 *
1920 * @param int $fieldID FK to civicrm_custom_field
1921 * @param int $newGroupID FK to civicrm_custom_group
1922 *
1923 * @return void
1924 */
1925 static function moveField($fieldID, $newGroupID) {
1926 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1927 if (TRUE !== $validation) {
1928 CRM_Core_Error::fatal(implode(' ', $validation));
1929 }
1930 $field = new CRM_Core_DAO_CustomField();
1931 $field->id = $fieldID;
1932 $field->find(TRUE);
1933
1934 $newGroup = new CRM_Core_DAO_CustomGroup();
1935 $newGroup->id = $newGroupID;
1936 $newGroup->find(TRUE);
1937
1938 $oldGroup = new CRM_Core_DAO_CustomGroup();
1939 $oldGroup->id = $field->custom_group_id;
1940 $oldGroup->find(TRUE);
1941
1942 $add = clone$field;
1943 $add->custom_group_id = $newGroup->id;
1944 self::createField($add, 'add');
1945
1946 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1947 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1948 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1949 ";
1950 CRM_Core_DAO::executeQuery($sql);
1951
1952 $del = clone$field;
1953 $del->custom_group_id = $oldGroup->id;
1954 self::createField($del, 'delete');
1955
1956 $add->save();
1957
1958 CRM_Utils_System::flushCache();
1959 }
1960
1961 /**
1962 * Get the database table name and column name for a custom field
1963 *
1964 * @param int $fieldID - the fieldID of the custom field
1965 * @param boolean $force - force the sql to be run again (primarily used for tests)
1966 *
1967 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
1968 * @static
1969 * @public
1970 */
1971 static function getTableColumnGroup($fieldID, $force = FALSE) {
1972 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1973 $cache = CRM_Utils_Cache::singleton();
1974 $fieldValues = $cache->get($cacheKey);
1975 if (empty($fieldValues) || $force) {
1976 $query = "
1977SELECT cg.table_name, cf.column_name, cg.id
1978FROM civicrm_custom_group cg,
1979 civicrm_custom_field cf
1980WHERE cf.custom_group_id = cg.id
1981AND cf.id = %1";
1982 $params = array(1 => array($fieldID, 'Integer'));
1983 $dao = CRM_Core_DAO::executeQuery($query, $params);
1984
1985 if (!$dao->fetch()) {
1986 CRM_Core_Error::fatal();
1987 }
1988 $dao->free();
1989 $fieldValues = array($dao->table_name, $dao->column_name, $dao->id);
1990 $cache->set($cacheKey, $fieldValues);
1991 }
1992 return $fieldValues;
1993 }
1994
1995 /**
1996 * Function to get custom option groups
1997 *
1998 * @params array $includeFieldIds ids of custom fields for which
1999 * option groups must be included.
2000 *
2001 * Currently this is required in the cases where option groups are to be included
2002 * for inactive fields : CRM-5369
2003 *
2004 * @access public
2005 *
2006 * @return $customOptionGroup
2007 * @static
2008 */
2009 public static function &customOptionGroup($includeFieldIds = NULL) {
2010 static $customOptionGroup = NULL;
2011
2012 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2013 if ($cacheKey == 'force') {
2014 $customOptionGroup[$cacheKey] = NULL;
2015 }
2016
2017 if (!CRM_Utils_Array::value($cacheKey, $customOptionGroup)) {
2018 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2019
2020 //support for single as well as array format.
2021 if (!empty($includeFieldIds)) {
2022 if (is_array($includeFieldIds)) {
2023 $includeFieldIds = implode(',', $includeFieldIds);
2024 }
2025 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2026 }
2027
2028 $query = "
2029 SELECT g.id, g.title
2030 FROM civicrm_option_group g
2031INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2032 WHERE {$whereClause}";
2033
2034 $dao = CRM_Core_DAO::executeQuery($query);
2035 while ($dao->fetch()) {
2036 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2037 }
2038 }
2039
2040 return $customOptionGroup[$cacheKey];
2041 }
2042
2043 /**
2044 * Function to fix orphan groups
2045 *
2046 * @params int $customFieldId custom field id
2047 * @params int $optionGroupId option group id
2048 *
2049 * @access public
2050 *
2051 * @return void
2052 * @static
2053 */
2054 static function fixOptionGroups($customFieldId, $optionGroupId) {
2055 // check if option group belongs to any custom Field else delete
2056 // get the current option group
2057 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2058 $customFieldId,
2059 'option_group_id'
2060 );
2061 // get the updated option group
2062 // if both are same return
2063 if ($currentOptionGroupId == $optionGroupId) {
2064 return;
2065 }
2066
2067 // check if option group is related to any other field
2068 self::checkOptionGroup($currentOptionGroupId);
2069 }
2070
2071 /**
2072 * Function to check if option group is related to more than one
2073 * custom field
2074 *
2075 * @params int $optionGroupId option group id
2076 *
2077 * @return
2078 * @static
2079 */
2080 static function checkOptionGroup($optionGroupId) {
2081 $query = "
2082SELECT count(*)
2083FROM civicrm_custom_field
2084WHERE option_group_id = {$optionGroupId}";
2085
2086 $count = CRM_Core_DAO::singleValueQuery($query);
2087
2088 if ($count < 2) {
2089 //delete the option group
2090 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2091 }
2092 }
2093
2094 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2095 $query = "
2096SELECT default_value, html_type
2097FROM civicrm_custom_field
2098WHERE option_group_id = {$optionGroupId}
2099AND default_value IS NOT NULL
2100ORDER BY html_type";
2101
2102 $dao = CRM_Core_DAO::executeQuery($query);
2103 $defaultValue = NULL;
2104 $defaultHTMLType = NULL;
2105 while ($dao->fetch()) {
2106 if ($dao->html_type == $htmlType) {
2107 return $dao->default_value;
2108 }
2109 if ($defaultValue == NULL) {
2110 $defaultValue = $dao->default_value;
2111 $defaultHTMLType = $dao->html_type;
2112 }
2113 }
2114
2115 // some conversions are needed if either the old or new has a html type which has potential
2116 // multiple default values.
2117 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2118 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2119 ) {
2120 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2121 }
2122 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2123 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2124 ) {
2125 $defaultValue = substr($defaultValue, 1, -1);
2126 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2127 substr($defaultValue, 1, -1)
2128 );
2129 $defaultValue = $values[0];
2130 }
2131
2132 return $defaultValue;
2133 }
2134
2135 static function postProcess(&$params,
2136 &$customFields,
2137 $entityID,
2138 $customFieldExtends,
2139 $inline = FALSE
2140 ) {
2141 $customData = array();
2142
2143 foreach ($params as $key => $value) {
2144 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2145
2146 // for autocomplete transfer hidden value instead of label
2147 if ($params[$key] && isset($params[$key . '_id'])) {
2148 $value = $params[$key . '_id'];
2149 }
2150
2151 // we need to append time with date
2152 if ($params[$key] && isset($params[$key . '_time'])) {
2153 $value .= ' ' . $params[$key . '_time'];
2154 }
2155
2156 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2157 $customData,
2158 $value,
2159 $customFieldExtends,
2160 $customFieldInfo[1],
2161 $entityID,
2162 $inline
2163 );
2164 }
2165 }
2166 return $customData;
2167 }
2168
2169 static function buildOption($field, &$options) {
2170 $options['attributes'] = array(
2171 'label' => $field['label'],
2172 'data_type' => $field['data_type'],
2173 'html_type' => $field['html_type'],
2174 );
2175
2176 $optionGroupID = NULL;
2177 if (($field['html_type'] == 'CheckBox' ||
2178 $field['html_type'] == 'Radio' ||
2179 $field['html_type'] == 'Select' ||
2180 $field['html_type'] == 'AdvMulti-Select' ||
2181 $field['html_type'] == 'Multi-Select' ||
2182 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2183 )) {
2184 if ($field['option_group_id']) {
2185 $optionGroupID = $field['option_group_id'];
2186 }
2187 elseif ($field['data_type'] != 'Boolean') {
2188 CRM_Core_Error::fatal();
2189 }
2190 }
2191
2192 // build the cache for custom values with options (label => value)
2193 if ($optionGroupID != NULL) {
2194 $query = "
2195SELECT label, value
2196 FROM civicrm_option_value
2197 WHERE option_group_id = $optionGroupID
2198";
2199
2200 $dao = CRM_Core_DAO::executeQuery($query);
2201 while ($dao->fetch()) {
2202 if ($field['data_type'] == 'Int' || $field['data_type'] == 'Float') {
2203 $num = round($dao->value, 2);
2204 $options["$num"] = $dao->label;
2205 }
2206 else {
2207 $options[$dao->value] = $dao->label;
2208 }
2209 }
2210
2211 CRM_Utils_Hook::customFieldOptions($field['id'], $options);
2212 }
2213 }
2214
2215 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2216 $params = array(1 => array($fieldLabel, 'String'));
2217 if ($groupTitle) {
2218 $params[2] = array($groupTitle, 'String');
2219 $sql = "
2220SELECT f.id
2221FROM civicrm_custom_field f
2222INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2223WHERE ( f.label = %1 OR f.name = %1 )
2224AND ( g.title = %2 OR g.name = %2 )
2225";
2226 }
2227 else {
2228 $sql = "
2229SELECT f.id
2230FROM civicrm_custom_field f
2231WHERE ( f.label = %1 OR f.name = %1 )
2232";
2233 }
2234
2235 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2236 if ($dao->fetch() &&
2237 $dao->N == 1
2238 ) {
2239 return $dao->id;
2240 }
2241 else {
2242 return NULL;
2243 }
2244 }
2245
2246 /**
2247 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2248 *
2249 */
2250 static function getNameFromID($ids) {
2251 if (is_array($ids)) {
2252 $ids = implode(',', $ids);
2253 }
2254 $sql = "
2255SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2256FROM civicrm_custom_field f
2257INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2258WHERE f.id IN ($ids)";
2259
2260
2261 $dao = CRM_Core_DAO::executeQuery($sql);
2262 $result = array();
2263 while ($dao->fetch()) {
2264 $result[$dao->id] = array(
2265 'field_name' => $dao->field_name,
2266 'field_label' => $dao->field_label,
2267 'group_name' => $dao->group_name,
2268 'group_title' => $dao->group_title,
2269 );
2270 }
2271 return $result;
2272 }
2273
2274 /**
2275 * Validate custom data.
2276 *
2277 * @param array $params custom data submitted.
2278 * ie array( 'custom_1' => 'validate me' );
2279 *
2280 * @return array $errors validation errors.
2281 * @static
2282 */
2283 static function validateCustomData($params) {
2284 $errors = array();
2285 if (!is_array($params) || empty($params)) {
2286 return $errors;
2287 }
2288
2289
2290 //pick up profile fields.
2291 $profileFields = array();
2292 $ufGroupId = CRM_Utils_Array::value('ufGroupId', $params);
2293 if ($ufGroupId) {
2294 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2295 FALSE,
2296 CRM_Core_Action::VIEW
2297 );
2298 }
2299
2300 //lets start w/ params.
2301 foreach ($params as $key => $value) {
2302 $customFieldID = self::getKeyID($key);
2303 if (!$customFieldID) {
2304 continue;
2305 }
2306
2307 //load the structural info for given field.
2308 $field = new CRM_Core_DAO_CustomField();
2309 $field->id = $customFieldID;
2310 if (!$field->find(TRUE)) {
2311 continue;
2312 }
2313 $dataType = $field->data_type;
2314
2315 $profileField = CRM_Utils_Array::value($key, $profileFields, array());
2316 $fieldTitle = CRM_Utils_Array::value('title', $profileField);
2317 $isRequired = CRM_Utils_Array::value('is_required', $profileField);
2318 if (!$fieldTitle) {
2319 $fieldTitle = $field->label;
2320 }
2321
2322 //no need to validate.
2323 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2324 continue;
2325 }
2326
2327 //lets validate first for required field.
2328 if ($isRequired && CRM_Utils_System::isNull($value)) {
2329 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2330 continue;
2331 }
2332
2333 //now time to take care of custom field form rules.
2334 $ruleName = $errorMsg = NULL;
2335 switch ($dataType) {
2336 case 'Int':
2337 $ruleName = 'integer';
2338 $errorMsg = ts('%1 must be an integer (whole number).',
2339 array(1 => $fieldTitle)
2340 );
2341 break;
2342
2343 case 'Money':
2344 $ruleName = 'money';
2345 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2346 array(1 => $fieldTitle)
2347 );
2348 break;
2349
2350 case 'Float':
2351 $ruleName = 'numeric';
2352 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2353 array(1 => $fieldTitle)
2354 );
2355 break;
2356
2357 case 'Link':
2358 $ruleName = 'wikiURL';
2359 $errorMsg = ts('%1 must be valid Website.',
2360 array(1 => $fieldTitle)
2361 );
2362 break;
2363 }
2364
2365 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2366 $valid = FALSE;
2367 $funName = "CRM_Utils_Rule::{$ruleName}";
2368 if (is_callable($funName)) {
2369 $valid = call_user_func($funName, $value);
2370 }
2371 if (!$valid) {
2372 $errors[$key] = $errorMsg;
2373 }
2374 }
2375 }
2376
2377 return $errors;
2378 }
2379
2380 static function isMultiRecordField($customId) {
2381 $isMultipleWithGid = FALSE;
2382 if (!is_numeric($customId)) {
2383 $customId = self::getKeyID($customId);
2384 }
2385 if (is_numeric($customId)) {
2386 $sql = "SELECT cg.id cgId
2387 FROM civicrm_custom_group cg
2388 INNER JOIN civicrm_custom_field cf
2389 ON cg.id = cf.custom_group_id
2390WHERE cf.id = %1 AND cg.is_multiple = 1";
2391 $params[1] = array($customId, 'Integer');
2392 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2393 if ($dao->fetch()) {
2394 if ($dao->cgId) {
2395 $isMultipleWithGid = $dao->cgId;
2396 }
2397 }
2398 }
2399
2400 return $isMultipleWithGid;
2401 }
2402}
2403