3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Class CRM_Report_Form
15 class CRM_Report_Form
extends CRM_Core_Form
{
17 * Variables smarty expects to have set.
19 * We ensure these are assigned (value = NULL) when Smarty is instantiated in
20 * order to avoid e-notices / having to use empty or isset in the template layer.
24 public $expectedSmartyVariables = ['pager', 'skip', 'sections', 'grandStat', 'chartEnabled'];
27 * Deprecated constant, Reports should be updated to use the getRowCount function.
29 const ROW_COUNT_LIMIT
= 50;
32 * Operator types - used for displaying filter elements
42 OP_MULTISELECT_SEPARATOR
= 66,
47 * The id of the report instance
54 * The Number of rows to display on screen
60 * The id of the report template
64 protected $_templateID;
72 protected $_noFields = FALSE;
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attributes as the value
80 protected $_columns = [];
83 * The set of filters in the report
87 protected $_filters = [];
90 * The set of optional columns in the report
94 public $_options = [];
97 * By default most reports hide contact id.
98 * Setting this to true makes it available
101 protected $_exposeContactID = TRUE;
104 * Set of statistic fields
108 protected $_statFields = [];
111 * Set of statistics data
115 protected $_statistics = [];
118 * List of fields not to be repeated during display
122 protected $_noRepeats = [];
125 * List of fields not to be displayed
129 protected $_noDisplay = [];
132 * Object type that a custom group extends
136 protected $_customGroupExtends = NULL;
137 protected $_customGroupExtendsJoin = [];
138 protected $_customGroupFilters = TRUE;
139 protected $_customGroupGroupBy = FALSE;
140 protected $_customGroupJoin = 'LEFT JOIN';
146 protected $_tagFilter = FALSE;
149 * specify entity table for tags filter
152 protected $_tagFilterTable = 'civicrm_contact';
155 * Build groups filter.
159 protected $_groupFilter = FALSE;
162 * Has the report been optimised for group filtering.
164 * The functionality for group filtering has been improved but not
165 * all reports have been adjusted to take care of it.
167 * This property exists to highlight the reports which are still using the
168 * slow method & allow group filtering to still work for them until they
171 * In order to protect extensions we have to default to TRUE - but I have
172 * separately marked every class with a groupFilter in the hope that will trigger
173 * people to fix them as they touch them.
176 * @see https://issues.civicrm.org/jira/browse/CRM-19170
178 protected $groupFilterNotOptimised = TRUE;
185 public $_navigation = [];
187 public $_drilldownReport = [];
190 * Array of tabs to display on report.
192 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
194 * $this->tabs['OrderBy'] = array(
195 * 'title' => ts('Sorting'),
196 * 'tpl' => 'OrderBy',
197 * 'div_label' => 'order-by',
202 protected $tabs = [];
205 * Should we add paging.
209 protected $addPaging = TRUE;
211 protected $isForceGroupBy = FALSE;
213 protected $groupConcatTested = FALSE;
216 * Are we in print mode. Can be set by another outputMode, ex: sendmail.
220 public $printOnly = FALSE;
223 * An attribute for checkbox/radio form field layout
227 protected $_fourColumnAttribute = [
228 '</td><td width="25%">',
229 '</td><td width="25%">',
230 '</td><td width="25%">',
234 protected $_force = 1;
236 protected $_params = NULL;
237 protected $_formValues = NULL;
238 protected $_instanceValues = NULL;
240 protected $_instanceForm = FALSE;
241 protected $_criteriaForm = FALSE;
243 protected $_instanceButtonName = NULL;
244 protected $_createNewButtonName = NULL;
245 protected $_groupButtonName = NULL;
246 protected $_chartButtonName = NULL;
247 protected $_csvSupported = TRUE;
248 protected $_add2groupSupported = TRUE;
249 protected $_groups = NULL;
250 protected $_grandFlag = FALSE;
251 protected $_rowsFound = NULL;
252 protected $_selectAliases = [];
253 protected $_rollup = NULL;
256 * Table containing list of contact IDs within the group filter.
260 protected $groupTempTable = '';
265 protected $_aliases = [];
268 * SQL where clause. May be altered by hook_civicrm_alterReportVar.
274 * SQL from clause. May be altered by hook_civicrm_alterReportVar.
283 protected $_limit = NULL;
286 * This can be set to specify a limit to the number of rows
287 * Since it is currently envisaged as part of the api usage it is only being applied
288 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
289 * of the code (see limit() fn.
293 protected $_limitValue = NULL;
296 * This can be set to specify row offset
297 * See notes on _limitValue
301 protected $_offsetValue = NULL;
306 protected $_sections = [];
308 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
311 * Whether to generate absolute URLs (ex: in report emails).
315 public $_absoluteUrl = FALSE;
318 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
322 protected $_storeResultSet = FALSE;
325 * When _storeResultSet Flag is set use this var to store result set in form of array
329 protected $_resultSet = [];
332 * To what frequency group-by a date column
336 protected $_groupByDateFreq = [
338 'YEARWEEK' => 'Week',
339 'QUARTER' => 'Quarter',
344 * Variables to hold the acl inner join and where clause
347 protected $_aclFrom = NULL;
348 protected $_aclWhere = NULL;
351 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
353 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
357 protected $_selectedTables = [];
360 * Array of DAO tables having columns included in WHERE or HAVING clause
364 protected $filteredTables;
367 * Output mode e.g 'print', 'csv', 'pdf'.
371 protected $_outputMode;
374 * Format of any chart in use.
376 * (it's unclear if this could be merged with outputMode at this stage)
382 public $_having = NULL;
383 public $_select = NULL;
384 public $_selectClauses = [];
385 public $_columnHeaders = [];
386 public $_orderBy = NULL;
387 public $_orderByFields = [];
388 public $_orderByArray = [];
390 * Array of clauses to group by.
394 protected $_groupByArray = [];
395 public $_groupBy = NULL;
396 public $_whereClauses = [];
397 public $_havingClauses = [];
400 * DashBoardRowCount Dashboard row count.
404 public $_dashBoardRowCount;
407 * Is this being called without a form controller (ie. the report is being render outside the normal form
408 * - e.g the api is retrieving the rows.
412 public $noController = FALSE;
415 * Variable to hold the currency alias.
419 protected $_currencyColumn = NULL;
424 protected $_interval;
429 protected $_sendmail;
442 * Report description.
446 public $_description;
449 * Is an address field selected.
452 * This was intended to determine if the address table should be joined in
453 * The isTableSelected function is now preferred for this purpose
455 protected $_addressField;
458 * Is an email field selected.
461 * This was intended to determine if the email table should be joined in
462 * The isTableSelected function is now preferred for this purpose
464 protected $_emailField;
467 * Is a phone field selected.
470 * This was intended to determine if the phone table should be joined in
471 * The isTableSelected function is now preferred for this purpose
473 protected $_phoneField;
476 * Create new report instance? (or update existing) on save.
480 protected $_createNew;
483 * When a grand total row has calculated the status we pop it off to here.
485 * This allows us to access it from the stats function and avoid recalculating.
489 protected $rollupRow = [];
492 * Database attributes - character set and collation.
496 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
499 * SQL being run in this report.
501 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
509 * An instruction not to add a Group By.
511 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
513 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
514 * such as in pivot charts when no row header is set
518 protected $noGroupBy = FALSE;
521 * SQL being run in this report as an array.
523 * The sql in the report is stored in this variable in order to be returned to api & test calls.
531 * Tables created for the report that need removal afterwards.
533 * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x']
536 protected $temporaryTables = [];
539 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
542 public $optimisedForOnlyFullGroupBy = TRUE;
545 * Determines which chart types are supported for this report
548 protected $_charts = [];
551 * Get the number of rows to show
554 public function getRowCount(): int {
555 return $this->_rowCount
;
559 * set the number of rows to show
560 * @param int $rowCount
562 public function setRowCount($rowCount): void
{
563 $this->_rowCount
= $rowCount;
569 public function __construct() {
570 parent
::__construct();
572 $this->setRowCount(\Civi
::settings()->get('default_pager_size'));
574 $this->addClass('crm-report-form');
576 if ($this->_tagFilter
) {
577 $this->buildTagFilter();
579 if ($this->_exposeContactID
) {
580 if (array_key_exists('civicrm_contact', $this->_columns
)) {
581 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = [
583 'title' => ts('Contact ID'),
589 if ($this->_groupFilter
) {
590 $this->buildGroupFilter();
593 // Get all custom groups
594 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
596 // Get the custom groupIds for which the user has VIEW permission
597 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
598 // and addCustomDataToColumns() will allow access to all custom groups.
599 $permCustomGroupIds = [];
600 if (!CRM_Core_Permission
::check('access all custom data')) {
601 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
602 // do not allow custom data for reports if user doesn't have
603 // permission to access custom data.
604 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
605 $this->_customGroupExtends
= [];
609 // merge custom data columns to _columns list, if any
610 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
612 // add / modify display columns, filters ..etc
613 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
615 //assign currencyColumn variable to tpl
616 $this->assign('currencyColumn', $this->_currencyColumn
);
620 * Shared pre-process function.
622 * If overriding preProcess function this should still be called.
626 public function preProcessCommon() {
627 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
628 // Ensure smarty variables are assigned here since this function is called from
629 // the report api and the main buildForm is not.
630 self
::$_template->ensureVariablesAreAssigned($this->expectedSmartyVariables
);
631 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
633 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
635 $this->assign('section', $this->_section
);
636 CRM_Core_Region
::instance('page-header')->add([
637 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
639 if (!$this->noController
) {
640 $this->setID($this->get('instanceId'));
643 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
645 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
649 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
650 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
651 if (!isset($_SERVER['QUERY_STRING'])) {
652 // in php 7.4 can do this with less lines with ??=
653 $_SERVER['QUERY_STRING'] = '';
655 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
659 $this->assign('instanceId', $this->_id
);
660 $params = ['id' => $this->_id
];
661 $this->_instanceValues
= [];
662 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
664 $this->_instanceValues
666 if (empty($this->_instanceValues
)) {
667 CRM_Core_Error
::statusBounce("Report could not be loaded.");
669 $this->_title
= $this->_instanceValues
['title'];
670 if (!empty($this->_instanceValues
['permission']) &&
671 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
672 CRM_Core_Permission
::check('administer Reports')
675 CRM_Utils_System
::permissionDenied();
676 CRM_Utils_System
::civiExit();
679 $formValues = $this->_instanceValues
['form_values'] ??
NULL;
681 $this->_formValues
= CRM_Utils_String
::unserialize($formValues);
684 $this->_formValues
= NULL;
687 $this->setOutputMode();
689 if ($this->_outputMode
== 'copy') {
690 $this->_createNew
= TRUE;
691 $this->_params
= $this->_formValues
;
692 $this->_params
['view_mode'] = 'criteria';
693 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', [
694 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
695 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
697 // Do not pass go. Do not collect another chance to re-run the same query.
698 CRM_Report_Form_Instance
::postProcess($this);
701 // lets always do a force if reset is found in the url.
702 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
703 // in the comment line above these 2.
704 if (!empty($_REQUEST['reset'])
705 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), ['save', 'criteria'])) {
710 $this->assign('mode', 'instance');
712 elseif (!$this->noController
) {
713 [$optionValueID, $optionValue] = CRM_Report_Utils_Report
::getValueIDFromUrl();
714 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
715 if (($instanceCount > 0) && $optionValueID) {
716 $this->assign('instanceUrl',
717 CRM_Utils_System
::url('civicrm/report/list',
718 "reset=1&ovid=$optionValueID"
722 if ($optionValueID) {
723 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
727 $this->assign('mode', 'template');
730 // lets display the Report Settings section
731 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
733 // Do not display Report Settings section if administer Reports permission is absent OR
734 // if report instance is reserved and administer reserved reports absent
735 if (!CRM_Core_Permission
::check('administer Reports') ||
736 (!empty($this->_instanceValues
['is_reserved']) &&
737 !CRM_Core_Permission
::check('administer reserved reports'))
739 $this->_instanceForm
= FALSE;
742 $this->assign('criteriaForm', FALSE);
743 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
744 if (CRM_Core_Permission
::check('administer Reports') ||
745 CRM_Core_Permission
::check('access Report Criteria')
747 if (empty($this->_instanceValues
['is_reserved']) ||
748 CRM_Core_Permission
::check('administer reserved reports')
750 $this->assign('criteriaForm', TRUE);
751 $this->_criteriaForm
= TRUE;
755 // Special permissions check for private instance if it's not the current contact instance
757 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
758 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
759 if (!CRM_Core_Permission
::check('access all private reports')) {
760 $this->_instanceForm
= FALSE;
761 $this->assign('criteriaForm', FALSE);
765 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
766 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
767 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
768 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
774 public function addBreadCrumb() {
778 'title' => ts('Report Templates'),
779 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
783 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
787 * Pre process function.
789 * Called prior to build form.
791 public function preProcess() {
792 $this->preProcessCommon();
795 $this->addBreadCrumb();
798 foreach ($this->_columns
as $tableName => $table) {
799 $this->setTableAlias($table, $tableName);
802 // higher preference to bao object
803 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
806 if (method_exists($daoOrBaoName, 'exportableFields')) {
807 $expFields = $daoOrBaoName::exportableFields();
810 $expFields = $daoOrBaoName::export();
814 $doNotCopy = ['required', 'default'];
816 $fieldGroups = ['fields', 'filters', 'group_bys', 'order_bys'];
817 foreach ($fieldGroups as $fieldGrp) {
818 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
819 foreach ($table[$fieldGrp] as $fieldName => $field) {
820 // $name is the field name used to reference the BAO/DAO export fields array
821 $name = $field['name'] ??
$fieldName;
823 // Sometimes the field name key in the BAO/DAO export fields array is
824 // different from the actual database field name.
825 // Unset $field['name'] so that actual database field name can be obtained
826 // from the BAO/DAO export fields array.
827 unset($field['name']);
829 if (array_key_exists($name, $expFields)) {
830 foreach ($doNotCopy as $dnc) {
831 // unset the values we don't want to be copied.
832 unset($expFields[$name][$dnc]);
835 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
838 foreach ($expFields[$name] as $property => $val) {
839 if (!array_key_exists($property, $field)) {
840 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
847 if (!empty($field['no_repeat'])) {
848 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
850 if (!empty($field['no_display'])) {
851 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
854 // set alias = table-name, unless already set
855 $alias = $field['alias'] ??
(
856 $this->_columns
[$tableName]['alias'] ??
$tableName
858 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
860 // set name = fieldName, unless already set
861 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
862 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
865 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
866 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
869 // set dbAlias = alias.name, unless already set
870 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
871 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
873 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
876 // a few auto fills for filters
877 if ($fieldGrp == 'filters') {
878 // fill operator types
879 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
880 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
881 case CRM_Utils_Type
::T_MONEY
:
882 case CRM_Utils_Type
::T_FLOAT
:
883 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
886 case CRM_Utils_Type
::T_INT
:
887 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
890 case CRM_Utils_Type
::T_DATE
:
891 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
894 case CRM_Utils_Type
::T_BOOLEAN
:
895 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
896 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
897 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
908 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
910 // with multiple options operator-type is generally multi-select
911 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
912 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
914 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
921 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
922 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
925 $this->_columns
[$tableName]['metadata'][$fieldName] = array_merge($this->_columns
[$tableName][$fieldGrp][$fieldName], $this->_columns
[$tableName]['metadata'][$fieldName]);
931 // copy filters to a separate handy variable
932 if (array_key_exists('filters', $table)) {
933 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
936 if (array_key_exists('group_bys', $table)) {
937 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
940 if (array_key_exists('fields', $table)) {
941 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
946 $this->setDefaultValues(FALSE);
949 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
950 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
951 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
952 CRM_Report_Utils_Get
::processChart($this->_defaults
);
955 $this->_formValues
= $this->_defaults
;
956 $this->postProcess();
961 * Set default values.
963 * @param bool $freeze
967 public function setDefaultValues($freeze = TRUE) {
970 // FIXME: generalizing form field naming conventions would reduce
971 // Lots of lines below.
972 foreach ($this->_columns
as $tableName => $table) {
973 if (array_key_exists('fields', $table)) {
974 foreach ($table['fields'] as $fieldName => $field) {
975 if (empty($field['no_display'])) {
976 if (!empty($field['required'])) {
978 $this->_defaults
['fields'][$fieldName] = 1;
981 // find element object, so that we could use quickform's freeze method
982 // for required elements
983 $obj = $this->getElementFromGroup("fields", $fieldName);
985 $freezeGroup[] = $obj;
989 elseif (isset($field['default'])) {
990 $this->_defaults
['fields'][$fieldName] = $field['default'];
996 if (array_key_exists('group_bys', $table)) {
997 foreach ($table['group_bys'] as $fieldName => $field) {
998 if (isset($field['default'])) {
999 if (!empty($field['frequency'])) {
1000 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
1002 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
1006 if (array_key_exists('filters', $table)) {
1007 foreach ($table['filters'] as $fieldName => $field) {
1008 if (isset($field['default'])) {
1009 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
1011 if (is_array($field['default'])) {
1012 $this->_defaults
["{$fieldName}_from"] = $field['default']['from'] ??
NULL;
1013 $this->_defaults
["{$fieldName}_to"] = $field['default']['to'] ??
NULL;
1014 $this->_defaults
["{$fieldName}_relative"] = 0;
1017 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
1021 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
1022 $this->_defaults
["{$fieldName}_min"] = $field['default']['min'] ??
NULL;
1023 $this->_defaults
["{$fieldName}_max"] = $field['default']['max'] ??
NULL;
1025 $this->_defaults
["{$fieldName}_value"] = $field['default'];
1028 //assign default value as "in" for multiselect
1029 //operator, To freeze the select element
1030 if (CRM_Utils_Array
::value('operatorType', $field) ==
1031 CRM_Report_Form
::OP_MULTISELECT
1033 $this->_defaults
["{$fieldName}_op"] = 'in';
1035 if (CRM_Utils_Array
::value('operatorType', $field) ==
1036 CRM_Report_Form
::OP_ENTITYREF
1038 $this->_defaults
["{$fieldName}_op"] = 'in';
1040 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
1041 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
1043 $this->_defaults
["{$fieldName}_op"] = 'mhas';
1045 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
1046 $this->_defaults
["{$fieldName}_op"] = $op;
1052 empty($this->_formValues
['order_bys']) &&
1053 (array_key_exists('order_bys', $table) &&
1054 is_array($table['order_bys']))
1056 if (!array_key_exists('order_bys', $this->_defaults
)) {
1057 $this->_defaults
['order_bys'] = [];
1059 foreach ($table['order_bys'] as $fieldName => $field) {
1060 if (!empty($field['default']) ||
!empty($field['default_order']) ||
1061 CRM_Utils_Array
::value('default_is_section', $field) ||
1062 !empty($field['default_weight'])
1065 'column' => $fieldName,
1066 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
1067 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
1070 if (!empty($field['default_weight'])) {
1071 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
1074 array_unshift($this->_defaults
['order_bys'], $order_by);
1080 foreach ($this->_options
as $fieldName => $field) {
1081 if (isset($field['default'])) {
1082 $this->_defaults
['options'][$fieldName] = $field['default'];
1087 if (!empty($this->_submitValues
)) {
1088 $this->preProcessOrderBy($this->_submitValues
);
1091 $this->preProcessOrderBy($this->_defaults
);
1094 // lets finish freezing task here itself
1095 if (!empty($freezeGroup)) {
1096 foreach ($freezeGroup as $elem) {
1101 if ($this->_formValues
) {
1102 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1105 if ($this->_instanceValues
) {
1106 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1109 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1111 return $this->_defaults
;
1115 * Get element from group.
1117 * @param string $group
1118 * @param string $grpFieldName
1120 * @return object|bool
1122 public function getElementFromGroup($group, $grpFieldName) {
1123 $eleObj = $this->getElement($group);
1124 foreach ($eleObj->_elements
as $index => $obj) {
1125 if ($grpFieldName == $obj->_attributes
['name']) {
1133 * Setter for $_params.
1135 * @param array $params
1137 public function setParams($params) {
1138 $this->_params
= $params;
1142 * Getter for $_params.
1144 * @return void|array $params
1146 public function getParams() {
1147 return $this->_params
;
1153 * @param int $instanceID
1155 public function setID($instanceID) {
1156 $this->_id
= $instanceID;
1164 public function getID() {
1169 * Getter for _outputMode
1171 * Note you can implement hook_civicrm_alterReportVar('actions', ...)
1172 * which indirectly allows setting _outputMode if the user chooses
1177 public function getOutputMode():string {
1178 return $this->_outputMode
;
1182 * Getter for report header form field value
1186 public function getReportHeader():string {
1187 return $this->_formValues
['report_header'] ??
'';
1191 * Getter for report footer form field value
1195 public function getReportFooter():string {
1196 return $this->_formValues
['report_footer'] ??
'';
1200 * Setter for $_force.
1202 * @param bool $isForce
1204 public function setForce($isForce) {
1205 $this->_force
= $isForce;
1209 * Setter for $_limitValue.
1211 * @param int $_limitValue
1213 public function setLimitValue($_limitValue) {
1214 $this->_limitValue
= $_limitValue;
1218 * Setter for $_offsetValue.
1220 * @param int $_offsetValue
1222 public function setOffsetValue($_offsetValue) {
1223 $this->_offsetValue
= $_offsetValue;
1227 * Setter for $addPaging.
1229 * @param bool $value
1231 public function setAddPaging($value) {
1232 $this->addPaging
= $value;
1236 * Getter for $_defaultValues.
1240 public function getDefaultValues() {
1241 return $this->_defaults
;
1245 * Remove any temporary tables.
1247 public function cleanUpTemporaryTables() {
1248 foreach ($this->temporaryTables
as $temporaryTable) {
1249 CRM_Core_DAO
::executeQuery('DROP ' . ($temporaryTable['temporary'] ?
'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']);
1254 * Create a temporary table.
1256 * This function creates a table AND adds the details to the developer tab & $this->>temporary tables.
1258 * @param string $identifier
1259 * This is the key that will be used for the table in the temporaryTables property.
1260 * @param string $sql
1261 * Sql select statement or column description (the latter requires the columns flag)
1262 * @param bool $isColumns
1263 * Is the sql describing columns to create (rather than using a select query).
1264 * @param bool $isMemory
1265 * Create a memory table rather than a normal INNODB table.
1269 public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) {
1270 $tempTable = CRM_Utils_SQL_TempTable
::build();
1272 $tempTable->setMemory();
1275 $tempTable->createWithColumns($sql);
1278 $tempTable->createWithQuery($sql);
1280 $name = $tempTable->getName();
1281 // Developers may force tables to be durable to assist in debugging so lets check.
1282 $isNotTrueTemporary = $tempTable->isDurable();
1283 $this->addToDeveloperTab($tempTable->getCreateSql());
1284 $this->temporaryTables
[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name];
1289 * Add columns to report.
1291 public function addColumns() {
1294 foreach ($this->_columns
as $tableName => $table) {
1295 if (array_key_exists('fields', $table)) {
1296 foreach ($table['fields'] as $fieldName => $field) {
1298 if (empty($field['no_display'])) {
1299 foreach (['table', 'field'] as $var) {
1300 if (!empty($
{$var}['grouping'])) {
1301 if (!is_array($
{$var}['grouping'])) {
1302 $tableName = $
{$var}['grouping'];
1305 $tableName = array_keys($
{$var}['grouping']);
1306 $tableName = $tableName[0];
1307 $groupTitle = array_values($
{$var}['grouping']);
1308 $groupTitle = $groupTitle[0];
1313 if (!$groupTitle && isset($table['group_title'])) {
1314 $groupTitle = $table['group_title'];
1315 // Having a group_title is secret code for being a custom group
1316 // which cryptically translates to needing an accordion.
1317 // here we make that explicit.
1318 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1321 $colGroups[$tableName]['fields'][$fieldName] = $field['title'] ??
NULL;
1322 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1323 $colGroups[$tableName]['group_title'] = $groupTitle;
1325 $options[$fieldName] = $field['title'] ??
NULL;
1331 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1332 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1334 if (!empty($colGroups)) {
1335 $this->tabs
['FieldSelection'] = [
1336 'title' => ts('Columns'),
1337 'tpl' => 'FieldSelection',
1338 'div_label' => 'col-groups',
1341 // Note this assignment is only really required in buildForm. It is being 'over-called'
1342 // to reduce risk of being missed due to overridden functions.
1343 $this->assign('tabs', $this->tabs
);
1346 $this->assign('colGroups', $colGroups);
1350 * Add filters to report.
1352 public function addFilters() {
1353 $filters = $filterGroups = [];
1355 foreach ($this->_filters
as $table => $attributes) {
1356 $groupingKey = $this->_columns
[$table]['grouping'] ??
'';
1357 $filterGroups[$groupingKey]['tables'][$table] = [];
1358 // If a prior table hasn't set group title then set it.
1359 if (empty($filterGroups[$groupingKey]['group_title'])) {
1360 $filterGroups[$groupingKey]['group_title'] = $this->_columns
[$table]['group_title'] ??
'';
1362 // The presence of 'group_title' is secret code for 'display in an accordion'
1363 // here we make this explicit.
1364 if (!isset($filterGroups[$groupingKey]['use_accordion_for_field_selection'])) {
1365 if (isset($this->_columns
[$table]['use_accordion_for_field_selection'])) {
1366 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = $this->_columns
[$table]['use_accordion_for_field_selection'];
1369 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = isset($this->_columns
[$table]['group_title']);
1373 foreach ($attributes as $fieldName => $field) {
1374 $filterGroups[$groupingKey]['tables'][$table][$fieldName] = $field;
1375 // Filters is deprecated in favour of filterGroups.
1376 $filters[$table][$fieldName] = $field;
1377 // get ready with option value pair
1378 // @ todo being able to specific options for a field (e.g a date field) in the field spec as an array rather than an override
1380 $operations = $this->getOperationPair(
1381 CRM_Utils_Array
::value('operatorType', $field),
1384 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1385 case CRM_Report_Form
::OP_MONTH
:
1386 if (!array_key_exists('options', $field) ||
1387 !is_array($field['options']) ||
empty($field['options'])
1389 // If there's no option list for this filter, define one.
1390 $field['options'] = CRM_Utils_Date
::getFullMonthNames();
1392 // Add this option list to this column _columns. This is
1393 // required so that filter statistics show properly.
1394 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1396 case CRM_Report_Form
::OP_MULTISELECT
:
1397 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1398 // assume a multi-select field
1399 if (!empty($field['options']) ||
1400 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1402 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1403 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1406 if (count($operations) <= 1) {
1409 if ($fieldName == 'state_province_id' ||
1410 $fieldName == 'county_id'
1412 $this->addChainSelect($fieldName . '_value', [
1419 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], [
1420 'style' => 'min-width:250px',
1421 'class' => 'crm-select2 huge',
1423 'placeholder' => ts('- select -'),
1429 case CRM_Report_Form
::OP_SELECT
:
1430 // assume a select field
1431 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1432 if (!empty($field['options'])) {
1433 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1437 case CRM_Report_Form
::OP_ENTITYREF
:
1438 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1439 $this->setEntityRefDefaults($field, $table);
1440 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1443 case CRM_Report_Form
::OP_DATE
:
1444 // build datetime fields
1445 $this->addDatePickerRange($fieldName, $field['title'], FALSE, FALSE, 'From', 'To', $operations, '_to', '_from');
1448 case CRM_Report_Form
::OP_DATETIME
:
1449 // build datetime fields
1450 $this->addDatePickerRange($fieldName, $field['title'], TRUE, FALSE, 'From', 'To', $operations, '_to', '_from');
1453 case CRM_Report_Form
::OP_INT
:
1454 case CRM_Report_Form
::OP_FLOAT
:
1455 // and a min value input box
1456 $this->add('text', "{$fieldName}_min", ts('Min'));
1457 // and a max value input box
1458 $this->add('text', "{$fieldName}_max", ts('Max'));
1460 // default type is string
1461 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1462 ['onchange' => "return showHideMaxMinVal( '$fieldName', this.value );"]
1464 // we need text box for value input
1465 $this->add('text', "{$fieldName}_value", NULL, ['class' => 'huge']);
1470 if (!empty($filterGroups)) {
1471 $this->tabs
['Filters'] = [
1472 'title' => ts('Filters'),
1474 'div_label' => 'set-filters',
1477 $this->assign('filterGroups', $filterGroups);
1478 // Filters is deprecated in favour of filterGroups.
1479 $this->assign('filters', $filters);
1483 * Function to assign the tabs to the template in the correct order.
1485 * We want the tabs to wind up in this order (if not overridden).
1493 protected function assignTabs() {
1501 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1502 $order = array_merge($order, $this->tabs
);
1503 $this->assign('tabs', $order);
1507 * The intent is to add a tab for developers to view the sql.
1509 * Currently using dpm.
1511 * @param string $sql
1513 public function addToDeveloperTab($sql) {
1514 if (!CRM_Core_Permission
::check('view report sql')) {
1517 $ignored_output_modes = ['pdf', 'csv', 'print'];
1518 if (in_array($this->_outputMode
, $ignored_output_modes)) {
1521 $this->tabs
['Developer'] = [
1522 'title' => ts('Developer'),
1523 'tpl' => 'Developer',
1524 'div_label' => 'set-developer',
1527 $this->assignTabs();
1528 $this->sqlFormattedArray
= [];
1529 $this->sqlArray
[] = $sql;
1530 foreach ($this->sqlArray
as $sql) {
1531 foreach (['LEFT JOIN'] as $term) {
1532 $sql = str_replace($term, '<br> ' . $term, ($sql ??
''));
1534 foreach (['FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';'] as $term) {
1535 $sql = str_replace($term, '<br><br>' . $term, ($sql ??
''));
1537 $this->sqlFormattedArray
[] = $sql;
1538 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1540 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL
::getSqlModes());
1545 * Add options defined in $this->_options to the report.
1547 public function addOptions() {
1548 if (!empty($this->_options
)) {
1549 // FIXME: For now lets build all elements as checkboxes.
1550 // Once we clear with the format we can build elements based on type
1552 foreach ($this->_options
as $fieldName => $field) {
1555 if ($field['type'] == 'select') {
1556 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1558 elseif ($field['type'] == 'checkbox') {
1559 $options[$field['title']] = $fieldName;
1560 $this->addCheckBox($fieldName, NULL,
1562 NULL, NULL, NULL, $this->_fourColumnAttribute
1567 if (!empty($this->_options
) &&
1569 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1571 $this->tabs
['ReportOptions'] = [
1572 'title' => ts('Display Options'),
1573 'tpl' => 'ReportOptions',
1574 'div_label' => 'other-options',
1577 $this->assign('otherOptions', $this->_options
);
1581 * Add chart options to the report.
1583 public function addChartOptions() {
1584 if (!empty($this->_charts
)) {
1585 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1586 $this->assign('charts', $this->_charts
);
1587 $this->addElement('xbutton', $this->_chartButtonName
, ts('View'), ['type' => 'submit']);
1592 * Add group by options to the report.
1594 public function addGroupBys() {
1595 $options = $freqElements = [];
1597 foreach ($this->_columns
as $tableName => $table) {
1598 if (array_key_exists('group_bys', $table)) {
1599 foreach ($table['group_bys'] as $fieldName => $field) {
1600 if (!empty($field) && empty($field['no_display'])) {
1601 $options[$field['title']] = $fieldName;
1602 if (!empty($field['frequency'])) {
1603 $freqElements[$field['title']] = $fieldName;
1609 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1610 NULL, NULL, NULL, $this->_fourColumnAttribute
1612 $this->assign('groupByElements', $options);
1613 if (!empty($options)) {
1614 $this->tabs
['GroupBy'] = [
1615 'title' => ts('Grouping'),
1617 'div_label' => 'group-by-elements',
1621 foreach ($freqElements as $name) {
1622 $this->addElement('select', "group_bys_freq[$name]",
1623 ts('Frequency'), $this->_groupByDateFreq
1629 * Add data for order by tab.
1631 public function addOrderBys() {
1633 foreach ($this->_columns
as $tableName => $table) {
1635 // Report developer may define any column to order by; include these as order-by options.
1636 if (array_key_exists('order_bys', $table)) {
1637 foreach ($table['order_bys'] as $fieldName => $field) {
1638 if (!empty($field)) {
1639 $options[$fieldName] = $field['title'];
1644 // Add searchable custom fields as order-by options, if so requested
1645 // (These are already indexed, so allowing to order on them is cheap.)
1647 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1648 array_key_exists('extends', $table) && !empty($table['extends'])
1650 foreach ($table['fields'] as $fieldName => $field) {
1651 if (empty($field['no_display'])) {
1652 $options[$fieldName] = $field['title'];
1660 $this->assign('orderByOptions', $options);
1661 if (!empty($options)) {
1662 $this->tabs
['OrderBy'] = [
1663 'title' => ts('Sorting'),
1665 'div_label' => 'order-by-elements',
1669 if (!empty($options)) {
1671 '-' => ts(' - none - '),
1673 for ($i = 1; $i <= 5; $i++
) {
1674 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1675 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
1676 'ASC' => ts('Ascending'),
1677 'DESC' => ts('Descending'),
1679 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, ['id' => "order_by_section_$i"]);
1680 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, ['id' => "order_by_pagebreak_$i"]);
1686 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1688 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1689 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1692 public function buildInstanceAndButtons() {
1693 CRM_Report_Form_Instance
::buildForm($this);
1694 $this->_actionButtonName
= $this->getButtonName('submit');
1695 $this->addTaskMenu($this->getActions($this->_id
));
1697 $this->assign('instanceForm', $this->_instanceForm
);
1699 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1700 $permission = CRM_Core_Permission
::getPermission();
1701 if ($this->_instanceForm
&& $permission == CRM_Core_Permission
::EDIT
&&
1702 $this->_add2groupSupported
1704 $this->addElement('select', 'groups', ts('Group'),
1705 ['' => ts('Add Contacts to Group')] +
1706 CRM_Core_PseudoConstant
::nestedGroup(),
1707 ['class' => 'crm-select2 crm-action-menu fa-plus huge']
1709 $this->assign('group', TRUE);
1712 $this->addElement('xbutton', $this->_groupButtonName
, '', [
1714 'style' => 'display: none;',
1717 $this->addChartOptions();
1718 $showResultsLabel = $this->getResultsLabel();
1722 'name' => $showResultsLabel,
1723 'isDefault' => TRUE,
1729 * Has this form been submitted already?
1733 public function resultsDisplayed() {
1734 $buttonName = $this->controller
->getButtonName();
1735 return ($buttonName ||
$this->_outputMode
);
1739 * Get the actions for this report instance.
1741 * @param int $instanceId
1745 protected function getActions($instanceId) {
1746 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1747 if (empty($instanceId)) {
1748 $actions['report_instance.save'] = [
1749 'title' => ts('Create Report'),
1751 'is_confirm' => TRUE,
1752 'confirm_title' => ts('Create Report'),
1753 'confirm_refresh_fields' => json_encode([
1754 'title' => ['selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''],
1755 'description' => ['selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''],
1759 unset($actions['report_instance.delete']);
1762 if (!$this->_csvSupported
) {
1763 unset($actions['report_instance.csv']);
1766 CRM_Utils_Hook
::alterReportVar('actions', $actions, $this);
1772 * Main build form function.
1774 public function buildQuickForm() {
1775 $this->addColumns();
1777 $this->addFilters();
1779 $this->addOptions();
1781 $this->addGroupBys();
1783 $this->addOrderBys();
1785 $this->buildInstanceAndButtons();
1787 // Add form rule for report.
1792 $this->addFormRule([get_class($this), 'formRule'], $this);
1794 $this->assignTabs();
1798 * A form rule function for custom data.
1800 * The rule ensures that fields selected in group_by if any) should only be the ones
1801 * present in display/select fields criteria;
1802 * note: works if and only if any custom field selected in group_by.
1804 * @param array $fields
1805 * @param array $ignoreFields
1809 public function customDataFormRule($fields, $ignoreFields = []) {
1811 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1812 !empty($fields['group_bys'])
1814 foreach ($this->_columns
as $tableName => $table) {
1815 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1816 substr($tableName, 0, 12) == 'custom_value') &&
1817 !empty($this->_columns
[$tableName]['fields'])
1819 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1820 if (array_key_exists($fieldName, $fields['group_bys']) &&
1821 !array_key_exists($fieldName, $fields['fields'])
1823 $errors['fields'] = ts("Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.");
1825 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1826 foreach ($fields['fields'] as $fld => $val) {
1827 if (!array_key_exists($fld, $fields['group_bys']) &&
1828 !in_array($fld, $ignoreFields)
1830 $errors['fields'] = ts("Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.");
1842 * Get operators to display on form.
1844 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1846 * @param int|string $type
1847 * @param string $fieldName
1851 public function getOperationPair($type = "string", $fieldName = NULL) {
1852 // FIXME: At some point we should move these key-val pairs
1853 // to option_group and option_value table.
1855 case CRM_Report_Form
::OP_INT
:
1856 case CRM_Report_Form
::OP_FLOAT
:
1859 'lte' => ts('Is less than or equal to'),
1860 'gte' => ts('Is greater than or equal to'),
1861 'bw' => ts('Is between'),
1862 'eq' => ts('Is equal to'),
1863 'lt' => ts('Is less than'),
1864 'gt' => ts('Is greater than'),
1865 'neq' => ts('Is not equal to'),
1866 'nbw' => ts('Is not between'),
1867 'nll' => ts('Is empty (Null)'),
1868 'nnll' => ts('Is not empty (Null)'),
1872 case CRM_Report_Form
::OP_SELECT
:
1874 'eq' => ts('Is equal to'),
1878 case CRM_Report_Form
::OP_MONTH
:
1879 case CRM_Report_Form
::OP_MULTISELECT
:
1880 case CRM_Report_Form
::OP_ENTITYREF
:
1883 'in' => ts('Is one of'),
1884 'notin' => ts('Is not one of'),
1885 'nll' => ts('Is empty (Null)'),
1886 'nnll' => ts('Is not empty (Null)'),
1890 case CRM_Report_Form
::OP_DATE
:
1893 'nll' => ts('Is empty (Null)'),
1894 'nnll' => ts('Is not empty (Null)'),
1898 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1899 // use this operator for the values, concatenated with separator. For e.g if
1900 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1902 'mhas' => ts('Is one of'),
1903 'mnot' => ts('Is not one of'),
1904 'nll' => ts('Is empty (Null)'),
1905 'nnll' => ts('Is not empty (Null)'),
1912 'has' => ts('Contains'),
1913 'sw' => ts('Starts with'),
1914 'ew' => ts('Ends with'),
1915 'nhas' => ts('Does not contain'),
1916 'eq' => ts('Is equal to'),
1917 'neq' => ts('Is not equal to'),
1918 'nll' => ts('Is empty (Null)'),
1919 'nnll' => ts('Is not empty (Null)'),
1926 * Build the tag filter field to display on the filters tab.
1928 public function buildTagFilter() {
1929 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1930 if (!empty($contactTags)) {
1931 $this->_columns
['civicrm_tag'] = [
1932 'dao' => 'CRM_Core_DAO_Tag',
1936 'title' => ts('Tag'),
1937 'type' => CRM_Utils_Type
::T_INT
,
1939 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1940 'options' => $contactTags,
1948 * Adds group filters to _columns (called from _Construct).
1950 public function buildGroupFilter() {
1951 $this->_columns
['civicrm_group']['filters'] = [
1953 'name' => 'group_id',
1954 'title' => ts('Group'),
1955 'type' => CRM_Utils_Type
::T_INT
,
1956 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1958 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1961 if (empty($this->_columns
['civicrm_group']['dao'])) {
1962 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1964 if (empty($this->_columns
['civicrm_group']['alias'])) {
1965 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1970 * Get SQL operator from form text version.
1972 * @param string $operator
1976 public function getSQLOperator($operator = "like") {
1977 switch ($operator) {
2010 return 'IS NOT NULL';
2019 * Generate where clause.
2021 * This can be overridden in reports for special treatment of a field
2023 * @param array $field Field specifications
2024 * @param string $op Query operator (not an exact match to sql)
2025 * @param mixed $value
2029 * @return null|string
2031 public function whereClause(&$field, $op, $value, $min, $max) {
2033 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
2035 // CRM-18010: Ensure type of each report filters
2037 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
2044 if (($min !== NULL && strlen($min) > 0) ||
2045 ($max !== NULL && strlen($max) > 0)
2049 $min = CRM_Utils_Type
::escape($min, $type);
2051 $clauses[] = "( {$field['dbAlias']} >= $min )";
2054 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
2058 $max = CRM_Utils_Type
::escape($max, $type);
2060 $clauses[] = "( {$field['dbAlias']} <= $max )";
2063 $clauses[] = "( {$field['dbAlias']} > $max )";
2067 if (!empty($clauses)) {
2069 $clause = implode(' AND ', $clauses);
2072 $clause = '(' . implode('OR', $clauses) . ')';
2080 if ($value !== NULL && strlen($value) > 0) {
2081 $value = CRM_Utils_Type
::escape($value, $type);
2082 if (strpos($value, '%') === FALSE) {
2083 $value = "'%{$value}%'";
2086 $value = "'{$value}'";
2088 $sqlOP = $this->getSQLOperator($op);
2089 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2095 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
2096 $value = explode(',', $value);
2098 if ($value !== NULL && is_array($value) && count($value) > 0) {
2099 $sqlOP = $this->getSQLOperator($op);
2100 if (CRM_Utils_Array
::value('type', $field) ==
2101 CRM_Utils_Type
::T_STRING
2103 //cycle through selections and escape values
2104 foreach ($value as $key => $selection) {
2105 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
2108 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
2112 // for numerical values
2113 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
2116 if ($op == 'notin') {
2117 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
2120 $clause = "( " . $clause . " )";
2127 // multiple has or multiple not
2128 if ($value !== NULL && count($value) > 0) {
2129 $value = CRM_Utils_Type
::escapeAll($value, $type);
2130 $operator = $op == 'mnot' ?
'NOT' : '';
2131 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2132 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2138 if ($value !== NULL && strlen($value) > 0) {
2139 $value = CRM_Utils_Type
::escape($value, $type);
2140 if (strpos($value, '%') === FALSE) {
2142 $value = "'{$value}%'";
2145 $value = "'%{$value}'";
2149 $value = "'{$value}'";
2151 $sqlOP = $this->getSQLOperator($op);
2152 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2157 if ($type == 'String') {
2158 $sqlOP = $this->getSQLOperator($op);
2159 $clause = "( {$field['dbAlias']} $sqlOP OR {$field['dbAlias']} = '' )";
2162 $sqlOP = $this->getSQLOperator($op);
2163 $clause = "( {$field['dbAlias']} $sqlOP )";
2168 if ($type == 'String') {
2169 $sqlOP = $this->getSQLOperator($op);
2170 $clause = "( {$field['dbAlias']} $sqlOP AND {$field['dbAlias']} <> '' )";
2173 $sqlOP = $this->getSQLOperator($op);
2174 $clause = "( {$field['dbAlias']} $sqlOP )";
2181 //CRM-18457: some custom field passes value in array format against binary operator
2182 if (is_array($value) && count($value)) {
2187 if ($value !== NULL && $value !== '') {
2188 if (isset($field['clause'])) {
2189 // FIXME: we not doing escape here. Better solution is to use two
2190 // different types - data-type and filter-type
2191 $clause = $field['clause'];
2193 elseif (!is_array($value)) {
2194 $value = CRM_Utils_Type
::escape($value, $type);
2195 $sqlOP = $this->getSQLOperator($op);
2196 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
2197 $value = "'{$value}'";
2199 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2205 //dev/core/544 Add report support for multiple contact subTypes
2206 if ($field['name'] == 'contact_sub_type' && $clause) {
2207 $clause = $this->whereSubtypeClause($field, $value, $op);
2209 if (!empty($field['group']) && $clause) {
2210 $clause = $this->whereGroupClause($field, $value, $op);
2212 elseif (!empty($field['tag']) && $clause) {
2213 // not using left join in query because if any contact
2214 // belongs to more than one tag, results duplicate
2216 $clause = $this->whereTagClause($field, $value, $op);
2218 elseif (!empty($field['membership_org']) && $clause) {
2219 $clause = $this->whereMembershipOrgClause($value, $op);
2221 elseif (!empty($field['membership_type']) && $clause) {
2222 $clause = $this->whereMembershipTypeClause($value, $op);
2228 * Get SQL where clause for contact subtypes
2229 * @param array $field Field specifications
2230 * @param mixed $value
2231 * @param string $op SQL Operator
2235 public function whereSubtypeClause($field, $value, $op) {
2236 // Get the correct SQL operator.
2241 $clauseSeparator = ' AND ';
2247 $clauseSeparator = ' OR ';
2250 $sqlOp = $this->getSQLOperator($op);
2251 if ($sqlOp == 'IS NULL' ||
$sqlOp == 'IS NOT NULL') {
2252 $clause = "{$field['dbAlias']} $sqlOp";
2256 foreach ($value as $item) {
2257 $subclauses[] = "( {$field['dbAlias']} $sqlOp '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $item . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' )";
2259 $clause = implode($clauseSeparator, $subclauses);
2261 $clause = "( $clause )";
2263 $clause = "( ( {$field['dbAlias']} IS NULL ) OR $clause )";
2269 * Get SQL where clause for a date field.
2271 * @param string $fieldName
2272 * @param string $relative
2273 * @param string $from
2275 * @param string $type
2276 * @param string $fromTime
2277 * @param string $toTime
2279 * @return null|string
2281 public function dateClause(
2283 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2286 if (array_key_exists($relative, $this->getOperationPair(CRM_Report_Form
::OP_DATE
))) {
2287 $sqlOP = $this->getSQLOperator($relative);
2288 return "( {$fieldName} {$sqlOP} )";
2290 if (strlen($to ??
'') === 10) {
2291 // If we just have the date we assume the end of that day.
2296 [$from, $to] = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2300 $clauses[] = "( {$fieldName} >= " . date('YmdHis', strtotime($from)) . ')';
2304 $clauses[] = "( {$fieldName} <= " . date('YmdHis', strtotime($to)) . ')';
2306 if (!empty($clauses)) {
2307 return implode(' AND ', $clauses);
2314 * Get values for from and to for date ranges.
2318 * @param bool $relative
2319 * @param string $from
2321 * @param string $fromTime
2322 * @param string $toTime
2326 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2327 if (!empty($fromTime) ||
!empty($toTime)) {
2328 throw new CRM_Core_Exception('Report template needs to be updated as getFromTo no longer supports fromTime or ToTime Parameters');
2330 return CRM_Utils_Date
::getFromTo($relative, $from, $to);
2334 * Alter display of rows.
2336 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2337 * such as rendering contacts as links.
2339 * @param array $rows
2340 * Rows generated by SQL, with an array for each row.
2342 public function alterDisplay(&$rows) {
2346 * Alter the way in which custom data fields are displayed.
2348 * @param array $rows
2350 public function alterCustomDataDisplay(&$rows) {
2351 // custom code to alter rows having custom values
2352 if (empty($this->_customGroupExtends
)) {
2357 $customFieldIds = [];
2358 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2359 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2360 $customFieldIds[$fieldAlias] = $fieldId;
2363 if (empty($customFieldIds)) {
2367 // skip for type date and ContactReference since date format is already handled
2369 SELECT cg.table_name, cf.id
2370 FROM civicrm_custom_field cf
2371 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2372 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2373 cg.is_active = 1 AND
2374 cf.is_active = 1 AND
2375 cf.is_searchable = 1 AND
2376 cf.data_type NOT IN ('ContactReference', 'Date') AND
2377 cf.id IN (" . implode(",", $customFieldIds) . ")";
2379 $dao = CRM_Core_DAO
::executeQuery($query);
2380 while ($dao->fetch()) {
2381 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2384 $entryFound = FALSE;
2385 foreach ($rows as $rowNum => $row) {
2386 foreach ($row as $tableCol => $val) {
2387 if (array_key_exists($tableCol, $customFields)) {
2388 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2393 // skip looking further in rows, if first row itself doesn't
2394 // have the column we need
2402 * Remove duplicate rows.
2404 * @param array $rows
2406 public function removeDuplicates(&$rows) {
2407 if (empty($this->_noRepeats
)) {
2412 foreach ($rows as $key => $list) {
2413 foreach ($list as $colName => $colVal) {
2414 if (array_key_exists($colName, $checkList) &&
2415 $checkList[$colName] == $colVal
2417 $rows[$key][$colName] = "";
2419 if (in_array($colName, $this->_noRepeats
)) {
2420 $checkList[$colName] = $colVal;
2427 * Fix subtotal display.
2430 * @param array $fields
2431 * @param bool $subtotal
2433 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2434 foreach ($row as $colName => $colVal) {
2435 if (in_array($colName, $fields)) {
2437 elseif (isset($this->_columnHeaders
[$colName])) {
2439 $row[$colName] = 'Subtotal';
2443 unset($row[$colName]);
2450 * Calculate grant total.
2452 * @param array $rows
2456 public function grandTotal(&$rows) {
2457 if (!$this->_rollup ||
count($rows) == 1) {
2461 $this->moveSummaryColumnsToTheRightHandSide();
2463 if ($this->_limit
&& count($rows) >= $this->getRowCount()) {
2467 $this->rollupRow
= array_pop($rows);
2469 foreach ($this->_columnHeaders
as $fld => $val) {
2470 if (!in_array($fld, $this->_statFields
)) {
2471 if (!$this->_grandFlag
) {
2472 $this->rollupRow
[$fld] = ts('Grand Total');
2473 $this->_grandFlag
= TRUE;
2476 $this->rollupRow
[$fld] = "";
2481 $this->assign('grandStat', $this->rollupRow
);
2486 * Format display output.
2488 * @param array $rows
2489 * @param bool $pager
2491 public function formatDisplay(&$rows, $pager = TRUE) {
2492 // set pager based on if any limit was applied in the query.
2496 $chartEnabled = !empty($this->_params
['charts']) && !empty($rows);
2497 $this->assign('chartEnabled', $chartEnabled);
2498 // allow building charts if any
2499 if ($chartEnabled) {
2500 $this->buildChart($rows);
2501 $this->_chartId
= "{$this->_params['charts']}_" .
2502 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2503 CRM_Core_Config
::singleton()->userSystem
->getSessionId();
2504 $this->assign('chartId', $this->_chartId
);
2507 // unset columns not to be displayed.
2508 foreach ($this->_columnHeaders
as $key => $value) {
2509 if (!empty($value['no_display'])) {
2510 unset($this->_columnHeaders
[$key]);
2513 foreach (['colspan', 'type'] as $expectedKey) {
2514 if (!isset($this->_columnHeaders
[$key][$expectedKey])) {
2515 // Ensure it is set to prevent smarty notices.
2516 $this->_columnHeaders
[$key][$expectedKey] = FALSE;
2522 // unset columns not to be displayed.
2523 if (!empty($rows)) {
2524 foreach ($this->_noDisplay
as $noDisplayField) {
2525 foreach ($rows as $rowNum => $row) {
2526 unset($this->_columnHeaders
[$noDisplayField]);
2527 $expectedKeys = ['class'];
2528 foreach ($expectedKeys as $expectedKey) {
2529 if (!array_key_exists($expectedKey, $row)) {
2530 $rows[$rowNum][$expectedKey] = NULL;
2537 // Find alter display functions.
2538 $firstRow = reset($rows);
2540 $selectedFields = array_keys($firstRow);
2541 $alterFunctions = $alterMap = $alterSpecs = [];
2542 foreach ($this->_columns
as $tableName => $table) {
2543 if (array_key_exists('metadata', $table)) {
2544 foreach ($table['metadata'] as $field => $specs) {
2545 if (in_array($tableName . '_' . $field, $selectedFields)) {
2546 if (array_key_exists('alter_display', $specs)) {
2547 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2548 $alterMap[$tableName . '_' . $field] = $field;
2549 $alterSpecs[$tableName . '_' . $field] = NULL;
2551 // Add any alters that can be intuited from the field specs.
2552 // So far only boolean but a lot more could be.
2553 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2554 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2555 $alterMap[$tableName . '_' . $field] = $field;
2556 $alterSpecs[$tableName . '_' . $field] = NULL;
2563 // Run the alter display functions
2564 foreach ($rows as $index => & $row) {
2565 foreach ($row as $selectedField => $value) {
2566 if (array_key_exists($selectedField, $alterFunctions) && isset($value)) {
2567 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2573 // use this method for formatting rows for display purpose.
2574 $this->alterDisplay($rows);
2575 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2577 // build array of section totals
2578 $this->sectionTotals();
2580 // process grand-total row
2581 $this->grandTotal($rows);
2583 // use this method for formatting custom rows for display purpose.
2584 $this->alterCustomDataDisplay($rows);
2590 * @param $selectedfield
2591 * @param $criteriaFieldName
2595 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2596 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2597 $row[$selectedfield . '_link'] = $url;
2598 $row[$selectedfield . '_hover'] = ts("%1 for this state.", [
2602 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2603 if (!is_array($states)) {
2611 * @param $selectedField
2612 * @param $criteriaFieldName
2616 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2617 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2618 $row[$selectedField . '_link'] = $url;
2619 $row[$selectedField . '_hover'] = ts("%1 for this country.", [
2622 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2623 if (!is_array($countries)) {
2631 * @param $selectedfield
2632 * @param $criteriaFieldName
2636 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2637 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2638 $row[$selectedfield . '_link'] = $url;
2639 $row[$selectedfield . '_hover'] = ts("%1 for this county.", [
2642 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2643 if (!is_array($counties)) {
2651 * @param $selectedfield
2652 * @param $criteriaFieldName
2656 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2657 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value);
2667 protected function alterContactID($value, &$row, $fieldname) {
2668 $nameField = substr($fieldname, 0, -2) . 'name';
2669 static $first = TRUE;
2670 static $viewContactList = FALSE;
2672 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2675 if (!$viewContactList) {
2678 if (array_key_exists($nameField, $row)) {
2679 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2682 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2694 protected function alterCommunicationtMethod($value, &$row, $fieldname) {
2695 $communicationMethods = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
2697 // Explode padded values.
2698 $values = CRM_utils_array
::explodePadded($value);
2699 // Flip values, compute intersection with $communicationMethods, and implode with commas.
2700 $value = implode(', ', array_intersect_key($communicationMethods, array_flip($values)));
2709 protected function alterBoolean($value) {
2710 $options = [0 => '', 1 => ts('Yes')];
2711 if (isset($options[$value])) {
2712 return $options[$value];
2720 * @param array $rows
2722 public function buildChart(&$rows) {
2723 // override this method for building charts.
2726 // select() method below has been added recently (v3.3), and many of the report templates might
2727 // still be having their own select() method. We should fix them as and when encountered and move
2728 // towards generalizing the select() method below.
2731 * Generate the SELECT clause and set class variable $_select.
2733 public function select() {
2734 $select = $this->_selectAliases
= [];
2735 $this->storeGroupByArray();
2737 foreach ($this->_columns
as $tableName => $table) {
2738 if (array_key_exists('fields', $table)) {
2739 foreach ($table['fields'] as $fieldName => $field) {
2740 if ($tableName == 'civicrm_address') {
2741 // deprecated, use $this->isTableSelected.
2742 $this->_addressField
= TRUE;
2744 if ($tableName == 'civicrm_email') {
2745 $this->_emailField
= TRUE;
2747 if ($tableName == 'civicrm_phone') {
2748 $this->_phoneField
= TRUE;
2751 if (!empty($field['required']) ||
2752 !empty($this->_params
['fields'][$fieldName])
2755 // 1. In many cases we want select clause to be built in slightly different way
2756 // for a particular field of a particular type.
2757 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2759 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2760 if ($selectClause) {
2761 $select[] = $selectClause;
2765 // include statistics columns only if set
2766 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2767 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2771 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2772 if ($selectClause) {
2773 $select[] = $selectClause;
2776 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2783 // select for group bys
2784 if (array_key_exists('group_bys', $table)) {
2785 foreach ($table['group_bys'] as $fieldName => $field) {
2787 if ($tableName == 'civicrm_address') {
2788 $this->_addressField
= TRUE;
2790 if ($tableName == 'civicrm_email') {
2791 $this->_emailField
= TRUE;
2793 if ($tableName == 'civicrm_phone') {
2794 $this->_phoneField
= TRUE;
2796 // 1. In many cases we want select clause to be built in slightly different way
2797 // for a particular field of a particular type.
2798 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2800 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2801 if ($selectClause) {
2802 $select[] = $selectClause;
2806 if (!empty($this->_params
['group_bys']) &&
2807 !empty($this->_params
['group_bys'][$fieldName]) &&
2808 !empty($this->_params
['group_bys_freq'])
2810 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2812 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2813 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2814 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2815 $field['title'] = 'Week';
2819 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2820 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2821 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2822 $field['title'] = 'Year';
2826 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2827 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2828 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2829 $field['title'] = 'Month';
2833 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2834 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2835 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2836 $field['title'] = 'Quarter';
2839 // for graphs and charts -
2840 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2841 $this->_interval
= $field['title'];
2842 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2843 = $field['title'] . ' Beginning';
2844 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2845 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2847 // just to make sure these values are transferred to rows.
2848 // since we 'll need them for calculation purpose,
2849 // e.g making subtotals look nicer or graphs
2850 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
2851 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
2858 if (empty($select)) {
2859 // CRM-21412 Do not give fatal error on report when no fields selected
2863 $this->_selectClauses
= $select;
2864 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2868 * Build select clause for a single field.
2870 * @param string $tableName
2871 * @param string $tableKey
2872 * @param string $fieldName
2873 * @param array $field
2877 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2878 if (!empty($field['pseudofield'])) {
2879 $alias = "{$tableName}_{$fieldName}";
2880 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
2881 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
2882 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = $field['dbAlias'] ??
NULL;
2883 $this->_selectAliases
[] = $alias;
2884 return ' 1 as ' . $alias;
2890 * Build where clause.
2892 public function where() {
2893 $this->storeWhereHavingClauseArray();
2895 if (empty($this->_whereClauses
)) {
2896 $this->_where
= "WHERE ( 1 ) ";
2897 $this->_having
= "";
2900 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2903 if ($this->_aclWhere
) {
2904 $this->_where
.= " AND {$this->_aclWhere} ";
2907 if (!empty($this->_havingClauses
)) {
2908 // use this clause to construct group by clause.
2909 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2914 * Store Where clauses into an array.
2916 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2917 * temp table that may not be part of the final where clause or added
2918 * in other functions
2920 public function storeWhereHavingClauseArray() {
2921 foreach ($this->_columns
as $tableName => $table) {
2922 if (array_key_exists('filters', $table)) {
2923 foreach ($table['filters'] as $fieldName => $field) {
2924 // respect pseudofield to filter spec so fields can be marked as
2925 // not to be handled here
2926 if (!empty($field['pseudofield'])) {
2929 $clause = $this->generateFilterClause($field, $fieldName);
2931 if (!empty($clause)) {
2932 if (!empty($field['having'])) {
2933 $this->_havingClauses
[] = $clause;
2936 $this->_whereClauses
[] = $clause;
2948 public function processReportMode() {
2949 $this->setOutputMode();
2952 = CRM_Utils_Request
::retrieve(
2955 CRM_Core_DAO
::$_nullObject
2958 if ($this->_sendmail
&& !$this->_outputMode
) {
2959 // If we're here from the mail_report job, then the default there gets
2960 // set to pdf before we get here, but if we're somehow here and sending
2961 // by email and don't have a format set, then use print.
2962 // @todo Is this on purpose - why would they be different defaults?
2963 $this->_outputMode
= 'print';
2966 // _outputMode means multiple things and can cover export to file formats,
2967 // like csv, or actions with no output, like save. So this will only set
2968 // a handler if it's one of the former. But it's also possible we have a
2969 // really interesting handler out there. But the point is we don't need to
2970 // know, just to know that a handler doesn't always get set by this call.
2971 $this->setOutputHandler();
2973 if (!empty($this->outputHandler
)) {
2974 if ($this->_sendmail
) {
2975 // If we're sending by email these are the only options that make
2977 $this->printOnly
= TRUE;
2978 $this->addPaging
= FALSE;
2979 $this->_absoluteUrl
= TRUE;
2982 // otherwise ask the handler
2983 $this->printOnly
= $this->outputHandler
->isPrintOnly();
2984 $this->addPaging
= $this->outputHandler
->isAddPaging();
2985 $this->_absoluteUrl
= $this->outputHandler
->isAbsoluteUrl();
2988 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2989 $this->_createNew
= TRUE;
2992 $this->assign('outputMode', $this->_outputMode
);
2993 $this->assign('printOnly', $this->printOnly
);
2994 // Get today's date to include in printed reports
2995 if ($this->printOnly
) {
2996 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2997 $this->assign('reportDate', $reportDate);
3002 * Post Processing function for Form.
3004 * postProcessCommon should be used to set other variables from input as the api accesses that function.
3005 * This function is not accessed when the api calls the report.
3007 public function beginPostProcess() {
3008 $this->setParams($this->controller
->exportValues($this->_name
));
3009 if (empty($this->_params
) &&
3012 $this->setParams($this->_formValues
);
3015 // hack to fix params when submitted from dashboard, CRM-8532
3016 // fields array is missing because form building etc is skipped
3017 // in dashboard mode for report
3018 //@todo - this could be done in the dashboard no we have a setter
3019 if (empty($this->_params
['fields']) && !$this->_noFields
3020 && empty($this->_params
['task'])
3022 $this->setParams($this->_formValues
);
3025 $this->processReportMode();
3027 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
3028 $this->_createNew
= ($this->_outputMode
== 'copy');
3029 CRM_Report_Form_Instance
::postProcess($this);
3031 if ($this->_outputMode
== 'delete') {
3032 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
3035 $this->_formValues
= $this->_params
;
3037 $this->beginPostProcessCommon();
3041 * BeginPostProcess function run in both report mode and non-report mode (api).
3043 public function beginPostProcessCommon() {
3047 * Build the report query.
3049 * @param bool $applyLimit
3053 public function buildQuery($applyLimit = TRUE) {
3054 $this->buildGroupTempTable();
3057 $this->customDataFrom();
3058 $this->buildPermissionClause();
3063 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
3064 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
3066 $clause = "{$field['dbAlias']} as {$alias}";
3068 $this->_select
.= ", $clause ";
3071 if ($applyLimit && empty($this->_params
['charts'])) {
3074 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
3076 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
3077 $this->addToDeveloperTab($sql);
3082 * Build group by clause.
3084 public function groupBy() {
3085 $this->storeGroupByArray();
3087 if (!empty($this->_groupByArray
)) {
3088 if ($this->optimisedForOnlyFullGroupBy
) {
3089 // We should probably deprecate this code path. What happens here is that
3090 // the group by is amended to reflect the select columns. This often breaks the
3091 // results. Retrofitting group strict group by onto existing report classes
3093 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
3096 $this->_groupBy
= ' GROUP BY ' . implode($this->_groupByArray
);
3102 * Build order by clause.
3104 public function orderBy() {
3105 $this->_orderBy
= "";
3106 $this->_sections
= [];
3107 $this->storeOrderByArray();
3108 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
3109 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
3111 $this->assign('sections', $this->_sections
);
3115 * Extract order by fields and store as an array.
3117 * In some cases other functions want to know which fields are selected for ordering by
3118 * Separating this into a separate function allows it to be called separately from constructing
3119 * the order by clause
3121 public function storeOrderByArray() {
3124 if (!empty($this->_params
['order_bys']) &&
3125 is_array($this->_params
['order_bys']) &&
3126 !empty($this->_params
['order_bys'])
3129 // Process order_bys in user-specified order
3130 foreach ($this->_params
['order_bys'] as $orderBy) {
3132 foreach ($this->_columns
as $tableName => $table) {
3133 if (array_key_exists('order_bys', $table)) {
3134 // For DAO columns defined in $this->_columns
3135 $fields = $table['order_bys'];
3137 elseif (array_key_exists('extends', $table)) {
3138 // For custom fields referenced in $this->_customGroupExtends
3139 $fields = CRM_Utils_Array
::value('fields', $table, []);
3144 if (!empty($fields) && is_array($fields)) {
3145 foreach ($fields as $fieldName => $field) {
3146 if ($fieldName == $orderBy['column']) {
3147 $orderByField = array_merge($field, $orderBy);
3148 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
3155 if (!empty($orderByField)) {
3156 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
3157 if ($this->groupConcatTested
) {
3158 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
3161 // Not sure when this is preferable to using tplField (which has
3162 // definitely been tested to work in cases then this does not.
3163 // in caution not switching unless report has been tested for
3164 // group concat functionality.
3165 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
3168 // Record any section headers for assignment to the template
3169 if (!empty($orderBy['section'])) {
3170 $orderByField['pageBreak'] = $orderBy['pageBreak'] ??
NULL;
3171 $this->_sections
[$orderByField['tplField']] = $orderByField;
3177 $this->_orderByArray
= $orderBys;
3179 $this->assign('sections', $this->_sections
);
3183 * Determine unselected columns.
3187 public function unselectedOrderByColumns() {
3188 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
3192 * Determine unselected columns.
3196 public function unselectedSectionColumns() {
3197 if (is_array($this->_sections
)) {
3198 return array_diff_key($this->_sections
, $this->getSelectColumns());
3206 * Build output rows.
3208 * @param string $sql
3209 * @param array $rows
3211 public function buildRows($sql, &$rows) {
3212 if (!$this->optimisedForOnlyFullGroupBy
) {
3213 CRM_Core_DAO
::disableFullGroupByMode();
3215 $dao = CRM_Core_DAO
::executeQuery($sql);
3216 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
3217 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
3219 CRM_Core_DAO
::reenableFullGroupByMode();
3220 if (!is_array($rows)) {
3224 // use this method to modify $this->_columnHeaders
3225 $this->modifyColumnHeaders();
3227 $unselectedSectionColumns = $this->unselectedSectionColumns();
3229 while ($dao->fetch()) {
3231 foreach ($this->_columnHeaders
as $key => $value) {
3232 if (property_exists($dao, $key)) {
3233 $row[$key] = $dao->$key;
3237 // section headers not selected for display need to be added to row
3238 foreach ($unselectedSectionColumns as $key => $values) {
3239 if (property_exists($dao, $key)) {
3240 $row[$key] = $dao->$key;
3249 * Calculate section totals.
3251 * When "order by" fields are marked as sections, this assigns to the template
3252 * an array of total counts for each section. This data is used by the Smarty
3253 * plugin {sectionTotal}.
3255 public function sectionTotals() {
3257 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3258 if (empty($this->_selectAliases
)) {
3262 if (!empty($this->_sections
)) {
3263 // build the query with no LIMIT clause
3264 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3265 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3267 // pull section aliases out of $this->_sections
3268 $sectionAliases = array_keys($this->_sections
);
3271 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3272 $ifnulls[] = "ifnull($alias, '') as $alias";
3274 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3275 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3277 // Group (un-limited) report by all aliases and get counts. This might
3278 // be done more efficiently when the contents of $sql are known, ie. by
3279 // overriding this method in the report class.
3281 $query = $this->_select
.
3282 ", count(*) as ct from ($sql) as subquery group by " .
3283 implode(", ", $sectionAliases);
3285 // initialize array of total counts
3287 $dao = CRM_Core_DAO
::executeQuery($query);
3288 while ($dao->fetch()) {
3290 // let $this->_alterDisplay translate any integer ids to human-readable values.
3291 $rows[0] = $dao->toArray();
3292 $this->alterDisplay($rows);
3293 $this->alterCustomDataDisplay($rows);
3296 // add totals for all permutations of section values
3299 $aliasCount = count($sectionAliases);
3300 foreach ($sectionAliases as $alias) {
3301 $values[] = $row[$alias];
3302 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3303 if ($i == $aliasCount) {
3304 // the last alias is the lowest-level section header; use count as-is
3305 $totals[$key] = $dao->ct
;
3308 // other aliases are higher level; roll count into their total
3309 $totals[$key] +
= $dao->ct
;
3313 $this->assign('sectionTotals', $totals);
3318 * Modify column headers.
3320 public function modifyColumnHeaders() {
3321 // use this method to modify $this->_columnHeaders
3325 * Move totals columns to the right edge of the table.
3327 * It seems like a more logical layout to have any totals columns on the far right regardless of
3328 * the location of the rest of their table.
3330 public function moveSummaryColumnsToTheRightHandSide() {
3331 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3332 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3336 * Assign rows to the template.
3338 * @param array $rows
3340 public function doTemplateAssignment(&$rows) {
3341 $this->assign('columnHeaders', $this->_columnHeaders
);
3342 $this->assign_by_ref('rows', $rows);
3343 $this->assign('statistics', $this->statistics($rows));
3347 * Build report statistics.
3349 * Override this method to build your own statistics.
3351 * @param array $rows
3355 public function statistics(&$rows) {
3358 $count = count($rows);
3359 // Why do we increment the count for rollup seems to artificially inflate the count.
3360 // It seems perhaps intentional to include the summary row in the count of results - although
3361 // this just seems odd.
3362 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3366 $this->countStat($statistics, $count);
3368 $this->groupByStat($statistics);
3370 $this->filterStat($statistics);
3376 * Add count statistics.
3378 * @param array $statistics
3381 public function countStat(&$statistics, $count) {
3382 $statistics['counts']['rowCount'] = [
3383 'title' => ts('Row(s) Listed'),
3385 'type' => CRM_Utils_Type
::T_INT
,
3388 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3389 $statistics['counts']['rowsFound'] = [
3390 'title' => ts('Total Row(s)'),
3391 'value' => $this->_rowsFound
,
3392 'type' => CRM_Utils_Type
::T_INT
,
3398 * Add group by statistics.
3400 * @param array $statistics
3402 public function groupByStat(&$statistics) {
3403 if (!empty($this->_params
['group_bys']) &&
3404 is_array($this->_params
['group_bys']) &&
3405 !empty($this->_params
['group_bys'])
3407 foreach ($this->_columns
as $tableName => $table) {
3408 if (array_key_exists('group_bys', $table)) {
3409 foreach ($table['group_bys'] as $fieldName => $field) {
3410 if (!empty($this->_params
['group_bys'][$fieldName])) {
3411 $combinations[] = $field['title'];
3416 $statistics['groups'][] = [
3417 'title' => ts('Grouping(s)'),
3418 'value' => implode(' & ', $combinations),
3422 // prevents an e-notice in statistics.tpl.
3423 $statistics['groups'] = [];
3428 * Filter statistics.
3430 * @param array $statistics
3432 public function filterStat(&$statistics) {
3433 foreach ($this->_columns
as $tableName => $table) {
3434 if (array_key_exists('filters', $table)) {
3435 foreach ($table['filters'] as $fieldName => $field) {
3436 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3437 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3438 CRM_Utils_Array
::value('operatorType', $field) !=
3439 CRM_Report_Form
::OP_MONTH
3441 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
3442 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
3443 if (!empty($this->_params
["{$fieldName}_relative"])) {
3444 [$from, $to] = CRM_Utils_Date
::getFromTo($this->_params
["{$fieldName}_relative"], NULL, NULL);
3446 if (strlen($to ??
'') === 10) {
3447 // If we just have the date we assume the end of that day.
3452 $from = date('l j F Y, g:iA', strtotime($from));
3455 $to = date('l j F Y, g:iA', strtotime($to));
3457 $statistics['filters'][] = [
3458 'title' => $field['title'],
3459 'value' => ts("Between %1 and %2", [1 => $from, 2 => $to]),
3462 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3463 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3465 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3466 $statistics['filters'][] = [
3467 'title' => $field['title'],
3468 'value' => $pair[$rel],
3473 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
3476 $pair = $this->getOperationPair(
3477 CRM_Utils_Array
::value('operatorType', $field),
3480 $min = $this->_params
["{$fieldName}_min"] ??
NULL;
3481 $max = $this->_params
["{$fieldName}_max"] ??
NULL;
3482 $val = $this->_params
["{$fieldName}_value"] ??
NULL;
3483 if (in_array($op, ['bw', 'nbw']) && ($min ||
$max)) {
3484 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3486 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3487 $this->setEntityRefDefaults($field, $tableName);
3488 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3490 CRM_Utils_Array
::value('api', $field['attributes'], []));
3492 foreach ($result['values'] as $v) {
3493 $values[] = $v['label'];
3495 $value = "{$pair[$op]} " . implode(', ', $values);
3497 elseif ($op == 'nll' ||
$op == 'nnll') {
3498 $value = $pair[$op];
3500 elseif (is_array($val) && (!empty($val))) {
3501 $options = CRM_Utils_Array
::value('options', $field, []);
3502 foreach ($val as $key => $valIds) {
3503 if (isset($options[$valIds])) {
3504 $val[$key] = $options[$valIds];
3507 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3508 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3509 $val = implode(', ', $val);
3510 $value = "{$pair[$op]} " . $val;
3512 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3513 isset($field['options']) &&
3514 is_array($field['options']) && !empty($field['options'])
3516 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3517 CRM_Utils_Array
::value($val, $field['options'], $val);
3519 elseif ($val ||
$val == '0') {
3520 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3523 if ($value && empty($field['no_display'])) {
3524 $statistics['filters'][] = [
3525 'title' => $field['title'] ??
NULL,
3526 'value' => CRM_Utils_String
::htmlToText($value),
3533 // Prevents an e-notice in statistics.tpl.
3534 if (!isset($statistics['filters'])) {
3535 $statistics['filters'] = [];
3540 * End post processing.
3542 * @param array|null $rows
3544 public function endPostProcess(&$rows = NULL) {
3545 $this->assign('report_class', get_class($this));
3547 // This is used by unit tests, where _outputMode is intentionally blank.
3548 // Is there a reason it couldn't just always do this? It effectively does
3549 // the same thing anyway by assigning it to the template (in
3550 // doTemplateAssignment()).
3551 if ($this->_storeResultSet
) {
3552 $this->_resultSet
= $rows;
3555 // Add contacts to group
3556 if ($this->_outputMode
== 'group') {
3557 $group = $this->_params
['groups'];
3558 $this->add2group($group);
3561 if ($this->_sendmail
) {
3564 elseif (!empty($this->outputHandler
)) {
3565 $this->outputHandler
->download();
3566 CRM_Utils_System
::civiExit();
3568 // else we don't need to do anything here since it must have been
3569 // outputMode=save or something like that
3574 * Set store result set indicator to TRUE.
3576 * This is used by unit tests, along with getResultSet(), to get just
3577 * the output rows unformatted.
3579 public function storeResultSet() {
3580 $this->_storeResultSet
= TRUE;
3588 public function getResultSet() {
3589 return $this->_resultSet
;
3593 * Get the sql used to generate the report.
3597 public function getReportSql() {
3598 return $this->sqlArray
;
3602 * Use the form name to create the tpl file name.
3606 public function getTemplateFileName() {
3607 $defaultTpl = parent
::getTemplateFileName();
3608 $template = CRM_Core_Smarty
::singleton();
3609 if (!$template->template_exists($defaultTpl)) {
3610 $defaultTpl = 'CRM/Report/Form.tpl';
3616 * Compile the report content.
3618 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3622 public function compileContent() {
3623 $templateFile = $this->getHookedTemplateFileName();
3624 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3625 CRM_Core_Form
::$_template->fetch($templateFile) .
3626 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3630 * Post process function.
3632 public function postProcess() {
3633 // get ready with post process params
3634 $this->beginPostProcess();
3637 $sql = $this->buildQuery();
3639 // build array of result based on column headers. This method also allows
3640 // modifying column headers before using it to build result set i.e $rows.
3642 $this->buildRows($sql, $rows);
3644 // format result set.
3645 $this->formatDisplay($rows);
3647 // assign variables to templates
3648 $this->doTemplateAssignment($rows);
3650 // do print / pdf / instance stuff if needed
3651 $this->endPostProcess($rows);
3657 * @param int|null $rowCount
3661 public function limit($rowCount = NULL) {
3662 $rowCount = $rowCount ??
$this->getRowCount();
3663 // lets do the pager if in html mode
3664 $this->_limit
= NULL;
3666 // CRM-14115, over-ride row count if rowCount is specified in URL
3667 if ($this->_dashBoardRowCount
) {
3668 $rowCount = $this->_dashBoardRowCount
;
3670 if ($this->addPaging
) {
3671 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3673 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3675 // @todo all http vars should be extracted in the preProcess
3676 // - not randomly in the class
3677 if (!$pageId && !empty($_POST)) {
3678 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3679 $pageId = max((int) $_POST['crmPID_B'], 1);
3681 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3682 $pageId = max((int) $_POST['crmPID'], 1);
3684 unset($_POST['crmPID_B'], $_POST['crmPID']);
3687 $pageId = $pageId ?
$pageId : 1;
3688 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3689 $offset = ($pageId - 1) * $rowCount;
3691 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3692 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3694 $this->_limit
= " LIMIT $offset, $rowCount";
3695 return [$offset, $rowCount];
3697 if ($this->_limitValue
) {
3698 if ($this->_offsetValue
) {
3699 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3702 $this->_limit
= " LIMIT " . $this->_limitValue
;
3710 * @param int|null $rowCount
3712 public function setPager($rowCount = NULL) {
3713 $rowCount = $rowCount ??
$this->getRowCount();
3714 // CRM-14115, over-ride row count if rowCount is specified in URL
3715 if ($this->_dashBoardRowCount
) {
3716 $rowCount = $this->_dashBoardRowCount
;
3719 if ($this->_limit
&& ($this->_limit
!= '')) {
3720 if (!$this->_rowsFound
) {
3721 $sql = "SELECT FOUND_ROWS();";
3722 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3725 'total' => $this->_rowsFound
,
3726 'rowCount' => $rowCount,
3727 'status' => ts('Records') . ' %%StatusMessage%%',
3728 'buttonBottom' => 'PagerBottomButton',
3729 'buttonTop' => 'PagerTopButton',
3731 if (!empty($this->controller
)) {
3732 // This happens when being called from the api Really we want the api to be able to
3733 // pass paging parameters, but at this stage just preventing test crashes.
3734 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3737 $pager = new CRM_Utils_Pager($params);
3738 $this->assign_by_ref('pager', $pager);
3739 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3744 * Build a group filter with contempt for large data sets.
3746 * This function has been retained as it takes time to migrate the reports over
3747 * to the new method which will not crash on large datasets.
3751 * @param array $field
3752 * @param mixed $value
3757 public function legacySlowGroupFilterClause($field, $value, $op) {
3758 $smartGroupQuery = "";
3760 $group = new CRM_Contact_DAO_Group();
3761 $group->is_active
= 1;
3764 while ($group->fetch()) {
3765 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3766 $group->saved_search_id
3768 $smartGroups[] = $group->id
;
3772 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3774 $smartGroupQuery = '';
3775 if (!empty($smartGroups)) {
3776 $smartGroups = implode(',', $smartGroups);
3777 $smartGroupQuery = " UNION DISTINCT
3778 SELECT DISTINCT smartgroup_contact.contact_id
3779 FROM civicrm_group_contact_cache smartgroup_contact
3780 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3783 $sqlOp = $this->getSQLOperator($op);
3784 if (!is_array($value)) {
3787 //include child groups if any
3788 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3790 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3792 $contactAlias = $this->_aliases
['civicrm_contact'];
3793 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3794 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3796 return " {$contactAlias}.id {$sqlOp} (
3797 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3798 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3799 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3800 {$smartGroupQuery} ) ";
3804 * Build where clause for groups.
3806 * @param array $field
3807 * @param mixed $value
3812 public function whereGroupClause($field, $value, $op) {
3813 if ($this->groupFilterNotOptimised
) {
3814 return $this->legacySlowGroupFilterClause($field, $value, $op);
3816 if ($op === 'notin') {
3817 return " group_temp_table.contact_id IS NULL ";
3819 // We will have used an inner join instead.
3824 * Create a table of the contact ids included by the group filter.
3826 * This function is called by both the api (tests) and the UI.
3828 * @throws \CiviCRM_API3_Exception
3830 public function buildGroupTempTable(): void
{
3831 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3834 $this->groupTempTable
= $this->createTemporaryTable('groups', 'contact_id INT', TRUE);
3835 $filteredGroups = (array) $this->_params
['gid_value'];
3836 CRM_Contact_BAO_GroupContactCache
::populateTemporaryTableWithContactsInGroups($filteredGroups, $this->groupTempTable
);
3837 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX contact_id(contact_id)");
3841 * Execute query and add it to the developer tab.
3843 * @param string $query
3844 * @param array $params
3846 * @return \CRM_Core_DAO|object
3848 protected function executeReportQuery($query, $params = []) {
3849 $this->addToDeveloperTab($query);
3850 return CRM_Core_DAO
::executeQuery($query, $params);
3854 * Build where clause for tags.
3856 * @param array $field
3857 * @param mixed $value
3862 public function whereTagClause($field, $value, $op) {
3863 // not using left join in query because if any contact
3864 // belongs to more than one tag, results duplicate
3866 $sqlOp = $this->getSQLOperator($op);
3867 if (!is_array($value)) {
3870 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3871 $entity_table = $this->_tagFilterTable
;
3872 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3873 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3874 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3875 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3879 * Generate membership organization clause.
3881 * @param mixed $value
3882 * @param string $op SQL Operator
3886 public function whereMembershipOrgClause($value, $op) {
3887 $sqlOp = $this->getSQLOperator($op);
3888 if (!is_array($value)) {
3892 $tmp_membership_org_sql_list = implode(', ', $value);
3893 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3894 SELECT DISTINCT mem.contact_id
3895 FROM civicrm_membership mem
3896 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3897 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3898 WHERE mt.member_of_contact_id IN (" .
3899 $tmp_membership_org_sql_list . ")
3900 AND mt.is_active = '1'
3901 AND mem_status.is_current_member = '1'
3902 AND mem_status.is_active = '1' ) ";
3906 * Generate Membership Type SQL Clause.
3908 * @param mixed $value
3914 public function whereMembershipTypeClause($value, $op) {
3915 $sqlOp = $this->getSQLOperator($op);
3916 if (!is_array($value)) {
3920 $tmp_membership_sql_list = implode(', ', $value);
3921 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3922 SELECT DISTINCT mem.contact_id
3923 FROM civicrm_membership mem
3924 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3925 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3926 WHERE mem.membership_type_id IN (" .
3927 $tmp_membership_sql_list . ")
3928 AND mt.is_active = '1'
3929 AND mem_status.is_current_member = '1'
3930 AND mem_status.is_active = '1' ) ";
3934 * Build contact acl clause
3935 * @deprecated in favor of buildPermissionClause
3937 * Note that if the buildPermissionClause function is called (which most reports do from
3938 * buildQuery then the results of this function are re-calculated and overwritten.
3940 * @param string $tableAlias
3942 public function buildACLClause($tableAlias = 'contact_a') {
3943 [$this->_aclFrom
, $this->_aclWhere
] = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3947 * Build the permission clause for all entities in this report
3949 public function buildPermissionClause() {
3951 foreach ($this->selectedTables() as $tableName) {
3952 $baoName = str_replace('_DAO_', '_BAO_', (CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName) ??
''));
3953 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3954 $tableAlias = $this->_columns
[$tableName]['alias'];
3955 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3956 foreach ($clauses as $field => $clause) {
3957 // Skip contact_id field if redundant
3958 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3959 $ret["$tableName.$field"] = $clause;
3964 // Override output from buildACLClause
3965 $this->_aclFrom
= NULL;
3966 $this->_aclWhere
= implode(' AND ', $ret);
3970 * Add custom data to the columns.
3972 * @param bool $addFields
3973 * @param array $permCustomGroupIds
3975 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = []) {
3976 if (empty($this->_customGroupExtends
)) {
3979 if (!is_array($this->_customGroupExtends
)) {
3980 $this->_customGroupExtends
= [$this->_customGroupExtends
];
3982 $customGroupWhere = '';
3983 if (!empty($permCustomGroupIds)) {
3984 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3988 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3989 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format,
3990 cf.serialize as serialize
3991 FROM civicrm_custom_group cg
3992 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3993 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3995 cg.is_active = 1 AND
3996 cf.is_active = 1 AND
3997 cf.is_searchable = 1
3998 ORDER BY cg.weight, cf.weight";
3999 $customDAO = CRM_Core_DAO
::executeQuery($sql);
4002 while ($customDAO->fetch()) {
4003 if ($customDAO->table_name
!= $curTable) {
4004 $curTable = $customDAO->table_name
;
4005 $curFields = $curFilters = [];
4008 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
4009 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
4010 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
4011 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
4013 foreach (['fields', 'filters', 'group_bys'] as $colKey) {
4014 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
4015 $this->_columns
[$curTable][$colKey] = [];
4019 $fieldName = 'custom_' . $customDAO->cf_id
;
4022 // this makes aliasing work in favor
4023 $curFields[$fieldName] = [
4024 'name' => $customDAO->column_name
,
4025 'title' => $customDAO->label
,
4026 'dataType' => $customDAO->data_type
,
4027 'htmlType' => $customDAO->html_type
,
4030 if ($this->_customGroupFilters
) {
4031 // this makes aliasing work in favor
4032 $curFilters[$fieldName] = [
4033 'name' => $customDAO->column_name
,
4034 'title' => $customDAO->label
,
4035 'dataType' => $customDAO->data_type
,
4036 'htmlType' => $customDAO->html_type
,
4040 switch ($customDAO->data_type
) {
4043 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
4044 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
4045 // CRM-6946, show time part for datetime date fields
4046 if ($customDAO->time_format
) {
4047 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
4052 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
4053 $curFilters[$fieldName]['options'] = ['' => ts('- select -')] + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4054 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
4058 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
4059 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
4063 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
4064 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
4065 // Use T_FLOAT instead of T_MONEY as the money number format happens
4066 // by calling CRM_Core_BAO_CustomField::displayValue in alterCustomDataDisplay
4067 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
4071 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
4072 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
4076 case 'StateProvince':
4078 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4080 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4081 if ((is_array($options) && count($options) != 0) ||
(!is_array($options) && $options !== FALSE)) {
4082 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4083 $curFilters[$fieldName]['options'] = $options;
4087 case 'ContactReference':
4088 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4089 $curFilters[$fieldName]['name'] = 'display_name';
4090 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4092 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4093 $curFields[$fieldName]['name'] = 'display_name';
4094 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4098 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4099 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4103 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
4104 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4105 if ($options !== FALSE) {
4106 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4107 $curFilters[$fieldName]['options'] = $options;
4111 if (!array_key_exists('type', $curFields[$fieldName])) {
4112 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], []);
4116 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
4118 if ($this->_customGroupFilters
) {
4119 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
4121 if ($this->_customGroupGroupBy
) {
4122 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
4128 * Build custom data from clause.
4130 * @param bool $joinsForFiltersOnly
4131 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
4133 public function customDataFrom($joinsForFiltersOnly = FALSE) {
4134 if (empty($this->_customGroupExtends
)) {
4137 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
4138 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
4139 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
4141 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
4142 while ($customTablesDAO->fetch()) {
4143 $customTables[] = $customTablesDAO->table_name
;
4146 foreach ($this->_columns
as $table => $prop) {
4147 if (in_array($table, $customTables)) {
4148 $extendsTable = $mapper[$prop['extends']];
4149 // Check field is required for rendering the report.
4150 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4153 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
4155 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
4157 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4158 // handle for ContactReference
4159 if (array_key_exists('fields', $prop)) {
4160 foreach ($prop['fields'] as $fieldName => $field) {
4161 if (CRM_Utils_Array
::value('dataType', $field) ==
4164 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4166 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4175 * Check if the field is selected.
4177 * @param string $prop
4181 public function isFieldSelected($prop) {
4186 if (!empty($this->_params
['fields'])) {
4187 foreach (array_keys($prop['fields']) as $fieldAlias) {
4188 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4189 if ($customFieldId) {
4190 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4194 //might be survey response field.
4195 if (!empty($this->_params
['fields']['survey_response']) &&
4196 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4204 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4205 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4206 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4207 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4214 if (!empty($this->_params
['order_bys'])) {
4215 foreach (array_keys($prop['fields']) as $fieldAlias) {
4216 foreach ($this->_params
['order_bys'] as $orderBy) {
4217 if ($fieldAlias == $orderBy['column'] &&
4218 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4225 return $this->isFieldFiltered($prop);
4230 * Check if the field is used as a filter.
4232 * @param string $prop
4236 protected function isFieldFiltered($prop) {
4237 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4238 foreach ($prop['filters'] as $fieldAlias => $val) {
4247 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4248 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4249 ||
($attach != 'relative' &&
4250 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4256 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4257 in_array($this->_params
[$fieldAlias . '_op'], ['nll', 'nnll'])
4268 * Check for empty order_by configurations and remove them.
4270 * Also set template to hide them.
4272 * @param array $formValues
4274 public function preProcessOrderBy(&$formValues) {
4275 // Object to show/hide form elements
4276 $_showHide = new CRM_Core_ShowHideBlocks();
4278 $_showHide->addShow('optionField_1');
4280 // Cycle through order_by options; skip any empty ones, and hide them as well
4283 if (!empty($formValues['order_bys'])) {
4284 foreach ($formValues['order_bys'] as $order_by) {
4285 if ($order_by['column'] && $order_by['column'] != '-') {
4286 $_showHide->addShow('optionField_' . $n);
4287 $orderBys[$n] = $order_by;
4292 for ($i = $n; $i <= 5; $i++
) {
4294 $_showHide->addHide('optionField_' . $i);
4298 // overwrite order_by options with modified values
4299 if (!empty($orderBys)) {
4300 $formValues['order_bys'] = $orderBys;
4303 $formValues['order_bys'] = [1 => ['column' => '-']];
4306 // assign show/hide data to template
4307 $_showHide->addToTemplate();
4311 * Check if table name has columns in SELECT clause.
4313 * @param string $tableName
4314 * Name of table (index of $this->_columns array).
4318 public function isTableSelected($tableName) {
4319 return in_array($tableName, $this->selectedTables());
4323 * Check if table name has columns in WHERE or HAVING clause.
4325 * @param string $tableName
4326 * Name of table (index of $this->_columns array).
4330 public function isTableFiltered($tableName) {
4331 // Cause the array to be generated if not previously done.
4332 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4333 $this->selectedTables();
4335 return in_array($tableName, $this->filteredTables
);
4339 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4341 * If the array is unset it will be built.
4346 public function selectedTables() {
4347 if (!$this->_selectedTables
) {
4348 $orderByColumns = [];
4349 if (array_key_exists('order_bys', $this->_params
) &&
4350 is_array($this->_params
['order_bys'])
4352 foreach ($this->_params
['order_bys'] as $orderBy) {
4353 $orderByColumns[] = $orderBy['column'];
4357 foreach ($this->_columns
as $tableName => $table) {
4358 if (array_key_exists('fields', $table)) {
4359 foreach ($table['fields'] as $fieldName => $field) {
4360 if (!empty($field['required']) ||
4361 !empty($this->_params
['fields'][$fieldName])
4363 $this->_selectedTables
[] = $tableName;
4368 if (array_key_exists('order_bys', $table)) {
4369 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4370 if (in_array($orderByName, $orderByColumns)) {
4371 $this->_selectedTables
[] = $tableName;
4376 if (array_key_exists('filters', $table)) {
4377 foreach ($table['filters'] as $filterName => $filter) {
4378 $filterOp = $this->_params
["{$filterName}_op"] ??
'';
4379 if ((isset($this->_params
["{$filterName}_value"])
4380 && !CRM_Utils_System
::isNull($this->_params
["{$filterName}_value"]))
4381 ||
!empty($this->_params
["{$filterName}_relative"])
4382 ||
$filterOp === 'nll'
4383 ||
$filterOp === 'nnll'
4385 $this->_selectedTables
[] = $tableName;
4386 $this->filteredTables
[] = $tableName;
4393 return $this->_selectedTables
;
4397 * Add campaign fields.
4398 * @param string $entityTable
4399 * @param bool $groupBy
4400 * Add GroupBy? Not appropriate for detail report.
4401 * @param bool $orderBy
4402 * Add OrderBy? Not appropriate for detail report.
4403 * @param bool $filters
4406 public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) {
4407 // Check if CiviCampaign is a) enabled and b) has active campaigns
4408 if (CRM_Core_Component
::isEnabled('CiviCampaign')) {
4409 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE);
4410 // If we have a campaign, build out the relevant elements
4411 if (!empty($getCampaigns['campaigns'])) {
4412 $this->campaigns
= $getCampaigns['campaigns'];
4413 asort($this->campaigns
);
4414 $this->_columns
[$entityTable]['fields']['campaign_id'] = ['title' => ts('Campaign'), 'default' => 'false'];
4416 $this->_columns
[$entityTable]['filters']['campaign_id'] = [
4417 'title' => ts('Campaign'),
4418 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4419 'options' => $this->campaigns
,
4420 'type' => CRM_Utils_Type
::T_INT
,
4425 $this->_columns
[$entityTable]['group_bys']['campaign_id'] = ['title' => ts('Campaign')];
4429 $this->_columns
[$entityTable]['order_bys']['campaign_id'] = ['title' => ts('Campaign')];
4436 * Add address fields.
4438 * @deprecated - use getAddressColumns which is a more accurate description
4439 * and also accepts an array of options rather than a long list
4441 * adding address fields to construct function in reports
4443 * @param bool $groupBy
4444 * Add GroupBy? Not appropriate for detail report.
4445 * @param bool $orderBy
4446 * Add GroupBy? Not appropriate for detail report.
4447 * @param bool $filters
4448 * @param array $defaults
4451 * address fields for construct clause
4453 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = ['country_id' => TRUE]) {
4454 $defaultAddressFields = [
4455 'street_address' => ts('Street Address'),
4456 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4457 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4458 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4459 'street_number' => ts('Street Number'),
4460 'street_name' => ts('Street Name'),
4461 'street_unit' => ts('Street Unit'),
4462 'city' => ts('City'),
4463 'postal_code' => ts('Postal Code'),
4464 'postal_code_suffix' => ts('Postal Code Suffix'),
4465 'country_id' => ts('Country'),
4466 'state_province_id' => ts('State/Province'),
4467 'county_id' => ts('County'),
4470 'civicrm_address' => [
4471 'dao' => 'CRM_Core_DAO_Address',
4474 'title' => ts('Address Name'),
4475 'default' => $defaults['name'] ??
FALSE,
4479 'grouping' => 'location-fields',
4482 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4483 $addressFields['civicrm_address']['fields'][$fieldName] = [
4484 'title' => $fieldLabel,
4485 'default' => $defaults[$fieldName] ??
FALSE,
4489 $street_address_filters = $general_address_filters = [];
4491 // Address filter depends on whether street address parsing is enabled.
4493 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4496 if ($addressOptions['street_address_parsing']) {
4497 $street_address_filters = [
4498 'street_number' => [
4499 'title' => ts('Street Number'),
4500 'type' => CRM_Utils_Type
::T_INT
,
4501 'name' => 'street_number',
4504 'title' => ts('Street Name'),
4505 'name' => 'street_name',
4506 'type' => CRM_Utils_Type
::T_STRING
,
4511 $street_address_filters = [
4512 'street_address' => [
4513 'title' => ts('Street Address'),
4514 'type' => CRM_Utils_Type
::T_STRING
,
4515 'name' => 'street_address',
4519 $general_address_filters = [
4521 'title' => ts('Postal Code'),
4522 'type' => CRM_Utils_Type
::T_STRING
,
4523 'name' => 'postal_code',
4526 'title' => ts('City'),
4527 'type' => CRM_Utils_Type
::T_STRING
,
4531 'name' => 'country_id',
4532 'title' => ts('Country'),
4533 'type' => CRM_Utils_Type
::T_INT
,
4534 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4535 'options' => CRM_Core_PseudoConstant
::country(),
4537 'state_province_id' => [
4538 'name' => 'state_province_id',
4539 'title' => ts('State/Province'),
4540 'type' => CRM_Utils_Type
::T_INT
,
4541 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4545 'name' => 'county_id',
4546 'title' => ts('County'),
4547 'type' => CRM_Utils_Type
::T_INT
,
4548 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4553 $addressFields['civicrm_address']['filters'] = array_merge(
4554 $street_address_filters,
4555 $general_address_filters);
4558 $addressFields['civicrm_address']['order_bys'] = [
4559 'street_name' => ['title' => ts('Street Name')],
4560 'street_number' => ['title' => ts('Odd / Even Street Number')],
4561 'street_address' => NULL,
4563 'postal_code' => NULL,
4568 $addressFields['civicrm_address']['group_bys'] = [
4569 'street_address' => NULL,
4571 'postal_code' => NULL,
4572 'state_province_id' => [
4573 'title' => ts('State/Province'),
4576 'title' => ts('Country'),
4579 'title' => ts('County'),
4583 return $addressFields;
4587 * Do AlterDisplay processing on Address Fields.
4588 * If there are multiple address field values then
4589 * on basis of provided separator the code values are translated into respective labels
4592 * @param array $rows
4593 * @param int $rowNum
4594 * @param string|null $baseUrl
4595 * @param string|null $linkText
4596 * @param string $separator
4600 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4601 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4602 $entryFound = FALSE;
4604 'civicrm_address_country_id' => 'country',
4605 'civicrm_address_county_id' => 'county',
4606 'civicrm_address_state_province_id' => 'stateProvince',
4608 foreach ($columnMap as $fieldName => $fnName) {
4609 if (array_key_exists($fieldName, $row)) {
4610 if ($values = $row[$fieldName]) {
4611 $values = (array) explode($separator, $values);
4612 $rows[$rowNum][$fieldName] = [];
4613 $addressField = $fnName == 'stateProvince' ?
'state' : $fnName;
4614 foreach ($values as $value) {
4615 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant
::$fnName($value);
4617 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4619 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4620 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4621 $criteriaQueryParams,
4622 str_replace('civicrm_address_', '', $fieldName),
4623 str_replace('civicrm_address_', '', $fieldName),
4624 implode(',', $values)
4625 ), $this->_absoluteUrl
, $this->_id
4627 $rows[$rowNum]["{$fieldName}_link"] = $url;
4628 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", [1 => $linkText, 2 => $addressField]);
4639 * Do AlterDisplay processing on Address Fields.
4642 * @param array $rows
4643 * @param int $rowNum
4644 * @param string|null $baseUrl
4645 * @param string|null $linkText
4649 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4650 $entryFound = FALSE;
4651 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4652 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4653 $addLinks = ['gender_id' => 'Gender'];
4654 foreach (['prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language'] as $fieldName) {
4655 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4656 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4657 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4659 foreach ($rowValues as $rowValue) {
4661 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4664 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4665 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4666 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4673 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'do_not_trade', 'is_opt_out',
4675 foreach ($yesNoFields as $fieldName) {
4676 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4677 // Since these are essentially 'negative fields' it feels like it
4678 // makes sense to only highlight the exceptions hence no 'No'.
4679 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4684 // Handle employer id
4685 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4686 $employerId = $row['civicrm_contact_employer_id'];
4688 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact
::displayName($employerId);
4689 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
4690 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4699 * Adjusts dates passed in to YEAR() for fiscal year.
4701 * @param string $fieldName
4705 public function fiscalYearOffset($fieldName) {
4706 $config = CRM_Core_Config
::singleton();
4707 $fy = $config->fiscalYearStart
;
4708 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4709 ($fy['d'] == 1 && $fy['M'] == 1)
4711 return "YEAR( $fieldName )";
4713 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4714 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4718 * Add Address into From Table if required.
4720 * Prefix will be added to both tables as
4721 * it is assumed you are using it to get address of a secondary contact.
4723 * @param string $prefix
4724 * @param array $extra Additional options.
4725 * Not currently used in core but may be used in override extensions.
4727 protected function joinAddressFromContact($prefix = '', $extra = []) {
4728 $defaults = ['primary_only' => TRUE];
4729 $params = array_merge($defaults, $extra);
4730 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4731 $isJoinRequired = $this->_addressField
;
4732 foreach ($addressTables as $addressTable) {
4733 if ($this->isTableSelected($prefix . $addressTable)) {
4734 $isJoinRequired = TRUE;
4737 if ($isJoinRequired) {
4739 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4740 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4741 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id)";
4742 if ($params['primary_only']) {
4744 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4746 $this->_from
.= $fromJoin;
4751 * Add Country into From Table if required.
4753 * Prefix will be added to both tables as
4754 * it is assumed you are using it to get address of a secondary contact.
4756 * @param string $prefix
4757 * @param array $extra Additional options.
4758 * Not currently used in core but may be used in override extensions.
4760 protected function joinCountryFromAddress($prefix = '', $extra = []) {
4761 $defaults = ['primary_only' => TRUE];
4762 $params = array_merge($defaults, $extra);
4763 // include country field if country column is to be included
4764 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4765 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4766 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4769 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4770 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id";
4771 if ($params['primary_only']) {
4773 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4775 $this->_from
.= $fromJoin;
4780 * Add Phone into From Table if required.
4782 * Prefix will be added to both tables as
4783 * it is assumed you are using it to get address of a secondary contact.
4785 * @param string $prefix
4786 * @param array $extra Additional options.
4787 * Not currently used in core but may be used in override extensions.
4789 protected function joinPhoneFromContact($prefix = '', $extra = []) {
4790 $defaults = ['primary_only' => TRUE];
4791 $params = array_merge($defaults, $extra);
4792 // include phone field if phone column is to be included
4793 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4795 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4796 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id";
4797 if ($params['primary_only']) {
4799 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4801 $this->_from
.= $fromJoin;
4806 * Add Email into From Table if required.
4808 * Prefix will be added to both tables as
4809 * it is assumed you are using it to get address of a secondary contact.
4811 * @param string $prefix
4812 * @param array $extra Additional options.
4813 * Not currently used in core but may be used in override extensions.
4815 protected function joinEmailFromContact($prefix = '', $extra = []) {
4816 $defaults = ['primary_only' => TRUE];
4817 $params = array_merge($defaults, $extra);
4818 // include email field if email column is to be included
4819 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4821 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4822 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id";
4823 if ($params['primary_only']) {
4825 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1 ";
4827 $this->_from
.= $fromJoin;
4832 * Add Financial Transaction into From Table if required.
4834 public function addFinancialTrxnFromClause() {
4835 if ($this->isTableSelected('civicrm_financial_trxn')) {
4837 LEFT JOIN civicrm_entity_financial_trxn eftcc
4838 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4839 eftcc.entity_table = 'civicrm_contribution')
4840 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4841 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4846 * Get phone columns to add to array.
4848 * @param array $options
4849 * - prefix Prefix to add to table (in case of more than one instance of the table)
4850 * - prefix_label Label to give columns from this phone table instance
4853 * phone columns definition
4855 public function getPhoneColumns($options = []) {
4858 'prefix_label' => '',
4861 $options = array_merge($defaultOptions, $options);
4864 $options['prefix'] . 'civicrm_phone' => [
4865 'dao' => 'CRM_Core_DAO_Phone',
4867 $options['prefix'] . 'phone' => [
4868 'title' => $options['prefix_label'] . ts('Phone'),
4878 * Get a standard set of contact fields.
4879 * @deprecated - use getColumns('Contact') instead
4882 public function getBasicContactFields() {
4885 'title' => ts('Contact Name'),
4890 'no_display' => TRUE,
4894 'title' => ts('Contact Prefix'),
4897 'title' => ts('First Name'),
4900 'title' => ts('Nick Name'),
4903 'title' => ts('Middle Name'),
4906 'title' => ts('Last Name'),
4909 'title' => ts('Contact Suffix'),
4911 'source' => ['title' => ts('Contact Source')],
4912 'postal_greeting_display' => ['title' => ts('Postal Greeting')],
4913 'email_greeting_display' => ['title' => ts('Email Greeting')],
4914 'addressee_display' => ['title' => ts('Addressee')],
4916 'title' => ts('Contact Type'),
4918 'contact_sub_type' => [
4919 'title' => ts('Contact Subtype'),
4922 'title' => ts('Gender'),
4925 'title' => ts('Birth Date'),
4928 'title' => ts('Age'),
4929 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4932 'title' => ts('Contact Job title'),
4934 'organization_name' => [
4935 'title' => ts('Organization Name'),
4937 'external_identifier' => [
4938 'title' => ts('Contact identifier from external system'),
4940 'do_not_email' => [],
4941 'do_not_phone' => [],
4942 'do_not_mail' => [],
4944 'do_not_trade' => [],
4946 'is_deceased' => [],
4947 'preferred_language' => [],
4949 'title' => ts('Current Employer'),
4955 * Get a standard set of contact filters.
4957 * @param array $defaults
4961 public function getBasicContactFilters($defaults = []) {
4964 'title' => ts('Contact Name'),
4967 'title' => ts('Contact Source'),
4968 'type' => CRM_Utils_Type
::T_STRING
,
4971 'title' => ts('Contact ID'),
4972 'no_display' => TRUE,
4975 'title' => ts('Gender'),
4976 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4977 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4980 'title' => ts('Birth Date'),
4981 'operatorType' => CRM_Report_Form
::OP_DATE
,
4984 'title' => ts('Contact Type'),
4986 'contact_sub_type' => [
4987 'title' => ts('Contact Subtype'),
4989 'modified_date' => [
4990 'title' => ts('Contact Modified'),
4991 'operatorType' => CRM_Report_Form
::OP_DATE
,
4992 'type' => CRM_Utils_Type
::T_DATE
,
4995 'title' => ts('Deceased'),
4996 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4997 'default' => CRM_Utils_Array
::value('deceased', $defaults, 0),
5000 'title' => ts('Do not email'),
5001 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5004 'title' => ts('Do not phone'),
5005 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5008 'title' => ts('Do not mail'),
5009 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5012 'title' => ts('Do not SMS'),
5013 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5016 'title' => ts('Do not Trade'),
5017 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5020 'title' => ts('Do not bulk email'),
5021 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5023 'preferred_language' => [
5024 'title' => ts('Preferred Language'),
5027 'no_display' => TRUE,
5029 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5035 * Add contact to group.
5037 * @param int $groupID
5039 public function add2group($groupID) {
5040 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
5041 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
5042 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
5043 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
5044 $sql = str_replace('WITH ROLLUP', '', $sql);
5045 if (!$this->optimisedForOnlyFullGroupBy
) {
5046 CRM_Core_DAO
::disableFullGroupByMode();
5048 $dao = CRM_Core_DAO
::executeQuery($sql);
5049 CRM_Core_DAO
::reenableFullGroupByMode();
5052 // Add resulting contacts to group
5053 while ($dao->fetch()) {
5054 if ($dao->addtogroup_contact_id
) {
5055 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
5059 if (!empty($contact_ids)) {
5060 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
5061 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
5064 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
5070 * Apply common settings to entityRef fields.
5072 * @param array $field
5073 * @param string $table
5075 public function setEntityRefDefaults(&$field, $table) {
5076 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : [];
5077 $field['attributes'] +
= [
5078 'entity' => CRM_Core_DAO_AllCoreTables
::getEntityNameForTable($table),
5080 'placeholder' => ts('- select -'),
5085 * Add link fields to the row.
5087 * Function adds the _link & _hover fields to the row.
5090 * @param string $baseUrl
5091 * @param string $linkText
5092 * @param string $value
5093 * @param string $fieldName
5094 * @param string $tablePrefix
5095 * @param string $fieldLabel
5099 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
5100 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
5101 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
5102 "reset=1&force=1&{$criteriaQueryParams}&" .
5103 $fieldName . "_op=in&{$fieldName}_value={$value}",
5104 $this->_absoluteUrl
, $this->_id
5106 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
5107 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
5108 [1 => $linkText, 2 => $fieldLabel]
5113 * Get label for show results buttons.
5117 public function getResultsLabel() {
5118 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
5119 return $showResultsLabel;
5123 * Determine the output mode from the url or input.
5126 * - pdf : Render as pdf
5127 * - csv : Render as csv
5128 * - print : Render in print format
5129 * - save : save the report and display the new report
5130 * - copy : save the report as a new instance and display that.
5131 * - group : go to the add to group screen.
5133 * Potentially chart variations could also be included but the complexity
5134 * is that we might print a bar chart as a pdf.
5136 protected function setOutputMode() {
5137 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
5140 CRM_Core_DAO
::$_nullObject,
5142 CRM_Utils_Array
::value('task', $this->_params
)
5144 // if contacts are added to group
5145 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
5146 $this->_outputMode
= 'group';
5148 if (isset($this->_params
['task'])) {
5149 unset($this->_params
['task']);
5154 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5156 * @param string $tempTable
5157 * @param string $columnName
5159 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5160 // add new column with date value for the datetime field
5161 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5162 CRM_Core_DAO
::executeQuery($tempQuery);
5163 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5164 CRM_Core_DAO
::executeQuery($updateQuery);
5165 $this->_selectClauses
[] = "{$columnName}_date";
5166 $this->_select
.= ", {$columnName}_date";
5167 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5168 unset($this->_sections
["{$columnName}"]);
5169 $this->assign('sections', $this->_sections
);
5173 * Get an array of the columns that have been selected for display.
5177 public function getSelectColumns() {
5178 $selectColumns = [];
5179 foreach ($this->_columns
as $tableName => $table) {
5180 if (array_key_exists('fields', $table)) {
5181 foreach ($table['fields'] as $fieldName => $field) {
5182 if (!empty($field['required']) ||
5183 !empty($this->_params
['fields'][$fieldName])
5186 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5191 return $selectColumns;
5195 * Add location tables to the query if they are used for filtering.
5197 * This is for when we are running the query separately for filtering and retrieving display fields.
5199 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5200 if ($this->isTableFiltered('civicrm_email')) {
5202 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5203 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5204 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5206 if ($this->isTableFiltered('civicrm_phone')) {
5208 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5209 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5210 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5212 if ($this->isTableFiltered('civicrm_address')) {
5214 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5215 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5216 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5221 * Set the base table for the FROM clause.
5223 * Sets up the from clause, allowing for the possibility it might be a
5224 * temp table pre-filtered by groups if a group filter is in use.
5226 * @param string $baseTable
5227 * @param string $field
5228 * @param string|null $tableAlias
5230 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5232 $tableAlias = $this->_aliases
[$baseTable];
5234 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5235 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5236 $this->_from
.= " {$this->_aclFrom} ";
5240 * Join the temp table contacting contacts who are members of the filtered groups.
5242 * If we are using an IN filter we use an inner join, otherwise a left join.
5244 * @param string $baseTable
5245 * @param string $field
5246 * @param string $tableAlias
5248 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5249 if ($this->groupTempTable
) {
5250 if ($this->_params
['gid_op'] == 'in') {
5251 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5252 ON group_temp_table.contact_id = $tableAlias.{$field} ";
5256 LEFT JOIN $this->groupTempTable group_temp_table
5257 ON $tableAlias.{$field} = group_temp_table.contact_id ";
5263 * Get all labels for fields that are used in a group concat.
5265 * @param string $options
5266 * comma separated option values.
5267 * @param string $baoName
5268 * The BAO name for the field.
5269 * @param string $fieldName
5270 * The name of the field for which labels should be retrieved.
5274 public function getLabels($options, $baoName, $fieldName) {
5275 $types = explode(',', $options);
5277 foreach ($types as $value) {
5278 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5280 return implode(', ', array_filter($labels));
5284 * Add statistics columns.
5286 * If a group by is in play then add columns for the statistics fields.
5288 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5289 * column header field.
5291 * @param array $field
5292 * @param string $tableName
5293 * @param string $fieldName
5294 * @param array $select
5298 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5299 foreach ($field['statistics'] as $stat => $label) {
5300 $alias = "{$tableName}_{$fieldName}_{$stat}";
5301 switch (strtolower($stat)) {
5304 $select[] = "$stat({$field['dbAlias']}) as $alias";
5305 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5306 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5307 $this->_statFields
[$label] = $alias;
5308 $this->_selectAliases
[] = $alias;
5312 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5313 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5314 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5315 $this->_statFields
[$label] = $alias;
5316 $this->_selectAliases
[] = $alias;
5319 case 'count_distinct':
5320 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5321 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5322 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5323 $this->_statFields
[$label] = $alias;
5324 $this->_selectAliases
[] = $alias;
5328 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5329 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5330 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5331 $this->_statFields
[$label] = $alias;
5332 $this->_selectAliases
[] = $alias;
5340 * Add a basic field to the select clause.
5342 * @param string $tableName
5343 * @param string $fieldName
5344 * @param array $field
5345 * @param string $select
5348 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5349 $alias = "{$tableName}_{$fieldName}";
5350 $select[] = "{$field['dbAlias']} as $alias";
5351 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
5352 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
5353 $this->_selectAliases
[] = $alias;
5360 * @param array $table
5361 * @param string $tableName
5366 protected function setTableAlias($table, $tableName) {
5367 if (!isset($table['alias'])) {
5368 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5372 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5375 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5376 return $this->_aliases
[$tableName];
5380 * Function to add columns to reports.
5382 * This is ported from extended reports, which also adds join filters to the options.
5384 * @param string $type
5385 * @param array $options
5386 * - prefix - A string to prepend to the table name
5387 * - prefix_label A string to prepend to the fields
5388 * - fields (bool) - should the fields for this table be made available
5389 * - group_by (bool) - should the group bys for this table be made available.
5390 * - order_by (bool) - should the group bys for this table be made available.
5391 * - filters (bool) - should the filters for this table by made available.
5392 * - fields_defaults (array) array of fields that should be displayed by default.
5393 * - filters_defaults (array) array of fields that should be filtered by default.
5394 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5395 * - join_fields (array) fields available from join (requires additional custom code).
5396 * - group_by_defaults (array) array of group bys that should be applied by default.
5397 * - order_by_defaults (array) array of order bys that should be applied by default.
5398 * - custom_fields (array) array of entity types for custom fields (not usually required).
5399 * - contact_type (string) optional restriction on contact type for some tables.
5400 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5404 protected function getColumns($type, $options = []) {
5407 'prefix_label' => '',
5409 'group_bys' => FALSE,
5410 'order_bys' => TRUE,
5412 'join_filters' => FALSE,
5413 'fields_defaults' => [],
5414 'filters_defaults' => [],
5415 'group_bys_defaults' => [],
5416 'order_bys_defaults' => [],
5418 $options = array_merge($defaultOptions, $options);
5420 $fn = 'get' . $type . 'Columns';
5421 return $this->$fn($options);
5425 * Get columns for contact table.
5427 * @param array $options
5431 protected function getContactColumns($options = []) {
5433 'custom_fields' => CRM_Contact_BAO_ContactType
::basicTypes(),
5434 'fields_defaults' => ['display_name', 'id'],
5435 'order_bys_defaults' => ['sort_name ASC'],
5436 'contact_type' => NULL,
5439 $options = array_merge($defaultOptions, $options);
5441 $tableAlias = $options['prefix'] . 'contact';
5444 $options['prefix'] . 'display_name' => [
5445 'name' => 'display_name',
5446 'title' => $options['prefix_label'] . ts('Contact Name'),
5447 'is_fields' => TRUE,
5449 $options['prefix'] . 'sort_name' => [
5450 'name' => 'sort_name',
5451 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5452 'is_fields' => TRUE,
5453 'is_filters' => TRUE,
5454 'is_order_bys' => TRUE,
5456 $options['prefix'] . 'id' => [
5458 'title' => $options['prefix_label'] . ts('Contact ID'),
5459 'alter_display' => 'alterContactID',
5460 'type' => CRM_Utils_Type
::T_INT
,
5461 'is_order_bys' => TRUE,
5462 'is_group_bys' => TRUE,
5463 'is_fields' => TRUE,
5464 'is_filters' => TRUE,
5466 $options['prefix'] . 'external_identifier' => [
5467 'name' => 'external_identifier',
5468 'title' => $options['prefix_label'] . ts('External ID'),
5469 'type' => CRM_Utils_Type
::T_INT
,
5470 'is_fields' => TRUE,
5472 $options['prefix'] . 'contact_type' => [
5473 'title' => $options['prefix_label'] . ts('Contact Type'),
5474 'name' => 'contact_type',
5475 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5476 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5477 'is_fields' => TRUE,
5478 'is_filters' => TRUE,
5479 'is_group_bys' => TRUE,
5481 $options['prefix'] . 'contact_sub_type' => [
5482 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5483 'name' => 'contact_sub_type',
5484 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5485 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5486 'is_fields' => TRUE,
5487 'is_filters' => TRUE,
5488 'is_group_bys' => TRUE,
5490 $options['prefix'] . 'is_deleted' => [
5491 'title' => $options['prefix_label'] . ts('Is deleted'),
5492 'name' => 'is_deleted',
5493 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5494 'is_fields' => FALSE,
5495 'is_filters' => TRUE,
5496 'is_group_bys' => FALSE,
5498 $options['prefix'] . 'external_identifier' => [
5499 'title' => $options['prefix_label'] . ts('Contact identifier from external system'),
5500 'name' => 'external_identifier',
5501 'is_fields' => TRUE,
5502 'is_filters' => FALSE,
5503 'is_group_bys' => FALSE,
5504 'is_order_bys' => TRUE,
5506 $options['prefix'] . 'preferred_language' => [
5507 'title' => $options['prefix_label'] . ts('Preferred Language'),
5508 'name' => 'preferred_language',
5509 'is_fields' => TRUE,
5510 'is_filters' => TRUE,
5511 'is_group_bys' => TRUE,
5512 'is_order_bys' => TRUE,
5514 $options['prefix'] . 'preferred_communication_method' => [
5515 'title' => $options['prefix_label'] . ts('Preferred Communication Method'),
5516 'alter_display' => 'alterCommunicationtMethod',
5517 'name' => 'preferred_communication_method',
5518 'is_fields' => TRUE,
5519 'is_filters' => FALSE,
5520 'is_group_bys' => FALSE,
5521 'is_order_bys' => FALSE,
5525 'postal_greeting_display' => 'Postal Greeting',
5526 'email_greeting_display' => 'Email Greeting',
5527 'addressee_display' => 'Addressee',
5528 ] as $field => $title) {
5529 $spec[$options['prefix'] . $field] = [
5530 'title' => $options['prefix_label'] . ts($title),
5532 'is_fields' => TRUE,
5533 'is_filters' => FALSE,
5534 'is_group_bys' => FALSE,
5537 foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'do_not_trade', 'is_opt_out'] as $field) {
5538 $spec[$options['prefix'] . $field] = [
5540 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5541 'is_fields' => TRUE,
5542 'is_filters' => TRUE,
5543 'is_group_bys' => FALSE,
5546 $individualFields = [
5547 $options['prefix'] . 'first_name' => [
5548 'name' => 'first_name',
5549 'title' => $options['prefix_label'] . ts('First Name'),
5550 'is_fields' => TRUE,
5551 'is_filters' => TRUE,
5552 'is_order_bys' => TRUE,
5554 $options['prefix'] . 'middle_name' => [
5555 'name' => 'middle_name',
5556 'title' => $options['prefix_label'] . ts('Middle Name'),
5557 'is_fields' => TRUE,
5559 $options['prefix'] . 'last_name' => [
5560 'name' => 'last_name',
5561 'title' => $options['prefix_label'] . ts('Last Name'),
5562 'default_order' => 'ASC',
5563 'is_fields' => TRUE,
5565 $options['prefix'] . 'nick_name' => [
5566 'name' => 'nick_name',
5567 'title' => $options['prefix_label'] . ts('Nick Name'),
5568 'is_fields' => TRUE,
5570 $options['prefix'] . 'prefix_id' => [
5571 'name' => 'prefix_id',
5572 'title' => $options['prefix_label'] . ts('Prefix'),
5573 'options' => CRM_Contact_BAO_Contact
::buildOptions('prefix_id'),
5574 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5575 'is_fields' => TRUE,
5576 'is_filters' => TRUE,
5578 $options['prefix'] . 'suffix_id' => [
5579 'name' => 'suffix_id',
5580 'title' => $options['prefix_label'] . ts('Suffix'),
5581 'options' => CRM_Contact_BAO_Contact
::buildOptions('suffix_id'),
5582 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5583 'is_fields' => TRUE,
5584 'is_filters' => TRUE,
5586 $options['prefix'] . 'gender_id' => [
5587 'name' => 'gender_id',
5588 'title' => $options['prefix_label'] . ts('Gender'),
5589 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5590 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5591 'is_fields' => TRUE,
5592 'is_filters' => TRUE,
5595 'title' => $options['prefix_label'] . ts('Birth Date'),
5596 'operatorType' => CRM_Report_Form
::OP_DATE
,
5597 'type' => CRM_Utils_Type
::T_DATE
,
5598 'is_fields' => TRUE,
5599 'is_filters' => TRUE,
5602 'title' => $options['prefix_label'] . ts('Age'),
5603 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5604 'type' => CRM_Utils_Type
::T_INT
,
5605 'is_fields' => TRUE,
5607 $options['prefix'] . 'is_deceased' => [
5608 'title' => $options['prefix_label'] . ts('Is deceased'),
5609 'name' => 'is_deceased',
5610 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5611 'is_fields' => FALSE,
5612 'is_filters' => TRUE,
5613 'is_group_bys' => FALSE,
5615 $options['prefix'] . 'job_title' => [
5616 'name' => 'job_title',
5617 'is_fields' => TRUE,
5618 'is_filters' => FALSE,
5619 'is_group_bys' => FALSE,
5621 $options['prefix'] . 'employer_id' => [
5622 'title' => $options['prefix_label'] . ts('Current Employer'),
5623 'type' => CRM_Utils_Type
::T_INT
,
5624 'name' => 'employer_id',
5625 'is_fields' => TRUE,
5626 'is_filters' => FALSE,
5627 'is_group_bys' => TRUE,
5630 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5631 $spec = array_merge($spec, $individualFields);
5634 if (!empty($options['custom_fields'])) {
5635 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = [
5636 'extends' => $options['custom_fields'],
5637 'title' => $options['prefix_label'],
5638 'filters' => $options['filters'],
5639 'prefix' => $options['prefix'],
5640 'prefix_label' => $options['prefix_label'],
5644 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5648 * Get address columns to add to array.
5650 * @param array $options
5651 * - prefix Prefix to add to table (in case of more than one instance of the table)
5652 * - prefix_label Label to give columns from this address table instance
5653 * - group_bys enable these fields for group by - default false
5654 * - order_bys enable these fields for order by
5655 * - filters enable these fields for filtering
5657 * @return array address columns definition
5659 protected function getAddressColumns($options = []) {
5662 'prefix_label' => '',
5664 'group_bys' => FALSE,
5665 'order_bys' => TRUE,
5667 'join_filters' => FALSE,
5668 'fields_defaults' => [],
5669 'filters_defaults' => [],
5670 'group_bys_defaults' => [],
5671 'order_bys_defaults' => [],
5674 $options = array_merge($defaultOptions, $options);
5675 $defaults = $this->getDefaultsFromOptions($options);
5676 $tableAlias = $options['prefix'] . 'address';
5679 $options['prefix'] . 'name' => [
5680 'title' => $options['prefix_label'] . ts('Address Name'),
5682 'is_fields' => TRUE,
5684 $options['prefix'] . 'street_number' => [
5685 'name' => 'street_number',
5686 'title' => $options['prefix_label'] . ts('Street Number'),
5688 'is_fields' => TRUE,
5690 $options['prefix'] . 'odd_street_number' => [
5691 'title' => ts('Odd / Even Street Number'),
5692 'name' => 'odd_street_number',
5693 'type' => CRM_Utils_Type
::T_INT
,
5694 'no_display' => TRUE,
5696 'dbAlias' => "({$tableAlias}_civireport.street_number % 2)",
5697 'is_fields' => TRUE,
5698 'is_order_bys' => TRUE,
5700 $options['prefix'] . 'street_name' => [
5701 'name' => 'street_name',
5702 'title' => $options['prefix_label'] . ts('Street Name'),
5704 'is_fields' => TRUE,
5705 'is_filters' => TRUE,
5706 'operator' => 'like',
5707 'is_order_bys' => TRUE,
5709 $options['prefix'] . 'street_address' => [
5710 'title' => $options['prefix_label'] . ts('Street Address'),
5711 'name' => 'street_address',
5712 'is_fields' => TRUE,
5713 'is_filters' => TRUE,
5714 'is_group_bys' => TRUE,
5716 $options['prefix'] . 'supplemental_address_1' => [
5717 'title' => $options['prefix_label'] . ts('Supplementary Address Field 1'),
5718 'name' => 'supplemental_address_1',
5719 'is_fields' => TRUE,
5721 $options['prefix'] . 'supplemental_address_2' => [
5722 'title' => $options['prefix_label'] . ts('Supplementary Address Field 2'),
5723 'name' => 'supplemental_address_2',
5724 'is_fields' => TRUE,
5726 $options['prefix'] . 'supplemental_address_3' => [
5727 'title' => $options['prefix_label'] . ts('Supplementary Address Field 3'),
5728 'name' => 'supplemental_address_3',
5729 'is_fields' => TRUE,
5731 $options['prefix'] . 'street_number' => [
5732 'name' => 'street_number',
5733 'title' => $options['prefix_label'] . ts('Street Number'),
5735 'is_order_bys' => TRUE,
5736 'is_filters' => TRUE,
5737 'is_fields' => TRUE,
5739 $options['prefix'] . 'street_unit' => [
5740 'name' => 'street_unit',
5741 'title' => $options['prefix_label'] . ts('Street Unit'),
5743 'is_fields' => TRUE,
5745 $options['prefix'] . 'city' => [
5746 'title' => $options['prefix_label'] . ts('City'),
5748 'operator' => 'like',
5749 'is_fields' => TRUE,
5750 'is_filters' => TRUE,
5751 'is_group_bys' => TRUE,
5752 'is_order_bys' => TRUE,
5754 $options['prefix'] . 'postal_code' => [
5755 'title' => $options['prefix_label'] . ts('Postal Code'),
5756 'name' => 'postal_code',
5758 'is_fields' => TRUE,
5759 'is_filters' => TRUE,
5760 'is_group_bys' => TRUE,
5761 'is_order_bys' => TRUE,
5763 $options['prefix'] . 'postal_code_suffix' => [
5764 'title' => $options['prefix_label'] . ts('Postal Code Suffix'),
5765 'name' => 'postal_code_suffix',
5767 'is_fields' => TRUE,
5768 'is_filters' => TRUE,
5769 'is_group_bys' => TRUE,
5770 'is_order_bys' => TRUE,
5772 $options['prefix'] . 'county_id' => [
5773 'title' => $options['prefix_label'] . ts('County'),
5774 'alter_display' => 'alterCountyID',
5775 'name' => 'county_id',
5776 'type' => CRM_Utils_Type
::T_INT
,
5777 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5778 'options' => CRM_Core_PseudoConstant
::county(),
5779 'is_fields' => TRUE,
5780 'is_filters' => TRUE,
5781 'is_group_bys' => TRUE,
5783 $options['prefix'] . 'state_province_id' => [
5784 'title' => $options['prefix_label'] . ts('State/Province'),
5785 'alter_display' => 'alterStateProvinceID',
5786 'name' => 'state_province_id',
5787 'type' => CRM_Utils_Type
::T_INT
,
5788 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5789 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5790 'is_fields' => TRUE,
5791 'is_filters' => TRUE,
5792 'is_group_bys' => TRUE,
5794 $options['prefix'] . 'country_id' => [
5795 'title' => $options['prefix_label'] . ts('Country'),
5796 'alter_display' => 'alterCountryID',
5797 'name' => 'country_id',
5798 'is_fields' => TRUE,
5799 'is_filters' => TRUE,
5800 'is_group_bys' => TRUE,
5801 'type' => CRM_Utils_Type
::T_INT
,
5802 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5803 'options' => CRM_Core_PseudoConstant
::country(),
5805 $options['prefix'] . 'location_type_id' => [
5806 'name' => 'location_type_id',
5807 'title' => $options['prefix_label'] . ts('Location Type'),
5808 'type' => CRM_Utils_Type
::T_INT
,
5809 'is_fields' => TRUE,
5810 'alter_display' => 'alterLocationTypeID',
5812 $options['prefix'] . 'id' => [
5813 'title' => $options['prefix_label'] . ts('ID'),
5815 'is_fields' => TRUE,
5817 $options['prefix'] . 'is_primary' => [
5818 'name' => 'is_primary',
5819 'title' => $options['prefix_label'] . ts('Primary Address?'),
5820 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5821 'is_fields' => TRUE,
5824 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5828 * Build the columns.
5830 * The normal report class needs you to remember to do a few things that are often erratic
5832 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5833 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5834 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5835 * means any saved filters / fields on saved report instances. This will mean that matching names from
5836 * different tables may be ambigious, but it will smooth any code transition.
5837 * - note that it assumes the value being passed in is the actual table field name
5839 * 2) set the field & set it to no display if you don't want the field but you might want to use the field in other
5840 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5842 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5843 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5844 * the core classes can start to move towards that.
5846 * @param array $specs
5847 * @param string $tableName
5848 * @param string $daoName
5849 * @param string $tableAlias
5850 * @param array $defaults
5851 * @param array $options
5855 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = [], $options = []) {
5857 $tableAlias = str_replace('civicrm_', '', $tableName);
5859 $types = ['filters', 'group_bys', 'order_bys', 'join_filters'];
5860 $columns = [$tableName => array_fill_keys($types, [])];
5861 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5862 $columns[$tableName]['dao'] = $daoName;
5863 $columns[$tableName]['alias'] = $tableAlias;
5865 foreach ($specs as $specName => $spec) {
5866 if (empty($spec['name'])) {
5867 $spec['name'] = $specName;
5870 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5871 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5872 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5873 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5874 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5877 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5878 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5881 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5882 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5885 foreach ($types as $type) {
5886 if ($options[$type] && !empty($spec['is_' . $type])) {
5887 $columns[$tableName][$type][$fieldAlias] = $spec;
5888 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5889 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5894 if (isset($options['grouping'])) {
5895 $columns[$tableName]['grouping'] = $options['grouping'];
5896 $columns[$tableName]['group_title'] = $options['group_title'] ??
'';
5902 * Store group bys into array - so we can check elsewhere what is grouped.
5904 protected function storeGroupByArray() {
5906 if (empty($this->_params
['group_bys'])
5907 ||
!is_array($this->_params
['group_bys'])) {
5908 $this->_params
['group_bys'] = [];
5911 foreach ($this->_columns
as $tableName => $table) {
5912 $table = $this->_columns
[$tableName];
5913 if (array_key_exists('group_bys', $table)) {
5914 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5915 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5916 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5917 if (!empty($field['chart'])) {
5918 $this->assign('chartSupported', TRUE);
5921 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5922 !empty($this->_params
['group_bys_freq'][$fieldName])
5925 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5927 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5931 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " YEAR({$field['dbAlias']})";
5935 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "YEAR({$field['dbAlias']}), QUARTER({$field['dbAlias']})";
5939 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "YEARWEEK({$field['dbAlias']})";
5943 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_MONTH FROM {$field['dbAlias']})";
5947 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "DATE({$field['dbAlias']})";
5952 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5953 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5964 * @param array $options
5968 protected function getDefaultsFromOptions($options) {
5970 'fields_defaults' => $options['fields_defaults'],
5971 'filters_defaults' => $options['filters_defaults'],
5972 'group_bys_defaults' => $options['group_bys_defaults'],
5973 'order_bys_defaults' => $options['order_bys_defaults'],
5979 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5981 * Full group by mode dictates that a field must either be in the group by function or
5982 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5985 * @param string $tableName
5986 * @param string $fieldName
5987 * @param string $field
5990 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5991 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5992 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5993 $label = $field['title'] ??
NULL;
5994 $alias = $field['tplField'] ??
"{$tableName}_{$fieldName}";
5995 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5996 $this->_selectAliases
[] = $alias;
5997 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5998 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
6000 return "({$field['dbAlias']}) as $alias";
6006 * Generate clause for the selected filter.
6008 * @param array $field
6009 * Field specification
6010 * @param string $fieldName
6014 * Relevant where clause.
6016 protected function generateFilterClause($field, $fieldName) {
6017 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
6018 if (CRM_Utils_Array
::value('operatorType', $field) ==
6019 CRM_Report_Form
::OP_MONTH
6021 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
6022 $value = $this->_params
["{$fieldName}_value"] ??
NULL;
6023 if (is_array($value) && !empty($value)) {
6024 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
6029 $relative = $this->_params
["{$fieldName}_relative"] ??
NULL;
6030 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
6031 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
6032 $fromTime = $this->_params
["{$fieldName}_from_time"] ??
NULL;
6033 $toTime = $this->_params
["{$fieldName}_to_time"] ??
NULL;
6034 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
6038 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
6040 return $this->whereClause($field,
6042 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
6043 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
6044 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
6052 * Retrieve a suitable object from the factory depending on the report
6053 * parameters, which typically might just be dependent on outputMode.
6055 * If there is no suitable output handler, e.g. if outputMode is "copy",
6056 * then this sets it to NULL.
6058 public function setOutputHandler() {
6059 $this->outputHandler
= \Civi\Report\OutputHandlerFactory
::singleton()->create($this);
6063 * Send report by email
6065 public function sendEmail() {
6066 if (empty($this->outputHandler
)) {
6067 // It's possible to end up here with outputMode unset, so we use
6068 // the "print" handler which was the default before, i.e. include
6069 // it as html in the body.
6070 $oldOutputMode = $this->_outputMode ??
NULL;
6071 $this->_outputMode
= 'print';
6072 $this->setOutputHandler();
6073 $this->_outputMode
= $oldOutputMode;
6076 $mailBody = $this->outputHandler
->getMailBody();
6079 $attachmentFileName = $this->outputHandler
->getFileName();
6080 // It's not always in the form of an attachment, e.g. for 'print' the
6081 // output ends up in $mailBody above.
6082 if ($attachmentFileName) {
6083 $fullFilename = CRM_Core_Config
::singleton()->templateCompileDir
. CRM_Utils_File
::makeFileName($attachmentFileName);
6084 file_put_contents($fullFilename, $this->outputHandler
->getOutputString());
6086 'fullPath' => $fullFilename,
6087 'mime_type' => $this->outputHandler
->getMimeType(),
6088 'cleanName' => $attachmentFileName,
6089 'charset' => $this->outputHandler
->getCharset(),
6094 // @todo outputMode doesn't seem to get used by mailReport, which is good
6095 // since it shouldn't have any outputMode-related `if` statements in it.
6096 // Someday could remove the param from the function call.
6097 if (CRM_Report_Utils_Report
::mailReport($mailBody, $this->_id
, $this->_outputMode
, $attachments)) {
6098 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
6101 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');