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