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