Merge pull request #1118 from totten/master-apientities
[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 $display = $value ? ts('Yes') : ts('No');
1155 }
1156 else {
1157 $display = CRM_Utils_Array::value($value, $option);
1158 }
1159 break;
1160
1161 case 'Autocomplete-Select':
1162 if ($data_type == 'ContactReference' &&
1163 $value
1164 ) {
1165 $display = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1166 }
1167 else {
1168 $display = CRM_Utils_Array::value($value, $option);
1169 }
1170 break;
1171
1172 case 'Select':
1173 $display = CRM_Utils_Array::value($value, $option);
1174 break;
1175
1176 case 'CheckBox':
1177 case 'AdvMulti-Select':
1178 case 'Multi-Select':
1179 if (is_array($value)) {
1180 $checkedData = $value;
1181 }
1182 else {
1183 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1184 substr($value, 1, -1)
1185 );
1186 if ($html_type == 'CheckBox') {
1187 $newData = array();
1188 foreach ($checkedData as $v) {
1189 $newData[$v] = 1;
1190 }
1191 $checkedData = $newData;
1192 }
1193 }
1194
1195 $v = array();
1196 $p = array();
1197 foreach ($checkedData as $key => $val) {
1198 if ($key === 'CiviCRM_OP_OR') {
1199 continue;
1200 }
1201
1202 if ($html_type == 'CheckBox') {
1203 if ($val) {
1204 $p[] = $key;
1205 $v[] = CRM_Utils_Array::value($key, $option);
1206 }
1207 }
1208 else {
1209 $p[] = $val;
1210 $v[] = CRM_Utils_Array::value($val, $option);
1211 }
1212 }
1213 if (!empty($v)) {
1214 $display = implode(', ', $v);
1215 }
1216 break;
1217
1218 case 'Select Date':
1219 if (is_array($value)) {
1220 foreach ($value as $key => $val) {
1221 $display[$key] = CRM_Utils_Date::customFormat($val);
1222 }
1223 }
1224 else {
1225 // remove time element display if time is not set
1226 if (empty($option['attributes']['time_format'])) {
1227 $value = substr($value, 0, 10);
1228 }
1229 $display = CRM_Utils_Date::customFormat($value);
1230 }
1231 break;
1232
1233 case 'Select State/Province':
1234 if (empty($value)) {
1235 $display = '';
1236 }
1237 else {
1238 $display = CRM_Core_PseudoConstant::stateProvince($value);
1239 }
1240 break;
1241
1242 case 'Multi-Select State/Province':
1243 if (is_array($value)) {
1244 $checkedData = $value;
1245 }
1246 else {
1247 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1248 substr($value, 1, -1)
1249 );
1250 }
1251
1252 $states = CRM_Core_PseudoConstant::stateProvince();
1253 $display = NULL;
1254 foreach ($checkedData as $stateID) {
1255 if ($display) {
1256 $display .= ', ';
1257 }
1258 $display .= $states[$stateID];
1259 }
1260 break;
1261
1262 case 'Select Country':
1263 if (empty($value)) {
1264 $display = '';
1265 }
1266 else {
1267 $display = CRM_Core_PseudoConstant::country($value);
1268 }
1269 break;
1270
1271 case 'Multi-Select Country':
1272 if (is_array($value)) {
1273 $checkedData = $value;
1274 }
1275 else {
1276 $checkedData = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1277 substr($value, 1, -1)
1278 );
1279 }
1280
1281 $countries = CRM_Core_PseudoConstant::country();
1282 $display = NULL;
1283 foreach ($checkedData as $countryID) {
1284 if ($display) {
1285 $display .= ', ';
1286 }
1287 $display .= $countries[$countryID];
1288 }
1289 break;
1290
1291 case 'File':
1292 if ($contactID) {
1293 $url = self::getFileURL($contactID, $fieldID, $value);
1294 if ($url) {
1295 $display = $url['file_url'];
1296 }
1297 }
1298 break;
1299
1300 case 'TextArea':
1301 if (empty($value)) {
1302 $display = '';
1303 }
1304 else {
1305 $display = nl2br($value);
1306 }
1307 break;
1308
1309 case 'Link':
1310 if (empty($value)) {
1311 $display = '';
1312 }
1313 else {
1314 $display = $value;
1315 }
1316 }
1317
1318 return $display ? $display : $value;
1319 }
1320
1321 /**
1322 * Function to set default values for custom data used in profile
1323 *
1324 * @params int $customFieldId custom field id
1325 * @params string $elementName custom field name
1326 * @params array $defaults associated array of fields
1327 * @params int $contactId contact id
1328 * @param int $mode profile mode
1329 * @param mixed $value if passed - dont fetch value from db,
1330 * just format the given value
1331 * @static
1332 * @access public
1333 */
1334 static function setProfileDefaults($customFieldId,
1335 $elementName,
1336 &$defaults,
1337 $contactId = NULL,
1338 $mode = NULL,
1339 $value = NULL
1340 ) {
1341 //get the type of custom field
1342 $customField = new CRM_Core_BAO_CustomField();
1343 $customField->id = $customFieldId;
1344 $customField->find(TRUE);
1345
1346 if (!$contactId) {
1347 if ($mode == CRM_Profile_Form::MODE_CREATE) {
1348 $value = $customField->default_value;
1349 }
1350 }
1351 else {
1352 if (!isset($value)) {
1353 $info = self::getTableColumnGroup($customFieldId);
1354 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1355 $result = CRM_Core_DAO::executeQuery($query);
1356 if ($result->fetch()) {
1357 $value = $result->value;
1358 }
1359 }
1360
1361 if ($customField->data_type == 'Country') {
1362 if (!$value) {
1363 $config = CRM_Core_Config::singleton();
1364 if ($config->defaultContactCountry) {
1365 $value = $config->defaultContactCountry();
1366 }
1367 }
1368 }
1369 }
1370
1371 //set defaults if mode is registration
1372 if (!trim($value) &&
1373 ($value !== 0) &&
1374 (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)))
1375 ) {
1376 $value = $customField->default_value;
1377 }
1378
1379 if ($customField->data_type == 'Money' && isset($value)) {
1380 $value = number_format($value, 2);
1381 }
1382 switch ($customField->html_type) {
1383 case 'CheckBox':
1384 case 'AdvMulti-Select':
1385 case 'Multi-Select':
1386 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldId, FALSE);
1387 $defaults[$elementName] = array();
1388 $checkedValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1389 substr($value, 1, -1)
1390 );
1391 foreach ($customOption as $val) {
1392 if (in_array($val['value'], $checkedValue)) {
1393 if ($customField->html_type == 'CheckBox') {
1394 $defaults[$elementName][$val['value']] = 1;
1395 }
1396 elseif ($customField->html_type == 'Multi-Select' ||
1397 $customField->html_type == 'AdvMulti-Select'
1398 ) {
1399 $defaults[$elementName][$val['value']] = $val['value'];
1400 }
1401 }
1402 }
1403 break;
1404
1405 case 'Select Date':
1406 if ($value) {
1407 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date::setDateDefaults(
1408 $value,
1409 NULL,
1410 $customField->date_format,
1411 $customField->time_format
1412 );
1413 }
1414 break;
1415
1416 case 'Autocomplete-Select':
1417 if ($customField->data_type == 'ContactReference') {
1418 if (is_numeric($value)) {
1419 $defaults[$elementName . '_id'] = $value;
1420 $defaults[$elementName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1421 }
1422 }
1423 else {
1424 $label = CRM_Core_BAO_CustomOption::getOptionLabel($customField->id, $value);
1425 $defaults[$elementName . '_id'] = $value;
1426 $defaults[$elementName] = $label;
1427 }
1428 break;
1429
1430 default:
1431 $defaults[$elementName] = $value;
1432 }
1433 }
1434
1435 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE) {
1436 if ($contactID) {
1437 if (!$fileID) {
1438 $params = array('id' => $cfID);
1439 $defaults = array();
1440 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1441 $columnName = $defaults['column_name'];
1442
1443 //table name of custom data
1444 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',
1445 $defaults['custom_group_id'],
1446 'table_name', 'id'
1447 );
1448
1449 //query to fetch id from civicrm_file
1450 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1451 $fileID = CRM_Core_DAO::singleValueQuery($query);
1452 }
1453
1454 $result = array();
1455 if ($fileID) {
1456 $fileType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1457 $fileID,
1458 'mime_type',
1459 'id'
1460 );
1461 $result['file_id'] = $fileID;
1462
1463 if ($fileType == 'image/jpeg' ||
1464 $fileType == 'image/pjpeg' ||
1465 $fileType == 'image/gif' ||
1466 $fileType == 'image/x-png' ||
1467 $fileType == 'image/png'
1468 ) {
1469 $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile',
1470 $fileID,
1471 'entity_id',
1472 'id'
1473 );
1474 list($path) = CRM_Core_BAO_File::path($fileID, $entityId, NULL, NULL);
1475 list($imageWidth, $imageHeight) = getimagesize($path);
1476 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
1477 $url = CRM_Utils_System::url('civicrm/file',
1478 "reset=1&id=$fileID&eid=$contactID",
1479 $absolute, NULL, TRUE, TRUE
1480 );
1481 $result['file_url'] = "<a href='javascript:imagePopUp(\"$url\");'><img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/></a>";
1482 // for non image files
1483 }
1484 else {
1485 $uri = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_File',
1486 $fileID,
1487 'uri'
1488 );
1489 $url = CRM_Utils_System::url('civicrm/file',
1490 "reset=1&id=$fileID&eid=$contactID",
1491 $absolute, NULL, TRUE, TRUE
1492 );
1493 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1494 }
1495 }
1496 return $result;
1497 }
1498 }
1499
1500 /**
1501 * Format custom fields before inserting
1502 *
1503 * @param int $customFieldId custom field id
1504 * @param array $customFormatted formatted array
1505 * @param mix $value value of custom field
1506 * @param string $customFieldExtend custom field extends
1507 * @param int $customValueId custom option value id
1508 * @param int $entityId entity id (contribution, membership...)
1509 * @param boolean $inline consider inline custom groups only
1510 * @param boolean $checkPermission if false, do not include permissioning clause
1511 *
1512 * @return array $customFormatted formatted custom field array
1513 * @static
1514 */
1515 static function formatCustomField($customFieldId, &$customFormatted, $value,
1516 $customFieldExtend, $customValueId = NULL,
1517 $entityId = NULL,
1518 $inline = FALSE,
1519 $checkPermission = TRUE
1520 ) {
1521 //get the custom fields for the entity
1522 //subtype and basic type
1523 $customDataSubType = NULL;
1524 if (in_array($customFieldExtend,
1525 CRM_Contact_BAO_ContactType::subTypes()
1526 )) {
1527 // This is the case when getFieldsForImport() requires fields
1528 // of subtype and its parent.CRM-5143
1529 $customDataSubType = $customFieldExtend;
1530 $customFieldExtend = CRM_Contact_BAO_ContactType::getBasicType($customDataSubType);
1531 }
1532
1533 $customFields = CRM_Core_BAO_CustomField::getFields($customFieldExtend,
1534 FALSE,
1535 $inline,
1536 $customDataSubType,
1537 NULL,
1538 FALSE,
1539 FALSE,
1540 $checkPermission
1541 );
1542
1543 if (!array_key_exists($customFieldId, $customFields)) {
1544 return;
1545 }
1546
1547 // return if field is a 'code' field
1548 if (CRM_Utils_Array::value('is_view', $customFields[$customFieldId])) {
1549 return;
1550 }
1551
1552 list($tableName, $columnName, $groupID) = self::getTableColumnGroup($customFieldId);
1553
1554 if (is_array($customFieldExtend)) {
1555 $customFieldExtend = $customFieldExtend[0];
1556 }
1557 if (!$customValueId &&
1558 // we always create new entites for is_multiple unless specified
1559 !$customFields[$customFieldId]['is_multiple'] &&
1560 $entityId
1561 ) {
1562 $query = "
1563 SELECT id
1564 FROM $tableName
1565 WHERE entity_id={$entityId}";
1566
1567 $customValueId = CRM_Core_DAO::singleValueQuery($query);
1568 }
1569
1570 //fix checkbox, now check box always submits values
1571 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1572 if ($value) {
1573 // Note that only during merge this is not an array, and you can directly use value
1574 if (is_array($value)) {
1575 $selectedValues = array();
1576 foreach ($value as $selId => $val) {
1577 if ($val) {
1578 $selectedValues[] = $selId;
1579 }
1580 }
1581 if (!empty($selectedValues)) {
1582 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1583 $selectedValues
1584 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1585 }
1586 else {
1587 $value = '';
1588 }
1589 }
1590 }
1591 }
1592
1593 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1594 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1595 ) {
1596 if ($value) {
1597 // Note that only during merge this is not an array,
1598 // and you can directly use value, CRM-4385
1599 if (is_array($value)) {
1600 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1601 array_values($value)
1602 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1603 }
1604 }
1605 else {
1606 $value = '';
1607 }
1608 }
1609
1610 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1611 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1612 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1613 ) &&
1614 $customFields[$customFieldId]['data_type'] == 'String' &&
1615 !empty($customFields[$customFieldId]['text_length']) &&
1616 !empty($value)
1617 ) {
1618 // lets make sure that value is less than the length, else we'll
1619 // be losing some data, CRM-7481
1620 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1621 // need to do a few things here
1622
1623 // 1. lets find a new length
1624 $newLength = $customFields[$customFieldId]['text_length'];
1625 $minLength = strlen($value);
1626 while ($newLength < $minLength) {
1627 $newLength = $newLength * 2;
1628 }
1629
1630 // set the custom field meta data to have a length larger than value
1631 // alter the custom value table column to match this length
1632 CRM_Core_BAO_SchemaHandler::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1633 }
1634 }
1635
1636 $date = NULL;
1637 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1638 if (!CRM_Utils_System::isNull($value)) {
1639 $format = $customFields[$customFieldId]['date_format'];
1640 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, 'YmdHis', $format);
1641 }
1642 $value = $date;
1643 }
1644
1645 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1646 $customFields[$customFieldId]['data_type'] == 'Money'
1647 ) {
1648 if (!$value) {
1649 $value = 0;
1650 }
1651
1652 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1653 $value = CRM_Utils_Rule::cleanMoney($value);
1654 }
1655 }
1656
1657 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1658 $customFields[$customFieldId]['data_type'] == 'Country'
1659 ) &&
1660 empty($value)
1661 ) {
1662 // CRM-3415
1663 $value = 0;
1664 }
1665
1666 $fileId = NULL;
1667
1668 if ($customFields[$customFieldId]['data_type'] == 'File') {
1669 if (empty($value)) {
1670 return;
1671 }
1672
1673 $config = CRM_Core_Config::singleton();
1674
1675 $fName = $value['name'];
1676 $mimeType = $value['type'];
1677
1678 $filename = pathinfo($fName, PATHINFO_BASENAME);
1679
1680 // rename this file to go into the secure directory
1681 if (!rename($fName, $config->customFileUploadDir . $filename)) {
1682 CRM_Core_Error::statusBounce(ts('Could not move custom file to custom upload directory'));
1683 break;
1684 }
1685
1686 if ($customValueId) {
1687 $query = "
1688 SELECT $columnName
1689 FROM $tableName
1690 WHERE id = %1";
1691 $params = array(1 => array($customValueId, 'Integer'));
1692 $fileId = CRM_Core_DAO::singleValueQuery($query, $params);
1693 }
1694
1695 $fileDAO = new CRM_Core_DAO_File();
1696
1697 if ($fileId) {
1698 $fileDAO->id = $fileId;
1699 }
1700
1701 $fileDAO->uri = $filename;
1702 $fileDAO->mime_type = $mimeType;
1703 $fileDAO->upload_date = date('Ymdhis');
1704 $fileDAO->save();
1705 $fileId = $fileDAO->id;
1706 $value = $filename;
1707 }
1708
1709 if (!is_array($customFormatted)) {
1710 $customFormatted = array();
1711 }
1712
1713 if (!array_key_exists($customFieldId, $customFormatted)) {
1714 $customFormatted[$customFieldId] = array();
1715 }
1716
1717 $index = -1;
1718 if ($customValueId) {
1719 $index = $customValueId;
1720 }
1721
1722 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1723 $customFormatted[$customFieldId][$index] = array();
1724 }
1725 $customFormatted[$customFieldId][$index] = array(
1726 'id' => $customValueId > 0 ? $customValueId : NULL,
1727 'value' => $value,
1728 'type' => $customFields[$customFieldId]['data_type'],
1729 'custom_field_id' => $customFieldId,
1730 'custom_group_id' => $groupID,
1731 'table_name' => $tableName,
1732 'column_name' => $columnName,
1733 'file_id' => $fileId,
1734 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1735 );
1736
1737 //we need to sort so that custom fields are created in the order of entry
1738 krsort($customFormatted[$customFieldId]);
1739 return $customFormatted;
1740 }
1741
1742 static function &defaultCustomTableSchema(&$params) {
1743 // add the id and extends_id
1744 $table = array(
1745 'name' => $params['name'],
1746 'is_multiple' => $params['is_multiple'],
1747 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1748 'fields' => array(
1749 array(
1750 'name' => 'id',
1751 'type' => 'int unsigned',
1752 'primary' => TRUE,
1753 'required' => TRUE,
1754 'attributes' => 'AUTO_INCREMENT',
1755 'comment' => 'Default MySQL primary key',
1756 ),
1757 array(
1758 'name' => 'entity_id',
1759 'type' => 'int unsigned',
1760 'required' => TRUE,
1761 'comment' => 'Table that this extends',
1762 'fk_table_name' => $params['extends_name'],
1763 'fk_field_name' => 'id',
1764 'fk_attributes' => 'ON DELETE CASCADE',
1765 ),
1766 ),
1767 );
1768
1769 if (!$params['is_multiple']) {
1770 $table['indexes'] = array(
1771 array(
1772 'unique' => TRUE,
1773 'field_name_1' => 'entity_id',
1774 ),
1775 );
1776 }
1777 return $table;
1778 }
1779
1780 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1781 $tableName = CRM_Core_DAO::getFieldValue(
1782 'CRM_Core_DAO_CustomGroup',
1783 $field->custom_group_id,
1784 'table_name'
1785 );
1786
1787 $params = array(
1788 'table_name' => $tableName,
1789 'operation' => $operation,
1790 'name' => $field->column_name,
1791 'type' => CRM_Core_BAO_CustomValueTable::fieldToSQLType(
1792 $field->data_type,
1793 $field->text_length
1794 ),
1795 'required' => $field->is_required,
1796 'searchable' => $field->is_searchable,
1797 );
1798
1799 if ($operation == 'delete') {
1800 $fkName = "{$tableName}_{$field->column_name}";
1801 if (strlen($fkName) >= 48) {
1802 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1803 }
1804 $params['fkName'] = $fkName;
1805 }
1806 if ($field->data_type == 'Country' && $field->html_type == 'Select Country') {
1807 $params['fk_table_name'] = 'civicrm_country';
1808 $params['fk_field_name'] = 'id';
1809 $params['fk_attributes'] = 'ON DELETE SET NULL';
1810 }
1811 elseif ($field->data_type == 'Country' && $field->html_type == 'Multi-Select Country') {
1812 $params['type'] = 'varchar(255)';
1813 }
1814 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Select State/Province') {
1815 $params['fk_table_name'] = 'civicrm_state_province';
1816 $params['fk_field_name'] = 'id';
1817 $params['fk_attributes'] = 'ON DELETE SET NULL';
1818 }
1819 elseif ($field->data_type == 'StateProvince' && $field->html_type == 'Multi-Select State/Province') {
1820 $params['type'] = 'varchar(255)';
1821 }
1822 elseif ($field->data_type == 'File') {
1823 $params['fk_table_name'] = 'civicrm_file';
1824 $params['fk_field_name'] = 'id';
1825 $params['fk_attributes'] = 'ON DELETE SET NULL';
1826 }
1827 elseif ($field->data_type == 'ContactReference') {
1828 $params['fk_table_name'] = 'civicrm_contact';
1829 $params['fk_field_name'] = 'id';
1830 $params['fk_attributes'] = 'ON DELETE SET NULL';
1831 }
1832 if ($field->default_value) {
1833 $params['default'] = "'{$field->default_value}'";
1834 }
1835
1836 CRM_Core_BAO_SchemaHandler::alterFieldSQL($params, $indexExist, $triggerRebuild);
1837 }
1838
1839 /**
1840 * Determine whether it would be safe to move a field
1841 *
1842 * @param int $fieldID FK to civicrm_custom_field
1843 * @param int $newGroupID FK to civicrm_custom_group
1844 *
1845 * @return array(
1846 string) or TRUE
1847 */
1848 static function _moveFieldValidate($fieldID, $newGroupID) {
1849 $errors = array();
1850
1851 $field = new CRM_Core_DAO_CustomField();
1852 $field->id = $fieldID;
1853 if (!$field->find(TRUE)) {
1854 $errors['fieldID'] = 'Invalid ID for custom field';
1855 return $errors;
1856 }
1857
1858 $oldGroup = new CRM_Core_DAO_CustomGroup();
1859 $oldGroup->id = $field->custom_group_id;
1860 if (!$oldGroup->find(TRUE)) {
1861 $errors['fieldID'] = 'Invalid ID for old custom group';
1862 return $errors;
1863 }
1864
1865 $newGroup = new CRM_Core_DAO_CustomGroup();
1866 $newGroup->id = $newGroupID;
1867 if (!$newGroup->find(TRUE)) {
1868 $errors['newGroupID'] = 'Invalid ID for new custom group';
1869 return $errors;
1870 }
1871
1872 $query = "
1873 SELECT b.id
1874 FROM civicrm_custom_field a
1875 INNER JOIN civicrm_custom_field b
1876 WHERE a.id = %1
1877 AND a.label = b.label
1878 AND b.custom_group_id = %2
1879 ";
1880 $params = array(
1881 1 => array($field->id, 'Integer'),
1882 2 => array($newGroup->id, 'Integer'),
1883 );
1884 $count = CRM_Core_DAO::singleValueQuery($query, $params);
1885 if ($count > 0) {
1886 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1887 }
1888
1889 $tableName = $oldGroup->table_name;
1890 $columnName = $field->column_name;
1891
1892 $query = "
1893 SELECT count(*)
1894 FROM $tableName
1895 WHERE $columnName is not null
1896 ";
1897 $count = CRM_Core_DAO::singleValueQuery($query,
1898 CRM_Core_DAO::$_nullArray
1899 );
1900 if ($count > 0) {
1901 $query = "
1902 SELECT extends
1903 FROM civicrm_custom_group
1904 WHERE id IN ( %1, %2 )
1905 ";
1906 $params = array(1 => array($oldGroup->id, 'Integer'),
1907 2 => array($newGroup->id, 'Integer'),
1908 );
1909
1910 $dao = CRM_Core_DAO::executeQuery($query, $params);
1911 $extends = array();
1912 while ($dao->fetch()) {
1913 $extends[] = $dao->extends;
1914 }
1915 if ($extends[0] != $extends[1]) {
1916 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1917 }
1918 }
1919
1920 return empty($errors) ? TRUE : $errors;
1921 }
1922
1923 /**
1924 * Move a custom data field from one group (table) to another
1925 *
1926 * @param int $fieldID FK to civicrm_custom_field
1927 * @param int $newGroupID FK to civicrm_custom_group
1928 *
1929 * @return void
1930 */
1931 static function moveField($fieldID, $newGroupID) {
1932 $validation = self::_moveFieldValidate($fieldID, $newGroupID);
1933 if (TRUE !== $validation) {
1934 CRM_Core_Error::fatal(implode(' ', $validation));
1935 }
1936 $field = new CRM_Core_DAO_CustomField();
1937 $field->id = $fieldID;
1938 $field->find(TRUE);
1939
1940 $newGroup = new CRM_Core_DAO_CustomGroup();
1941 $newGroup->id = $newGroupID;
1942 $newGroup->find(TRUE);
1943
1944 $oldGroup = new CRM_Core_DAO_CustomGroup();
1945 $oldGroup->id = $field->custom_group_id;
1946 $oldGroup->find(TRUE);
1947
1948 $add = clone$field;
1949 $add->custom_group_id = $newGroup->id;
1950 self::createField($add, 'add');
1951
1952 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1953 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1954 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1955 ";
1956 CRM_Core_DAO::executeQuery($sql);
1957
1958 $del = clone$field;
1959 $del->custom_group_id = $oldGroup->id;
1960 self::createField($del, 'delete');
1961
1962 $add->save();
1963
1964 CRM_Utils_System::flushCache();
1965 }
1966
1967 /**
1968 * Get the database table name and column name for a custom field
1969 *
1970 * @param int $fieldID - the fieldID of the custom field
1971 * @param boolean $force - force the sql to be run again (primarily used for tests)
1972 *
1973 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
1974 * @static
1975 * @public
1976 */
1977 static function getTableColumnGroup($fieldID, $force = FALSE) {
1978 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1979 $cache = CRM_Utils_Cache::singleton();
1980 $fieldValues = $cache->get($cacheKey);
1981 if (empty($fieldValues) || $force) {
1982 $query = "
1983 SELECT cg.table_name, cf.column_name, cg.id
1984 FROM civicrm_custom_group cg,
1985 civicrm_custom_field cf
1986 WHERE cf.custom_group_id = cg.id
1987 AND cf.id = %1";
1988 $params = array(1 => array($fieldID, 'Integer'));
1989 $dao = CRM_Core_DAO::executeQuery($query, $params);
1990
1991 if (!$dao->fetch()) {
1992 CRM_Core_Error::fatal();
1993 }
1994 $dao->free();
1995 $fieldValues = array($dao->table_name, $dao->column_name, $dao->id);
1996 $cache->set($cacheKey, $fieldValues);
1997 }
1998 return $fieldValues;
1999 }
2000
2001 /**
2002 * Function to get custom option groups
2003 *
2004 * @params array $includeFieldIds ids of custom fields for which
2005 * option groups must be included.
2006 *
2007 * Currently this is required in the cases where option groups are to be included
2008 * for inactive fields : CRM-5369
2009 *
2010 * @access public
2011 *
2012 * @return $customOptionGroup
2013 * @static
2014 */
2015 public static function &customOptionGroup($includeFieldIds = NULL) {
2016 static $customOptionGroup = NULL;
2017
2018 $cacheKey = (empty($includeFieldIds)) ? 'onlyActive' : 'force';
2019 if ($cacheKey == 'force') {
2020 $customOptionGroup[$cacheKey] = NULL;
2021 }
2022
2023 if (!CRM_Utils_Array::value($cacheKey, $customOptionGroup)) {
2024 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2025
2026 //support for single as well as array format.
2027 if (!empty($includeFieldIds)) {
2028 if (is_array($includeFieldIds)) {
2029 $includeFieldIds = implode(',', $includeFieldIds);
2030 }
2031 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2032 }
2033
2034 $query = "
2035 SELECT g.id, g.title
2036 FROM civicrm_option_group g
2037 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2038 WHERE {$whereClause}";
2039
2040 $dao = CRM_Core_DAO::executeQuery($query);
2041 while ($dao->fetch()) {
2042 $customOptionGroup[$cacheKey][$dao->id] = $dao->title;
2043 }
2044 }
2045
2046 return $customOptionGroup[$cacheKey];
2047 }
2048
2049 /**
2050 * Function to fix orphan groups
2051 *
2052 * @params int $customFieldId custom field id
2053 * @params int $optionGroupId option group id
2054 *
2055 * @access public
2056 *
2057 * @return void
2058 * @static
2059 */
2060 static function fixOptionGroups($customFieldId, $optionGroupId) {
2061 // check if option group belongs to any custom Field else delete
2062 // get the current option group
2063 $currentOptionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
2064 $customFieldId,
2065 'option_group_id'
2066 );
2067 // get the updated option group
2068 // if both are same return
2069 if ($currentOptionGroupId == $optionGroupId) {
2070 return;
2071 }
2072
2073 // check if option group is related to any other field
2074 self::checkOptionGroup($currentOptionGroupId);
2075 }
2076
2077 /**
2078 * Function to check if option group is related to more than one
2079 * custom field
2080 *
2081 * @params int $optionGroupId option group id
2082 *
2083 * @return
2084 * @static
2085 */
2086 static function checkOptionGroup($optionGroupId) {
2087 $query = "
2088 SELECT count(*)
2089 FROM civicrm_custom_field
2090 WHERE option_group_id = {$optionGroupId}";
2091
2092 $count = CRM_Core_DAO::singleValueQuery($query);
2093
2094 if ($count < 2) {
2095 //delete the option group
2096 CRM_Core_BAO_OptionGroup::del($optionGroupId);
2097 }
2098 }
2099
2100 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2101 $query = "
2102 SELECT default_value, html_type
2103 FROM civicrm_custom_field
2104 WHERE option_group_id = {$optionGroupId}
2105 AND default_value IS NOT NULL
2106 ORDER BY html_type";
2107
2108 $dao = CRM_Core_DAO::executeQuery($query);
2109 $defaultValue = NULL;
2110 $defaultHTMLType = NULL;
2111 while ($dao->fetch()) {
2112 if ($dao->html_type == $htmlType) {
2113 return $dao->default_value;
2114 }
2115 if ($defaultValue == NULL) {
2116 $defaultValue = $dao->default_value;
2117 $defaultHTMLType = $dao->html_type;
2118 }
2119 }
2120
2121 // some conversions are needed if either the old or new has a html type which has potential
2122 // multiple default values.
2123 if (($htmlType == 'CheckBox' || $htmlType == 'Multi-Select') &&
2124 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2125 ) {
2126 $defaultValue = CRM_Core_DAO::VALUE_SEPARATOR . $defaultValue . CRM_Core_DAO::VALUE_SEPARATOR;
2127 }
2128 elseif (($defaultHTMLType == 'CheckBox' || $defaultHTMLType == 'Multi-Select') &&
2129 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2130 ) {
2131 $defaultValue = substr($defaultValue, 1, -1);
2132 $values = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2133 substr($defaultValue, 1, -1)
2134 );
2135 $defaultValue = $values[0];
2136 }
2137
2138 return $defaultValue;
2139 }
2140
2141 static function postProcess(&$params,
2142 &$customFields,
2143 $entityID,
2144 $customFieldExtends,
2145 $inline = FALSE
2146 ) {
2147 $customData = array();
2148
2149 foreach ($params as $key => $value) {
2150 if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, TRUE)) {
2151
2152 // for autocomplete transfer hidden value instead of label
2153 if ($params[$key] && isset($params[$key . '_id'])) {
2154 $value = $params[$key . '_id'];
2155 }
2156
2157 // we need to append time with date
2158 if ($params[$key] && isset($params[$key . '_time'])) {
2159 $value .= ' ' . $params[$key . '_time'];
2160 }
2161
2162 CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0],
2163 $customData,
2164 $value,
2165 $customFieldExtends,
2166 $customFieldInfo[1],
2167 $entityID,
2168 $inline
2169 );
2170 }
2171 }
2172 return $customData;
2173 }
2174
2175 static function buildOption($field, &$options) {
2176 // Fixme - adding anything but options to the $options array is a bad idea
2177 // What if an option had the key 'attributes'?
2178 $options['attributes'] = array(
2179 'label' => $field['label'],
2180 'data_type' => $field['data_type'],
2181 'html_type' => $field['html_type'],
2182 );
2183
2184 $optionGroupID = NULL;
2185 if (($field['html_type'] == 'CheckBox' ||
2186 $field['html_type'] == 'Radio' ||
2187 $field['html_type'] == 'Select' ||
2188 $field['html_type'] == 'AdvMulti-Select' ||
2189 $field['html_type'] == 'Multi-Select' ||
2190 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2191 )) {
2192 if ($field['option_group_id']) {
2193 $optionGroupID = $field['option_group_id'];
2194 }
2195 elseif ($field['data_type'] != 'Boolean') {
2196 CRM_Core_Error::fatal();
2197 }
2198 }
2199
2200 // build the cache for custom values with options (label => value)
2201 if ($optionGroupID != NULL) {
2202 $query = "
2203 SELECT label, value
2204 FROM civicrm_option_value
2205 WHERE option_group_id = $optionGroupID
2206 ";
2207
2208 $dao = CRM_Core_DAO::executeQuery($query);
2209 while ($dao->fetch()) {
2210 if ($field['data_type'] == 'Int' || $field['data_type'] == 'Float') {
2211 $num = round($dao->value, 2);
2212 $options["$num"] = $dao->label;
2213 }
2214 else {
2215 $options[$dao->value] = $dao->label;
2216 }
2217 }
2218
2219 CRM_Utils_Hook::customFieldOptions($field['id'], $options);
2220 }
2221 }
2222
2223 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2224 $params = array(1 => array($fieldLabel, 'String'));
2225 if ($groupTitle) {
2226 $params[2] = array($groupTitle, 'String');
2227 $sql = "
2228 SELECT f.id
2229 FROM civicrm_custom_field f
2230 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2231 WHERE ( f.label = %1 OR f.name = %1 )
2232 AND ( g.title = %2 OR g.name = %2 )
2233 ";
2234 }
2235 else {
2236 $sql = "
2237 SELECT f.id
2238 FROM civicrm_custom_field f
2239 WHERE ( f.label = %1 OR f.name = %1 )
2240 ";
2241 }
2242
2243 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2244 if ($dao->fetch() &&
2245 $dao->N == 1
2246 ) {
2247 return $dao->id;
2248 }
2249 else {
2250 return NULL;
2251 }
2252 }
2253
2254 /**
2255 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2256 *
2257 */
2258 static function getNameFromID($ids) {
2259 if (is_array($ids)) {
2260 $ids = implode(',', $ids);
2261 }
2262 $sql = "
2263 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2264 FROM civicrm_custom_field f
2265 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2266 WHERE f.id IN ($ids)";
2267
2268
2269 $dao = CRM_Core_DAO::executeQuery($sql);
2270 $result = array();
2271 while ($dao->fetch()) {
2272 $result[$dao->id] = array(
2273 'field_name' => $dao->field_name,
2274 'field_label' => $dao->field_label,
2275 'group_name' => $dao->group_name,
2276 'group_title' => $dao->group_title,
2277 );
2278 }
2279 return $result;
2280 }
2281
2282 /**
2283 * Validate custom data.
2284 *
2285 * @param array $params custom data submitted.
2286 * ie array( 'custom_1' => 'validate me' );
2287 *
2288 * @return array $errors validation errors.
2289 * @static
2290 */
2291 static function validateCustomData($params) {
2292 $errors = array();
2293 if (!is_array($params) || empty($params)) {
2294 return $errors;
2295 }
2296
2297
2298 //pick up profile fields.
2299 $profileFields = array();
2300 $ufGroupId = CRM_Utils_Array::value('ufGroupId', $params);
2301 if ($ufGroupId) {
2302 $profileFields = CRM_Core_BAO_UFGroup::getFields($ufGroupId,
2303 FALSE,
2304 CRM_Core_Action::VIEW
2305 );
2306 }
2307
2308 //lets start w/ params.
2309 foreach ($params as $key => $value) {
2310 $customFieldID = self::getKeyID($key);
2311 if (!$customFieldID) {
2312 continue;
2313 }
2314
2315 //load the structural info for given field.
2316 $field = new CRM_Core_DAO_CustomField();
2317 $field->id = $customFieldID;
2318 if (!$field->find(TRUE)) {
2319 continue;
2320 }
2321 $dataType = $field->data_type;
2322
2323 $profileField = CRM_Utils_Array::value($key, $profileFields, array());
2324 $fieldTitle = CRM_Utils_Array::value('title', $profileField);
2325 $isRequired = CRM_Utils_Array::value('is_required', $profileField);
2326 if (!$fieldTitle) {
2327 $fieldTitle = $field->label;
2328 }
2329
2330 //no need to validate.
2331 if (CRM_Utils_System::isNull($value) && !$isRequired) {
2332 continue;
2333 }
2334
2335 //lets validate first for required field.
2336 if ($isRequired && CRM_Utils_System::isNull($value)) {
2337 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2338 continue;
2339 }
2340
2341 //now time to take care of custom field form rules.
2342 $ruleName = $errorMsg = NULL;
2343 switch ($dataType) {
2344 case 'Int':
2345 $ruleName = 'integer';
2346 $errorMsg = ts('%1 must be an integer (whole number).',
2347 array(1 => $fieldTitle)
2348 );
2349 break;
2350
2351 case 'Money':
2352 $ruleName = 'money';
2353 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2354 array(1 => $fieldTitle)
2355 );
2356 break;
2357
2358 case 'Float':
2359 $ruleName = 'numeric';
2360 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2361 array(1 => $fieldTitle)
2362 );
2363 break;
2364
2365 case 'Link':
2366 $ruleName = 'wikiURL';
2367 $errorMsg = ts('%1 must be valid Website.',
2368 array(1 => $fieldTitle)
2369 );
2370 break;
2371 }
2372
2373 if ($ruleName && !CRM_Utils_System::isNull($value)) {
2374 $valid = FALSE;
2375 $funName = "CRM_Utils_Rule::{$ruleName}";
2376 if (is_callable($funName)) {
2377 $valid = call_user_func($funName, $value);
2378 }
2379 if (!$valid) {
2380 $errors[$key] = $errorMsg;
2381 }
2382 }
2383 }
2384
2385 return $errors;
2386 }
2387
2388 static function isMultiRecordField($customId) {
2389 $isMultipleWithGid = FALSE;
2390 if (!is_numeric($customId)) {
2391 $customId = self::getKeyID($customId);
2392 }
2393 if (is_numeric($customId)) {
2394 $sql = "SELECT cg.id cgId
2395 FROM civicrm_custom_group cg
2396 INNER JOIN civicrm_custom_field cf
2397 ON cg.id = cf.custom_group_id
2398 WHERE cf.id = %1 AND cg.is_multiple = 1";
2399 $params[1] = array($customId, 'Integer');
2400 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2401 if ($dao->fetch()) {
2402 if ($dao->cgId) {
2403 $isMultipleWithGid = $dao->cgId;
2404 }
2405 }
2406 }
2407
2408 return $isMultipleWithGid;
2409 }
2410 }
2411