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