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