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