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