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