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