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