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'];
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 = [];
281 protected $_limit = NULL;
284 * This can be set to specify a limit to the number of rows
285 * Since it is currently envisaged as part of the api usage it is only being applied
286 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
287 * of the code (see limit() fn.
291 protected $_limitValue = NULL;
294 * This can be set to specify row offset
295 * See notes on _limitValue
299 protected $_offsetValue = NULL;
304 protected $_sections = [];
306 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
309 * Whether to generate absolute URLs (ex: in report emails).
313 public $_absoluteUrl = FALSE;
316 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
320 protected $_storeResultSet = FALSE;
323 * When _storeResultSet Flag is set use this var to store result set in form of array
327 protected $_resultSet = [];
330 * To what frequency group-by a date column
334 protected $_groupByDateFreq = [
336 'YEARWEEK' => 'Week',
337 'QUARTER' => 'Quarter',
342 * Variables to hold the acl inner join and where clause
345 protected $_aclFrom = NULL;
346 protected $_aclWhere = NULL;
349 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
351 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
355 protected $_selectedTables = [];
358 * Array of DAO tables having columns included in WHERE or HAVING clause
362 protected $filteredTables;
365 * Output mode e.g 'print', 'csv', 'pdf'.
369 protected $_outputMode;
372 * Format of any chart in use.
374 * (it's unclear if this could be merged with outputMode at this stage)
380 public $_having = NULL;
381 public $_select = NULL;
382 public $_selectClauses = [];
383 public $_columnHeaders = [];
384 public $_orderBy = NULL;
385 public $_orderByFields = [];
386 public $_orderByArray = [];
388 * Array of clauses to group by.
392 protected $_groupByArray = [];
393 public $_groupBy = NULL;
394 public $_whereClauses = [];
395 public $_havingClauses = [];
398 * DashBoardRowCount Dashboard row count.
402 public $_dashBoardRowCount;
405 * Is this being called without a form controller (ie. the report is being render outside the normal form
406 * - e.g the api is retrieving the rows.
410 public $noController = FALSE;
413 * Variable to hold the currency alias.
417 protected $_currencyColumn = NULL;
422 protected $_interval;
427 protected $_sendmail;
440 * Report description.
444 public $_description;
447 * Is an address field selected.
450 * This was intended to determine if the address table should be joined in
451 * The isTableSelected function is now preferred for this purpose
453 protected $_addressField;
456 * Is an email field selected.
459 * This was intended to determine if the email table should be joined in
460 * The isTableSelected function is now preferred for this purpose
462 protected $_emailField;
465 * Is a phone field selected.
468 * This was intended to determine if the phone table should be joined in
469 * The isTableSelected function is now preferred for this purpose
471 protected $_phoneField;
474 * Create new report instance? (or update existing) on save.
478 protected $_createNew;
481 * When a grand total row has calculated the status we pop it off to here.
483 * This allows us to access it from the stats function and avoid recalculating.
487 protected $rollupRow = [];
490 * Database attributes - character set and collation.
494 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
497 * SQL being run in this report.
499 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
507 * An instruction not to add a Group By.
509 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
511 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
512 * such as in pivot charts when no row header is set
516 protected $noGroupBy = FALSE;
519 * SQL being run in this report as an array.
521 * The sql in the report is stored in this variable in order to be returned to api & test calls.
529 * Tables created for the report that need removal afterwards.
531 * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x']
534 protected $temporaryTables = [];
537 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
540 public $optimisedForOnlyFullGroupBy = TRUE;
543 * Determines which chart types are supported for this report
546 protected $_charts = [];
549 * Get the number of rows to show
552 public function getRowCount(): int {
553 return $this->_rowCount
;
557 * set the number of rows to show
558 * @param $rowCount int
560 public function setRowCount($rowCount): void
{
561 $this->_rowCount
= $rowCount;
567 public function __construct() {
568 parent
::__construct();
570 $this->setRowCount(\Civi
::settings()->get('default_pager_size'));
572 $this->addClass('crm-report-form');
574 if ($this->_tagFilter
) {
575 $this->buildTagFilter();
577 if ($this->_exposeContactID
) {
578 if (array_key_exists('civicrm_contact', $this->_columns
)) {
579 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = [
581 'title' => ts('Contact ID'),
587 if ($this->_groupFilter
) {
588 $this->buildGroupFilter();
591 // Get all custom groups
592 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
594 // Get the custom groupIds for which the user has VIEW permission
595 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
596 // and addCustomDataToColumns() will allow access to all custom groups.
597 $permCustomGroupIds = [];
598 if (!CRM_Core_Permission
::check('access all custom data')) {
599 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
600 // do not allow custom data for reports if user doesn't have
601 // permission to access custom data.
602 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
603 $this->_customGroupExtends
= [];
607 // merge custom data columns to _columns list, if any
608 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
610 // add / modify display columns, filters ..etc
611 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
613 //assign currencyColumn variable to tpl
614 $this->assign('currencyColumn', $this->_currencyColumn
);
618 * Shared pre-process function.
620 * If overriding preProcess function this should still be called.
624 public function preProcessCommon() {
625 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
626 // Ensure smarty variables are assigned here since this function is called from
627 // the report api and the main buildForm is not.
628 self
::$_template->ensureVariablesAreAssigned($this->expectedSmartyVariables
);
629 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
631 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
633 $this->assign('section', $this->_section
);
634 CRM_Core_Region
::instance('page-header')->add([
635 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
637 if (!$this->noController
) {
638 $this->setID($this->get('instanceId'));
641 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
643 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
647 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
648 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
649 if (!isset($_SERVER['QUERY_STRING'])) {
650 // in php 7.4 can do this with less lines with ??=
651 $_SERVER['QUERY_STRING'] = '';
653 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
657 $this->assign('instanceId', $this->_id
);
658 $params = ['id' => $this->_id
];
659 $this->_instanceValues
= [];
660 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
662 $this->_instanceValues
664 if (empty($this->_instanceValues
)) {
665 CRM_Core_Error
::statusBounce("Report could not be loaded.");
667 $this->_title
= $this->_instanceValues
['title'];
668 if (!empty($this->_instanceValues
['permission']) &&
669 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
670 CRM_Core_Permission
::check('administer Reports')
673 CRM_Utils_System
::permissionDenied();
674 CRM_Utils_System
::civiExit();
677 $formValues = $this->_instanceValues
['form_values'] ??
NULL;
679 $this->_formValues
= CRM_Utils_String
::unserialize($formValues);
682 $this->_formValues
= NULL;
685 $this->setOutputMode();
687 if ($this->_outputMode
== 'copy') {
688 $this->_createNew
= TRUE;
689 $this->_params
= $this->_formValues
;
690 $this->_params
['view_mode'] = 'criteria';
691 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', [
692 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
693 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
695 // Do not pass go. Do not collect another chance to re-run the same query.
696 CRM_Report_Form_Instance
::postProcess($this);
699 // lets always do a force if reset is found in the url.
700 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
701 // in the comment line above these 2.
702 if (!empty($_REQUEST['reset'])
703 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), ['save', 'criteria'])) {
708 $this->assign('mode', 'instance');
710 elseif (!$this->noController
) {
711 [$optionValueID, $optionValue] = CRM_Report_Utils_Report
::getValueIDFromUrl();
712 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
713 if (($instanceCount > 0) && $optionValueID) {
714 $this->assign('instanceUrl',
715 CRM_Utils_System
::url('civicrm/report/list',
716 "reset=1&ovid=$optionValueID"
720 if ($optionValueID) {
721 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
725 $this->assign('mode', 'template');
728 // lets display the Report Settings section
729 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
731 // Do not display Report Settings section if administer Reports permission is absent OR
732 // if report instance is reserved and administer reserved reports absent
733 if (!CRM_Core_Permission
::check('administer Reports') ||
734 (!empty($this->_instanceValues
['is_reserved']) &&
735 !CRM_Core_Permission
::check('administer reserved reports'))
737 $this->_instanceForm
= FALSE;
740 $this->assign('criteriaForm', FALSE);
741 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
742 if (CRM_Core_Permission
::check('administer Reports') ||
743 CRM_Core_Permission
::check('access Report Criteria')
745 if (empty($this->_instanceValues
['is_reserved']) ||
746 CRM_Core_Permission
::check('administer reserved reports')
748 $this->assign('criteriaForm', TRUE);
749 $this->_criteriaForm
= TRUE;
753 // Special permissions check for private instance if it's not the current contact instance
755 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
756 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
757 if (!CRM_Core_Permission
::check('access all private reports')) {
758 $this->_instanceForm
= FALSE;
759 $this->assign('criteriaForm', FALSE);
763 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
764 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
765 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
766 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
772 public function addBreadCrumb() {
776 'title' => ts('Report Templates'),
777 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
781 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
785 * Pre process function.
787 * Called prior to build form.
789 public function preProcess() {
790 $this->preProcessCommon();
793 $this->addBreadCrumb();
796 foreach ($this->_columns
as $tableName => $table) {
797 $this->setTableAlias($table, $tableName);
800 // higher preference to bao object
801 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
804 if (method_exists($daoOrBaoName, 'exportableFields')) {
805 $expFields = $daoOrBaoName::exportableFields();
808 $expFields = $daoOrBaoName::export();
812 $doNotCopy = ['required', 'default'];
814 $fieldGroups = ['fields', 'filters', 'group_bys', 'order_bys'];
815 foreach ($fieldGroups as $fieldGrp) {
816 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
817 foreach ($table[$fieldGrp] as $fieldName => $field) {
818 // $name is the field name used to reference the BAO/DAO export fields array
819 $name = $field['name'] ??
$fieldName;
821 // Sometimes the field name key in the BAO/DAO export fields array is
822 // different from the actual database field name.
823 // Unset $field['name'] so that actual database field name can be obtained
824 // from the BAO/DAO export fields array.
825 unset($field['name']);
827 if (array_key_exists($name, $expFields)) {
828 foreach ($doNotCopy as $dnc) {
829 // unset the values we don't want to be copied.
830 unset($expFields[$name][$dnc]);
833 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
836 foreach ($expFields[$name] as $property => $val) {
837 if (!array_key_exists($property, $field)) {
838 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
845 if (!empty($field['no_repeat'])) {
846 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
848 if (!empty($field['no_display'])) {
849 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
852 // set alias = table-name, unless already set
853 $alias = $field['alias'] ??
(
854 $this->_columns
[$tableName]['alias'] ??
$tableName
856 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
858 // set name = fieldName, unless already set
859 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
860 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
863 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
864 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
867 // set dbAlias = alias.name, unless already set
868 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
869 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
871 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
874 // a few auto fills for filters
875 if ($fieldGrp == 'filters') {
876 // fill operator types
877 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
878 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
879 case CRM_Utils_Type
::T_MONEY
:
880 case CRM_Utils_Type
::T_FLOAT
:
881 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
884 case CRM_Utils_Type
::T_INT
:
885 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
888 case CRM_Utils_Type
::T_DATE
:
889 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
892 case CRM_Utils_Type
::T_BOOLEAN
:
893 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
894 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
895 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
906 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
908 // with multiple options operator-type is generally multi-select
909 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
910 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
912 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
919 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
920 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
923 $this->_columns
[$tableName]['metadata'][$fieldName] = array_merge($this->_columns
[$tableName][$fieldGrp][$fieldName], $this->_columns
[$tableName]['metadata'][$fieldName]);
929 // copy filters to a separate handy variable
930 if (array_key_exists('filters', $table)) {
931 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
934 if (array_key_exists('group_bys', $table)) {
935 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
938 if (array_key_exists('fields', $table)) {
939 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
944 $this->setDefaultValues(FALSE);
947 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
948 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
949 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
950 CRM_Report_Utils_Get
::processChart($this->_defaults
);
953 $this->_formValues
= $this->_defaults
;
954 $this->postProcess();
959 * Set default values.
961 * @param bool $freeze
965 public function setDefaultValues($freeze = TRUE) {
968 // FIXME: generalizing form field naming conventions would reduce
969 // Lots of lines below.
970 foreach ($this->_columns
as $tableName => $table) {
971 if (array_key_exists('fields', $table)) {
972 foreach ($table['fields'] as $fieldName => $field) {
973 if (empty($field['no_display'])) {
974 if (!empty($field['required'])) {
976 $this->_defaults
['fields'][$fieldName] = 1;
979 // find element object, so that we could use quickform's freeze method
980 // for required elements
981 $obj = $this->getElementFromGroup("fields", $fieldName);
983 $freezeGroup[] = $obj;
987 elseif (isset($field['default'])) {
988 $this->_defaults
['fields'][$fieldName] = $field['default'];
994 if (array_key_exists('group_bys', $table)) {
995 foreach ($table['group_bys'] as $fieldName => $field) {
996 if (isset($field['default'])) {
997 if (!empty($field['frequency'])) {
998 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
1000 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
1004 if (array_key_exists('filters', $table)) {
1005 foreach ($table['filters'] as $fieldName => $field) {
1006 if (isset($field['default'])) {
1007 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
1009 if (is_array($field['default'])) {
1010 $this->_defaults
["{$fieldName}_from"] = $field['default']['from'] ??
NULL;
1011 $this->_defaults
["{$fieldName}_to"] = $field['default']['to'] ??
NULL;
1012 $this->_defaults
["{$fieldName}_relative"] = 0;
1015 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
1019 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
1020 $this->_defaults
["{$fieldName}_min"] = $field['default']['min'] ??
NULL;
1021 $this->_defaults
["{$fieldName}_max"] = $field['default']['max'] ??
NULL;
1023 $this->_defaults
["{$fieldName}_value"] = $field['default'];
1026 //assign default value as "in" for multiselect
1027 //operator, To freeze the select element
1028 if (CRM_Utils_Array
::value('operatorType', $field) ==
1029 CRM_Report_Form
::OP_MULTISELECT
1031 $this->_defaults
["{$fieldName}_op"] = 'in';
1033 if (CRM_Utils_Array
::value('operatorType', $field) ==
1034 CRM_Report_Form
::OP_ENTITYREF
1036 $this->_defaults
["{$fieldName}_op"] = 'in';
1038 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
1039 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
1041 $this->_defaults
["{$fieldName}_op"] = 'mhas';
1043 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
1044 $this->_defaults
["{$fieldName}_op"] = $op;
1050 empty($this->_formValues
['order_bys']) &&
1051 (array_key_exists('order_bys', $table) &&
1052 is_array($table['order_bys']))
1054 if (!array_key_exists('order_bys', $this->_defaults
)) {
1055 $this->_defaults
['order_bys'] = [];
1057 foreach ($table['order_bys'] as $fieldName => $field) {
1058 if (!empty($field['default']) ||
!empty($field['default_order']) ||
1059 CRM_Utils_Array
::value('default_is_section', $field) ||
1060 !empty($field['default_weight'])
1063 'column' => $fieldName,
1064 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
1065 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
1068 if (!empty($field['default_weight'])) {
1069 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
1072 array_unshift($this->_defaults
['order_bys'], $order_by);
1078 foreach ($this->_options
as $fieldName => $field) {
1079 if (isset($field['default'])) {
1080 $this->_defaults
['options'][$fieldName] = $field['default'];
1085 if (!empty($this->_submitValues
)) {
1086 $this->preProcessOrderBy($this->_submitValues
);
1089 $this->preProcessOrderBy($this->_defaults
);
1092 // lets finish freezing task here itself
1093 if (!empty($freezeGroup)) {
1094 foreach ($freezeGroup as $elem) {
1099 if ($this->_formValues
) {
1100 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1103 if ($this->_instanceValues
) {
1104 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1107 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1109 return $this->_defaults
;
1113 * Get element from group.
1115 * @param string $group
1116 * @param string $grpFieldName
1120 public function getElementFromGroup($group, $grpFieldName) {
1121 $eleObj = $this->getElement($group);
1122 foreach ($eleObj->_elements
as $index => $obj) {
1123 if ($grpFieldName == $obj->_attributes
['name']) {
1131 * Setter for $_params.
1133 * @param array $params
1135 public function setParams($params) {
1136 $this->_params
= $params;
1140 * Getter for $_params.
1142 * @return void|array $params
1144 public function getParams() {
1145 return $this->_params
;
1151 * @param int $instanceID
1153 public function setID($instanceID) {
1154 $this->_id
= $instanceID;
1162 public function getID() {
1167 * Getter for _outputMode
1169 * Note you can implement hook_civicrm_alterReportVar('actions', ...)
1170 * which indirectly allows setting _outputMode if the user chooses
1175 public function getOutputMode():string {
1176 return $this->_outputMode
;
1180 * Getter for report header form field value
1184 public function getReportHeader():string {
1185 return $this->_formValues
['report_header'] ??
'';
1189 * Getter for report footer form field value
1193 public function getReportFooter():string {
1194 return $this->_formValues
['report_footer'] ??
'';
1198 * Setter for $_force.
1200 * @param bool $isForce
1202 public function setForce($isForce) {
1203 $this->_force
= $isForce;
1207 * Setter for $_limitValue.
1209 * @param int $_limitValue
1211 public function setLimitValue($_limitValue) {
1212 $this->_limitValue
= $_limitValue;
1216 * Setter for $_offsetValue.
1218 * @param int $_offsetValue
1220 public function setOffsetValue($_offsetValue) {
1221 $this->_offsetValue
= $_offsetValue;
1225 * Setter for $addPaging.
1227 * @param bool $value
1229 public function setAddPaging($value) {
1230 $this->addPaging
= $value;
1234 * Getter for $_defaultValues.
1238 public function getDefaultValues() {
1239 return $this->_defaults
;
1243 * Remove any temporary tables.
1245 public function cleanUpTemporaryTables() {
1246 foreach ($this->temporaryTables
as $temporaryTable) {
1247 CRM_Core_DAO
::executeQuery('DROP ' . ($temporaryTable['temporary'] ?
'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']);
1252 * Create a temporary table.
1254 * This function creates a table AND adds the details to the developer tab & $this->>temporary tables.
1256 * @param string $identifier
1257 * This is the key that will be used for the table in the temporaryTables property.
1258 * @param string $sql
1259 * Sql select statement or column description (the latter requires the columns flag)
1260 * @param bool $isColumns
1261 * Is the sql describing columns to create (rather than using a select query).
1262 * @param bool $isMemory
1263 * Create a memory table rather than a normal INNODB table.
1267 public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) {
1268 $tempTable = CRM_Utils_SQL_TempTable
::build();
1270 $tempTable->setMemory();
1273 $tempTable->createWithColumns($sql);
1276 $tempTable->createWithQuery($sql);
1278 $name = $tempTable->getName();
1279 // Developers may force tables to be durable to assist in debugging so lets check.
1280 $isNotTrueTemporary = $tempTable->isDurable();
1281 $this->addToDeveloperTab($tempTable->getCreateSql());
1282 $this->temporaryTables
[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name];
1287 * Add columns to report.
1289 public function addColumns() {
1292 foreach ($this->_columns
as $tableName => $table) {
1293 if (array_key_exists('fields', $table)) {
1294 foreach ($table['fields'] as $fieldName => $field) {
1296 if (empty($field['no_display'])) {
1297 foreach (['table', 'field'] as $var) {
1298 if (!empty($
{$var}['grouping'])) {
1299 if (!is_array($
{$var}['grouping'])) {
1300 $tableName = $
{$var}['grouping'];
1303 $tableName = array_keys($
{$var}['grouping']);
1304 $tableName = $tableName[0];
1305 $groupTitle = array_values($
{$var}['grouping']);
1306 $groupTitle = $groupTitle[0];
1311 if (!$groupTitle && isset($table['group_title'])) {
1312 $groupTitle = $table['group_title'];
1313 // Having a group_title is secret code for being a custom group
1314 // which cryptically translates to needing an accordion.
1315 // here we make that explicit.
1316 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1319 $colGroups[$tableName]['fields'][$fieldName] = $field['title'] ??
NULL;
1320 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1321 $colGroups[$tableName]['group_title'] = $groupTitle;
1323 $options[$fieldName] = $field['title'] ??
NULL;
1329 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1330 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1332 if (!empty($colGroups)) {
1333 $this->tabs
['FieldSelection'] = [
1334 'title' => ts('Columns'),
1335 'tpl' => 'FieldSelection',
1336 'div_label' => 'col-groups',
1339 // Note this assignment is only really required in buildForm. It is being 'over-called'
1340 // to reduce risk of being missed due to overridden functions.
1341 $this->assign('tabs', $this->tabs
);
1344 $this->assign('colGroups', $colGroups);
1348 * Add filters to report.
1350 public function addFilters() {
1351 $filters = $filterGroups = [];
1353 foreach ($this->_filters
as $table => $attributes) {
1354 $groupingKey = $this->_columns
[$table]['grouping'] ??
'';
1355 $filterGroups[$groupingKey]['tables'][$table] = [];
1356 // If a prior table hasn't set group title then set it.
1357 if (empty($filterGroups[$groupingKey]['group_title'])) {
1358 $filterGroups[$groupingKey]['group_title'] = $this->_columns
[$table]['group_title'] ??
'';
1360 // The presence of 'group_title' is secret code for 'display in an accordion'
1361 // here we make this explicit.
1362 if (!isset($filterGroups[$groupingKey]['use_accordion_for_field_selection'])) {
1363 if (isset($this->_columns
[$table]['use_accordion_for_field_selection'])) {
1364 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = $this->_columns
[$table]['use_accordion_for_field_selection'];
1367 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = isset($this->_columns
[$table]['group_title']);
1371 foreach ($attributes as $fieldName => $field) {
1372 $filterGroups[$groupingKey]['tables'][$table][$fieldName] = $field;
1373 // Filters is deprecated in favour of filterGroups.
1374 $filters[$table][$fieldName] = $field;
1375 // get ready with option value pair
1376 // @ 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
1378 $operations = $this->getOperationPair(
1379 CRM_Utils_Array
::value('operatorType', $field),
1382 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1383 case CRM_Report_Form
::OP_MONTH
:
1384 if (!array_key_exists('options', $field) ||
1385 !is_array($field['options']) ||
empty($field['options'])
1387 // If there's no option list for this filter, define one.
1388 $field['options'] = CRM_Utils_Date
::getFullMonthNames();
1390 // Add this option list to this column _columns. This is
1391 // required so that filter statistics show properly.
1392 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1394 case CRM_Report_Form
::OP_MULTISELECT
:
1395 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1396 // assume a multi-select field
1397 if (!empty($field['options']) ||
1398 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1400 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1401 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1404 if (count($operations) <= 1) {
1407 if ($fieldName == 'state_province_id' ||
1408 $fieldName == 'county_id'
1410 $this->addChainSelect($fieldName . '_value', [
1417 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], [
1418 'style' => 'min-width:250px',
1419 'class' => 'crm-select2 huge',
1421 'placeholder' => ts('- select -'),
1427 case CRM_Report_Form
::OP_SELECT
:
1428 // assume a select field
1429 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1430 if (!empty($field['options'])) {
1431 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1435 case CRM_Report_Form
::OP_ENTITYREF
:
1436 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1437 $this->setEntityRefDefaults($field, $table);
1438 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1441 case CRM_Report_Form
::OP_DATE
:
1442 // build datetime fields
1443 $this->addDatePickerRange($fieldName, $field['title'], FALSE, FALSE, 'From', 'To', $operations, '_to', '_from');
1446 case CRM_Report_Form
::OP_DATETIME
:
1447 // build datetime fields
1448 $this->addDatePickerRange($fieldName, $field['title'], TRUE, FALSE, 'From', 'To', $operations, '_to', '_from');
1451 case CRM_Report_Form
::OP_INT
:
1452 case CRM_Report_Form
::OP_FLOAT
:
1453 // and a min value input box
1454 $this->add('text', "{$fieldName}_min", ts('Min'));
1455 // and a max value input box
1456 $this->add('text', "{$fieldName}_max", ts('Max'));
1458 // default type is string
1459 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1460 ['onchange' => "return showHideMaxMinVal( '$fieldName', this.value );"]
1462 // we need text box for value input
1463 $this->add('text', "{$fieldName}_value", NULL, ['class' => 'huge']);
1468 if (!empty($filterGroups)) {
1469 $this->tabs
['Filters'] = [
1470 'title' => ts('Filters'),
1472 'div_label' => 'set-filters',
1475 $this->assign('filterGroups', $filterGroups);
1476 // Filters is deprecated in favour of filterGroups.
1477 $this->assign('filters', $filters);
1481 * Function to assign the tabs to the template in the correct order.
1483 * We want the tabs to wind up in this order (if not overridden).
1491 protected function assignTabs() {
1499 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1500 $order = array_merge($order, $this->tabs
);
1501 $this->assign('tabs', $order);
1505 * The intent is to add a tab for developers to view the sql.
1507 * Currently using dpm.
1509 * @param string $sql
1511 public function addToDeveloperTab($sql) {
1512 if (!CRM_Core_Permission
::check('view report sql')) {
1515 $ignored_output_modes = ['pdf', 'csv', 'print'];
1516 if (in_array($this->_outputMode
, $ignored_output_modes)) {
1519 $this->tabs
['Developer'] = [
1520 'title' => ts('Developer'),
1521 'tpl' => 'Developer',
1522 'div_label' => 'set-developer',
1525 $this->assignTabs();
1526 $this->sqlFormattedArray
= [];
1527 $this->sqlArray
[] = $sql;
1528 foreach ($this->sqlArray
as $sql) {
1529 foreach (['LEFT JOIN'] as $term) {
1530 $sql = str_replace($term, '<br> ' . $term, $sql);
1532 foreach (['FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';'] as $term) {
1533 $sql = str_replace($term, '<br><br>' . $term, $sql);
1535 $this->sqlFormattedArray
[] = $sql;
1536 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1538 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL
::getSqlModes());
1543 * Add options defined in $this->_options to the report.
1545 public function addOptions() {
1546 if (!empty($this->_options
)) {
1547 // FIXME: For now lets build all elements as checkboxes.
1548 // Once we clear with the format we can build elements based on type
1550 foreach ($this->_options
as $fieldName => $field) {
1553 if ($field['type'] == 'select') {
1554 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1556 elseif ($field['type'] == 'checkbox') {
1557 $options[$field['title']] = $fieldName;
1558 $this->addCheckBox($fieldName, NULL,
1560 NULL, NULL, NULL, $this->_fourColumnAttribute
1565 if (!empty($this->_options
) &&
1567 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1569 $this->tabs
['ReportOptions'] = [
1570 'title' => ts('Display Options'),
1571 'tpl' => 'ReportOptions',
1572 'div_label' => 'other-options',
1575 $this->assign('otherOptions', $this->_options
);
1579 * Add chart options to the report.
1581 public function addChartOptions() {
1582 if (!empty($this->_charts
)) {
1583 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1584 $this->assign('charts', $this->_charts
);
1585 $this->addElement('xbutton', $this->_chartButtonName
, ts('View'), ['type' => 'submit']);
1590 * Add group by options to the report.
1592 public function addGroupBys() {
1593 $options = $freqElements = [];
1595 foreach ($this->_columns
as $tableName => $table) {
1596 if (array_key_exists('group_bys', $table)) {
1597 foreach ($table['group_bys'] as $fieldName => $field) {
1598 if (!empty($field) && empty($field['no_display'])) {
1599 $options[$field['title']] = $fieldName;
1600 if (!empty($field['frequency'])) {
1601 $freqElements[$field['title']] = $fieldName;
1607 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1608 NULL, NULL, NULL, $this->_fourColumnAttribute
1610 $this->assign('groupByElements', $options);
1611 if (!empty($options)) {
1612 $this->tabs
['GroupBy'] = [
1613 'title' => ts('Grouping'),
1615 'div_label' => 'group-by-elements',
1619 foreach ($freqElements as $name) {
1620 $this->addElement('select', "group_bys_freq[$name]",
1621 ts('Frequency'), $this->_groupByDateFreq
1627 * Add data for order by tab.
1629 public function addOrderBys() {
1631 foreach ($this->_columns
as $tableName => $table) {
1633 // Report developer may define any column to order by; include these as order-by options.
1634 if (array_key_exists('order_bys', $table)) {
1635 foreach ($table['order_bys'] as $fieldName => $field) {
1636 if (!empty($field)) {
1637 $options[$fieldName] = $field['title'];
1642 // Add searchable custom fields as order-by options, if so requested
1643 // (These are already indexed, so allowing to order on them is cheap.)
1645 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1646 array_key_exists('extends', $table) && !empty($table['extends'])
1648 foreach ($table['fields'] as $fieldName => $field) {
1649 if (empty($field['no_display'])) {
1650 $options[$fieldName] = $field['title'];
1658 $this->assign('orderByOptions', $options);
1659 if (!empty($options)) {
1660 $this->tabs
['OrderBy'] = [
1661 'title' => ts('Sorting'),
1663 'div_label' => 'order-by-elements',
1667 if (!empty($options)) {
1669 '-' => ts(' - none - '),
1671 for ($i = 1; $i <= 5; $i++
) {
1672 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1673 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
1674 'ASC' => ts('Ascending'),
1675 'DESC' => ts('Descending'),
1677 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, ['id' => "order_by_section_$i"]);
1678 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, ['id' => "order_by_pagebreak_$i"]);
1684 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1686 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1687 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1690 public function buildInstanceAndButtons() {
1691 CRM_Report_Form_Instance
::buildForm($this);
1692 $this->_actionButtonName
= $this->getButtonName('submit');
1693 $this->addTaskMenu($this->getActions($this->_id
));
1695 $this->assign('instanceForm', $this->_instanceForm
);
1697 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1698 $permission = CRM_Core_Permission
::getPermission();
1699 if ($this->_instanceForm
&& $permission == CRM_Core_Permission
::EDIT
&&
1700 $this->_add2groupSupported
1702 $this->addElement('select', 'groups', ts('Group'),
1703 ['' => ts('Add Contacts to Group')] +
1704 CRM_Core_PseudoConstant
::nestedGroup(),
1705 ['class' => 'crm-select2 crm-action-menu fa-plus huge']
1707 $this->assign('group', TRUE);
1710 $this->addElement('xbutton', $this->_groupButtonName
, '', [
1712 'style' => 'display: none;',
1715 $this->addChartOptions();
1716 $showResultsLabel = $this->getResultsLabel();
1720 'name' => $showResultsLabel,
1721 'isDefault' => TRUE,
1727 * Has this form been submitted already?
1731 public function resultsDisplayed() {
1732 $buttonName = $this->controller
->getButtonName();
1733 return ($buttonName ||
$this->_outputMode
);
1737 * Get the actions for this report instance.
1739 * @param int $instanceId
1743 protected function getActions($instanceId) {
1744 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1745 if (empty($instanceId)) {
1746 $actions['report_instance.save'] = [
1747 'title' => ts('Create Report'),
1749 'is_confirm' => TRUE,
1750 'confirm_title' => ts('Create Report'),
1751 'confirm_refresh_fields' => json_encode([
1752 'title' => ['selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''],
1753 'description' => ['selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''],
1757 unset($actions['report_instance.delete']);
1760 if (!$this->_csvSupported
) {
1761 unset($actions['report_instance.csv']);
1764 CRM_Utils_Hook
::alterReportVar('actions', $actions, $this);
1770 * Main build form function.
1772 public function buildQuickForm() {
1773 $this->addColumns();
1775 $this->addFilters();
1777 $this->addOptions();
1779 $this->addGroupBys();
1781 $this->addOrderBys();
1783 $this->buildInstanceAndButtons();
1785 // Add form rule for report.
1790 $this->addFormRule([get_class($this), 'formRule'], $this);
1792 $this->assignTabs();
1796 * A form rule function for custom data.
1798 * The rule ensures that fields selected in group_by if any) should only be the ones
1799 * present in display/select fields criteria;
1800 * note: works if and only if any custom field selected in group_by.
1802 * @param array $fields
1803 * @param array $ignoreFields
1807 public function customDataFormRule($fields, $ignoreFields = []) {
1809 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1810 !empty($fields['group_bys'])
1812 foreach ($this->_columns
as $tableName => $table) {
1813 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1814 substr($tableName, 0, 12) == 'custom_value') &&
1815 !empty($this->_columns
[$tableName]['fields'])
1817 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1818 if (array_key_exists($fieldName, $fields['group_bys']) &&
1819 !array_key_exists($fieldName, $fields['fields'])
1821 $errors['fields'] = ts("Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.");
1823 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1824 foreach ($fields['fields'] as $fld => $val) {
1825 if (!array_key_exists($fld, $fields['group_bys']) &&
1826 !in_array($fld, $ignoreFields)
1828 $errors['fields'] = ts("Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.");
1840 * Get operators to display on form.
1842 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1844 * @param string $type
1845 * @param string $fieldName
1849 public function getOperationPair($type = "string", $fieldName = NULL) {
1850 // FIXME: At some point we should move these key-val pairs
1851 // to option_group and option_value table.
1853 case CRM_Report_Form
::OP_INT
:
1854 case CRM_Report_Form
::OP_FLOAT
:
1857 'lte' => ts('Is less than or equal to'),
1858 'gte' => ts('Is greater than or equal to'),
1859 'bw' => ts('Is between'),
1860 'eq' => ts('Is equal to'),
1861 'lt' => ts('Is less than'),
1862 'gt' => ts('Is greater than'),
1863 'neq' => ts('Is not equal to'),
1864 'nbw' => ts('Is not between'),
1865 'nll' => ts('Is empty (Null)'),
1866 'nnll' => ts('Is not empty (Null)'),
1870 case CRM_Report_Form
::OP_SELECT
:
1872 'eq' => ts('Is equal to'),
1876 case CRM_Report_Form
::OP_MONTH
:
1877 case CRM_Report_Form
::OP_MULTISELECT
:
1878 case CRM_Report_Form
::OP_ENTITYREF
:
1881 'in' => ts('Is one of'),
1882 'notin' => ts('Is not one of'),
1883 'nll' => ts('Is empty (Null)'),
1884 'nnll' => ts('Is not empty (Null)'),
1888 case CRM_Report_Form
::OP_DATE
:
1891 'nll' => ts('Is empty (Null)'),
1892 'nnll' => ts('Is not empty (Null)'),
1896 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1897 // use this operator for the values, concatenated with separator. For e.g if
1898 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1900 'mhas' => ts('Is one of'),
1901 'mnot' => ts('Is not one of'),
1902 'nll' => ts('Is empty (Null)'),
1903 'nnll' => ts('Is not empty (Null)'),
1910 'has' => ts('Contains'),
1911 'sw' => ts('Starts with'),
1912 'ew' => ts('Ends with'),
1913 'nhas' => ts('Does not contain'),
1914 'eq' => ts('Is equal to'),
1915 'neq' => ts('Is not equal to'),
1916 'nll' => ts('Is empty (Null)'),
1917 'nnll' => ts('Is not empty (Null)'),
1924 * Build the tag filter field to display on the filters tab.
1926 public function buildTagFilter() {
1927 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1928 if (!empty($contactTags)) {
1929 $this->_columns
['civicrm_tag'] = [
1930 'dao' => 'CRM_Core_DAO_Tag',
1934 'title' => ts('Tag'),
1935 'type' => CRM_Utils_Type
::T_INT
,
1937 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1938 'options' => $contactTags,
1946 * Adds group filters to _columns (called from _Construct).
1948 public function buildGroupFilter() {
1949 $this->_columns
['civicrm_group']['filters'] = [
1951 'name' => 'group_id',
1952 'title' => ts('Group'),
1953 'type' => CRM_Utils_Type
::T_INT
,
1954 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1956 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1959 if (empty($this->_columns
['civicrm_group']['dao'])) {
1960 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1962 if (empty($this->_columns
['civicrm_group']['alias'])) {
1963 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1968 * Get SQL operator from form text version.
1970 * @param string $operator
1974 public function getSQLOperator($operator = "like") {
1975 switch ($operator) {
2008 return 'IS NOT NULL';
2017 * Generate where clause.
2019 * This can be overridden in reports for special treatment of a field
2021 * @param array $field Field specifications
2022 * @param string $op Query operator (not an exact match to sql)
2023 * @param mixed $value
2027 * @return null|string
2029 public function whereClause(&$field, $op, $value, $min, $max) {
2031 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
2033 // CRM-18010: Ensure type of each report filters
2035 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
2042 if (($min !== NULL && strlen($min) > 0) ||
2043 ($max !== NULL && strlen($max) > 0)
2047 $min = CRM_Utils_Type
::escape($min, $type);
2049 $clauses[] = "( {$field['dbAlias']} >= $min )";
2052 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
2056 $max = CRM_Utils_Type
::escape($max, $type);
2058 $clauses[] = "( {$field['dbAlias']} <= $max )";
2061 $clauses[] = "( {$field['dbAlias']} > $max )";
2065 if (!empty($clauses)) {
2067 $clause = implode(' AND ', $clauses);
2070 $clause = '(' . implode('OR', $clauses) . ')';
2078 if ($value !== NULL && strlen($value) > 0) {
2079 $value = CRM_Utils_Type
::escape($value, $type);
2080 if (strpos($value, '%') === FALSE) {
2081 $value = "'%{$value}%'";
2084 $value = "'{$value}'";
2086 $sqlOP = $this->getSQLOperator($op);
2087 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2093 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
2094 $value = explode(',', $value);
2096 if ($value !== NULL && is_array($value) && count($value) > 0) {
2097 $sqlOP = $this->getSQLOperator($op);
2098 if (CRM_Utils_Array
::value('type', $field) ==
2099 CRM_Utils_Type
::T_STRING
2101 //cycle through selections and escape values
2102 foreach ($value as $key => $selection) {
2103 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
2106 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
2110 // for numerical values
2111 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
2114 if ($op == 'notin') {
2115 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
2118 $clause = "( " . $clause . " )";
2125 // multiple has or multiple not
2126 if ($value !== NULL && count($value) > 0) {
2127 $value = CRM_Utils_Type
::escapeAll($value, $type);
2128 $operator = $op == 'mnot' ?
'NOT' : '';
2129 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2130 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2136 if ($value !== NULL && strlen($value) > 0) {
2137 $value = CRM_Utils_Type
::escape($value, $type);
2138 if (strpos($value, '%') === FALSE) {
2140 $value = "'{$value}%'";
2143 $value = "'%{$value}'";
2147 $value = "'{$value}'";
2149 $sqlOP = $this->getSQLOperator($op);
2150 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2155 if ($type == 'String') {
2156 $sqlOP = $this->getSQLOperator($op);
2157 $clause = "( {$field['dbAlias']} $sqlOP OR {$field['dbAlias']} = '' )";
2160 $sqlOP = $this->getSQLOperator($op);
2161 $clause = "( {$field['dbAlias']} $sqlOP )";
2166 if ($type == 'String') {
2167 $sqlOP = $this->getSQLOperator($op);
2168 $clause = "( {$field['dbAlias']} $sqlOP AND {$field['dbAlias']} <> '' )";
2171 $sqlOP = $this->getSQLOperator($op);
2172 $clause = "( {$field['dbAlias']} $sqlOP )";
2179 //CRM-18457: some custom field passes value in array format against binary operator
2180 if (is_array($value) && count($value)) {
2185 if ($value !== NULL && $value !== '') {
2186 if (isset($field['clause'])) {
2187 // FIXME: we not doing escape here. Better solution is to use two
2188 // different types - data-type and filter-type
2189 $clause = $field['clause'];
2191 elseif (!is_array($value)) {
2192 $value = CRM_Utils_Type
::escape($value, $type);
2193 $sqlOP = $this->getSQLOperator($op);
2194 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
2195 $value = "'{$value}'";
2197 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2203 //dev/core/544 Add report support for multiple contact subTypes
2204 if ($field['name'] == 'contact_sub_type' && $clause) {
2205 $clause = $this->whereSubtypeClause($field, $value, $op);
2207 if (!empty($field['group']) && $clause) {
2208 $clause = $this->whereGroupClause($field, $value, $op);
2210 elseif (!empty($field['tag']) && $clause) {
2211 // not using left join in query because if any contact
2212 // belongs to more than one tag, results duplicate
2214 $clause = $this->whereTagClause($field, $value, $op);
2216 elseif (!empty($field['membership_org']) && $clause) {
2217 $clause = $this->whereMembershipOrgClause($value, $op);
2219 elseif (!empty($field['membership_type']) && $clause) {
2220 $clause = $this->whereMembershipTypeClause($value, $op);
2226 * Get SQL where clause for contact subtypes
2227 * @param string $field
2228 * @param mixed $value
2229 * @param string $op SQL Operator
2233 public function whereSubtypeClause($field, $value, $op) {
2234 // Get the correct SQL operator.
2239 $clauseSeparator = ' AND ';
2245 $clauseSeparator = ' OR ';
2248 $sqlOp = $this->getSQLOperator($op);
2249 if ($sqlOp == 'IS NULL' ||
$sqlOp == 'IS NOT NULL') {
2250 $clause = "{$field['dbAlias']} $sqlOp";
2254 foreach ($value as $item) {
2255 $subclauses[] = "( {$field['dbAlias']} $sqlOp '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $item . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' )";
2257 $clause = implode($clauseSeparator, $subclauses);
2259 $clause = "( $clause )";
2261 $clause = "( ( {$field['dbAlias']} IS NULL ) OR $clause )";
2267 * Get SQL where clause for a date field.
2269 * @param string $fieldName
2270 * @param string $relative
2271 * @param string $from
2273 * @param string $type
2274 * @param string $fromTime
2275 * @param string $toTime
2277 * @return null|string
2279 public function dateClause(
2281 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2284 if (array_key_exists($relative, $this->getOperationPair(CRM_Report_Form
::OP_DATE
))) {
2285 $sqlOP = $this->getSQLOperator($relative);
2286 return "( {$fieldName} {$sqlOP} )";
2288 if (strlen($to) === 10) {
2289 // If we just have the date we assume the end of that day.
2294 [$from, $to] = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2298 $clauses[] = "( {$fieldName} >= " . date('YmdHis', strtotime($from)) . ')';
2302 $clauses[] = "( {$fieldName} <= " . date('YmdHis', strtotime($to)) . ')';
2304 if (!empty($clauses)) {
2305 return implode(' AND ', $clauses);
2312 * Get values for from and to for date ranges.
2316 * @param bool $relative
2317 * @param string $from
2319 * @param string $fromTime
2320 * @param string $toTime
2324 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2325 if (!empty($fromTime) ||
!empty($toTime)) {
2326 throw new CRM_Core_Exception('Report template needs to be updated as getFromTo no longer supports fromTime or ToTime Parameters');
2328 return CRM_Utils_Date
::getFromTo($relative, $from, $to);
2332 * Alter display of rows.
2334 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2335 * such as rendering contacts as links.
2337 * @param array $rows
2338 * Rows generated by SQL, with an array for each row.
2340 public function alterDisplay(&$rows) {
2344 * Alter the way in which custom data fields are displayed.
2346 * @param array $rows
2348 public function alterCustomDataDisplay(&$rows) {
2349 // custom code to alter rows having custom values
2350 if (empty($this->_customGroupExtends
)) {
2355 $customFieldIds = [];
2356 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2357 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2358 $customFieldIds[$fieldAlias] = $fieldId;
2361 if (empty($customFieldIds)) {
2365 // skip for type date and ContactReference since date format is already handled
2367 SELECT cg.table_name, cf.id
2368 FROM civicrm_custom_field cf
2369 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2370 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2371 cg.is_active = 1 AND
2372 cf.is_active = 1 AND
2373 cf.is_searchable = 1 AND
2374 cf.data_type NOT IN ('ContactReference', 'Date') AND
2375 cf.id IN (" . implode(",", $customFieldIds) . ")";
2377 $dao = CRM_Core_DAO
::executeQuery($query);
2378 while ($dao->fetch()) {
2379 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2382 $entryFound = FALSE;
2383 foreach ($rows as $rowNum => $row) {
2384 foreach ($row as $tableCol => $val) {
2385 if (array_key_exists($tableCol, $customFields)) {
2386 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2391 // skip looking further in rows, if first row itself doesn't
2392 // have the column we need
2400 * Remove duplicate rows.
2402 * @param array $rows
2404 public function removeDuplicates(&$rows) {
2405 if (empty($this->_noRepeats
)) {
2410 foreach ($rows as $key => $list) {
2411 foreach ($list as $colName => $colVal) {
2412 if (array_key_exists($colName, $checkList) &&
2413 $checkList[$colName] == $colVal
2415 $rows[$key][$colName] = "";
2417 if (in_array($colName, $this->_noRepeats
)) {
2418 $checkList[$colName] = $colVal;
2425 * Fix subtotal display.
2428 * @param array $fields
2429 * @param bool $subtotal
2431 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2432 foreach ($row as $colName => $colVal) {
2433 if (in_array($colName, $fields)) {
2435 elseif (isset($this->_columnHeaders
[$colName])) {
2437 $row[$colName] = 'Subtotal';
2441 unset($row[$colName]);
2448 * Calculate grant total.
2450 * @param array $rows
2454 public function grandTotal(&$rows) {
2455 if (!$this->_rollup ||
count($rows) == 1) {
2459 $this->moveSummaryColumnsToTheRightHandSide();
2461 if ($this->_limit
&& count($rows) >= $this->getRowCount()) {
2465 $this->rollupRow
= array_pop($rows);
2467 foreach ($this->_columnHeaders
as $fld => $val) {
2468 if (!in_array($fld, $this->_statFields
)) {
2469 if (!$this->_grandFlag
) {
2470 $this->rollupRow
[$fld] = ts('Grand Total');
2471 $this->_grandFlag
= TRUE;
2474 $this->rollupRow
[$fld] = "";
2479 $this->assign('grandStat', $this->rollupRow
);
2484 * Format display output.
2486 * @param array $rows
2487 * @param bool $pager
2489 public function formatDisplay(&$rows, $pager = TRUE) {
2490 // set pager based on if any limit was applied in the query.
2494 $chartEnabled = !empty($this->_params
['charts']) && !empty($rows);
2495 $this->assign('chartEnabled', $chartEnabled);
2496 // allow building charts if any
2497 if ($chartEnabled) {
2498 $this->buildChart($rows);
2499 $this->_chartId
= "{$this->_params['charts']}_" .
2500 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2501 CRM_Core_Config
::singleton()->userSystem
->getSessionId();
2502 $this->assign('chartId', $this->_chartId
);
2505 // unset columns not to be displayed.
2506 foreach ($this->_columnHeaders
as $key => $value) {
2507 if (!empty($value['no_display'])) {
2508 unset($this->_columnHeaders
[$key]);
2510 foreach (['colspan', 'type'] as $expectedKey) {
2511 if (!isset($this->_columnHeaders
[$key][$expectedKey])) {
2512 // Ensure it is set to prevent smarty notices.
2513 $this->_columnHeaders
[$key][$expectedKey] = FALSE;
2518 // unset columns not to be displayed.
2519 if (!empty($rows)) {
2520 foreach ($this->_noDisplay
as $noDisplayField) {
2521 foreach ($rows as $rowNum => $row) {
2522 unset($this->_columnHeaders
[$noDisplayField]);
2523 $expectedKeys = ['class'];
2524 foreach ($expectedKeys as $expectedKey) {
2525 if (!array_key_exists($expectedKey, $row)) {
2526 $rows[$rowNum][$expectedKey] = NULL;
2533 // Find alter display functions.
2534 $firstRow = reset($rows);
2536 $selectedFields = array_keys($firstRow);
2537 $alterFunctions = $alterMap = $alterSpecs = [];
2538 foreach ($this->_columns
as $tableName => $table) {
2539 if (array_key_exists('metadata', $table)) {
2540 foreach ($table['metadata'] as $field => $specs) {
2541 if (in_array($tableName . '_' . $field, $selectedFields)) {
2542 if (array_key_exists('alter_display', $specs)) {
2543 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2544 $alterMap[$tableName . '_' . $field] = $field;
2545 $alterSpecs[$tableName . '_' . $field] = NULL;
2547 // Add any alters that can be intuited from the field specs.
2548 // So far only boolean but a lot more could be.
2549 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2550 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2551 $alterMap[$tableName . '_' . $field] = $field;
2552 $alterSpecs[$tableName . '_' . $field] = NULL;
2559 // Run the alter display functions
2560 foreach ($rows as $index => & $row) {
2561 foreach ($row as $selectedField => $value) {
2562 if (array_key_exists($selectedField, $alterFunctions) && isset($value)) {
2563 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2569 // use this method for formatting rows for display purpose.
2570 $this->alterDisplay($rows);
2571 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2573 // build array of section totals
2574 $this->sectionTotals();
2576 // process grand-total row
2577 $this->grandTotal($rows);
2579 // use this method for formatting custom rows for display purpose.
2580 $this->alterCustomDataDisplay($rows);
2586 * @param $selectedfield
2587 * @param $criteriaFieldName
2591 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2592 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2593 $row[$selectedfield . '_link'] = $url;
2594 $row[$selectedfield . '_hover'] = ts("%1 for this state.", [
2598 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2599 if (!is_array($states)) {
2607 * @param $selectedField
2608 * @param $criteriaFieldName
2612 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2613 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2614 $row[$selectedField . '_link'] = $url;
2615 $row[$selectedField . '_hover'] = ts("%1 for this country.", [
2618 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2619 if (!is_array($countries)) {
2627 * @param $selectedfield
2628 * @param $criteriaFieldName
2632 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2633 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2634 $row[$selectedfield . '_link'] = $url;
2635 $row[$selectedfield . '_hover'] = ts("%1 for this county.", [
2638 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2639 if (!is_array($counties)) {
2647 * @param $selectedfield
2648 * @param $criteriaFieldName
2652 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2653 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value);
2663 protected function alterContactID($value, &$row, $fieldname) {
2664 $nameField = substr($fieldname, 0, -2) . 'name';
2665 static $first = TRUE;
2666 static $viewContactList = FALSE;
2668 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2671 if (!$viewContactList) {
2674 if (array_key_exists($nameField, $row)) {
2675 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2678 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2690 protected function alterCommunicationtMethod($value, &$row, $fieldname) {
2691 $communicationMethods = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
2693 // Explode padded values.
2694 $values = CRM_utils_array
::explodePadded($value);
2695 // Flip values, compute intersection with $communicationMethods, and implode with commas.
2696 $value = implode(', ', array_intersect_key($communicationMethods, array_flip($values)));
2705 protected function alterBoolean($value) {
2706 $options = [0 => '', 1 => ts('Yes')];
2707 if (isset($options[$value])) {
2708 return $options[$value];
2716 * @param array $rows
2718 public function buildChart(&$rows) {
2719 // override this method for building charts.
2722 // select() method below has been added recently (v3.3), and many of the report templates might
2723 // still be having their own select() method. We should fix them as and when encountered and move
2724 // towards generalizing the select() method below.
2727 * Generate the SELECT clause and set class variable $_select.
2729 public function select() {
2730 $select = $this->_selectAliases
= [];
2731 $this->storeGroupByArray();
2733 foreach ($this->_columns
as $tableName => $table) {
2734 if (array_key_exists('fields', $table)) {
2735 foreach ($table['fields'] as $fieldName => $field) {
2736 if ($tableName == 'civicrm_address') {
2737 // deprecated, use $this->isTableSelected.
2738 $this->_addressField
= TRUE;
2740 if ($tableName == 'civicrm_email') {
2741 $this->_emailField
= TRUE;
2743 if ($tableName == 'civicrm_phone') {
2744 $this->_phoneField
= TRUE;
2747 if (!empty($field['required']) ||
2748 !empty($this->_params
['fields'][$fieldName])
2751 // 1. In many cases we want select clause to be built in slightly different way
2752 // for a particular field of a particular type.
2753 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2755 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2756 if ($selectClause) {
2757 $select[] = $selectClause;
2761 // include statistics columns only if set
2762 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2763 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2767 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2768 if ($selectClause) {
2769 $select[] = $selectClause;
2772 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2779 // select for group bys
2780 if (array_key_exists('group_bys', $table)) {
2781 foreach ($table['group_bys'] as $fieldName => $field) {
2783 if ($tableName == 'civicrm_address') {
2784 $this->_addressField
= TRUE;
2786 if ($tableName == 'civicrm_email') {
2787 $this->_emailField
= TRUE;
2789 if ($tableName == 'civicrm_phone') {
2790 $this->_phoneField
= TRUE;
2792 // 1. In many cases we want select clause to be built in slightly different way
2793 // for a particular field of a particular type.
2794 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2796 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2797 if ($selectClause) {
2798 $select[] = $selectClause;
2802 if (!empty($this->_params
['group_bys']) &&
2803 !empty($this->_params
['group_bys'][$fieldName]) &&
2804 !empty($this->_params
['group_bys_freq'])
2806 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2808 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2809 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2810 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2811 $field['title'] = 'Week';
2815 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2816 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2817 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2818 $field['title'] = 'Year';
2822 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2823 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2824 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2825 $field['title'] = 'Month';
2829 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2830 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2831 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2832 $field['title'] = 'Quarter';
2835 // for graphs and charts -
2836 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2837 $this->_interval
= $field['title'];
2838 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2839 = $field['title'] . ' Beginning';
2840 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2841 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2843 // just to make sure these values are transferred to rows.
2844 // since we 'll need them for calculation purpose,
2845 // e.g making subtotals look nicer or graphs
2846 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
2847 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
2854 if (empty($select)) {
2855 // CRM-21412 Do not give fatal error on report when no fields selected
2859 $this->_selectClauses
= $select;
2860 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2864 * Build select clause for a single field.
2866 * @param string $tableName
2867 * @param string $tableKey
2868 * @param string $fieldName
2869 * @param string $field
2873 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2874 if (!empty($field['pseudofield'])) {
2875 $alias = "{$tableName}_{$fieldName}";
2876 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
2877 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
2878 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = $field['dbAlias'] ??
NULL;
2879 $this->_selectAliases
[] = $alias;
2880 return ' 1 as ' . $alias;
2886 * Build where clause.
2888 public function where() {
2889 $this->storeWhereHavingClauseArray();
2891 if (empty($this->_whereClauses
)) {
2892 $this->_where
= "WHERE ( 1 ) ";
2893 $this->_having
= "";
2896 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2899 if ($this->_aclWhere
) {
2900 $this->_where
.= " AND {$this->_aclWhere} ";
2903 if (!empty($this->_havingClauses
)) {
2904 // use this clause to construct group by clause.
2905 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2910 * Store Where clauses into an array.
2912 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2913 * temp table that may not be part of the final where clause or added
2914 * in other functions
2916 public function storeWhereHavingClauseArray() {
2917 foreach ($this->_columns
as $tableName => $table) {
2918 if (array_key_exists('filters', $table)) {
2919 foreach ($table['filters'] as $fieldName => $field) {
2920 // respect pseudofield to filter spec so fields can be marked as
2921 // not to be handled here
2922 if (!empty($field['pseudofield'])) {
2925 $clause = $this->generateFilterClause($field, $fieldName);
2927 if (!empty($clause)) {
2928 if (!empty($field['having'])) {
2929 $this->_havingClauses
[] = $clause;
2932 $this->_whereClauses
[] = $clause;
2944 public function processReportMode() {
2945 $this->setOutputMode();
2948 = CRM_Utils_Request
::retrieve(
2951 CRM_Core_DAO
::$_nullObject
2954 if ($this->_sendmail
&& !$this->_outputMode
) {
2955 // If we're here from the mail_report job, then the default there gets
2956 // set to pdf before we get here, but if we're somehow here and sending
2957 // by email and don't have a format set, then use print.
2958 // @todo Is this on purpose - why would they be different defaults?
2959 $this->_outputMode
= 'print';
2962 // _outputMode means multiple things and can cover export to file formats,
2963 // like csv, or actions with no output, like save. So this will only set
2964 // a handler if it's one of the former. But it's also possible we have a
2965 // really interesting handler out there. But the point is we don't need to
2966 // know, just to know that a handler doesn't always get set by this call.
2967 $this->setOutputHandler();
2969 if (!empty($this->outputHandler
)) {
2970 if ($this->_sendmail
) {
2971 // If we're sending by email these are the only options that make
2973 $this->printOnly
= TRUE;
2974 $this->addPaging
= FALSE;
2975 $this->_absoluteUrl
= TRUE;
2978 // otherwise ask the handler
2979 $this->printOnly
= $this->outputHandler
->isPrintOnly();
2980 $this->addPaging
= $this->outputHandler
->isAddPaging();
2981 $this->_absoluteUrl
= $this->outputHandler
->isAbsoluteUrl();
2984 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2985 $this->_createNew
= TRUE;
2988 $this->assign('outputMode', $this->_outputMode
);
2989 $this->assign('printOnly', $this->printOnly
);
2990 // Get today's date to include in printed reports
2991 if ($this->printOnly
) {
2992 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2993 $this->assign('reportDate', $reportDate);
2998 * Post Processing function for Form.
3000 * postProcessCommon should be used to set other variables from input as the api accesses that function.
3001 * This function is not accessed when the api calls the report.
3003 public function beginPostProcess() {
3004 $this->setParams($this->controller
->exportValues($this->_name
));
3005 if (empty($this->_params
) &&
3008 $this->setParams($this->_formValues
);
3011 // hack to fix params when submitted from dashboard, CRM-8532
3012 // fields array is missing because form building etc is skipped
3013 // in dashboard mode for report
3014 //@todo - this could be done in the dashboard no we have a setter
3015 if (empty($this->_params
['fields']) && !$this->_noFields
) {
3016 $this->setParams($this->_formValues
);
3019 $this->processReportMode();
3021 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
3022 $this->_createNew
= ($this->_outputMode
== 'copy');
3023 CRM_Report_Form_Instance
::postProcess($this);
3025 if ($this->_outputMode
== 'delete') {
3026 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
3029 $this->_formValues
= $this->_params
;
3031 $this->beginPostProcessCommon();
3035 * BeginPostProcess function run in both report mode and non-report mode (api).
3037 public function beginPostProcessCommon() {
3041 * Build the report query.
3043 * @param bool $applyLimit
3047 public function buildQuery($applyLimit = TRUE) {
3048 $this->buildGroupTempTable();
3051 $this->customDataFrom();
3052 $this->buildPermissionClause();
3057 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
3058 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
3060 $clause = "{$field['dbAlias']} as {$alias}";
3062 $this->_select
.= ", $clause ";
3065 if ($applyLimit && empty($this->_params
['charts'])) {
3068 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
3070 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
3071 $this->addToDeveloperTab($sql);
3076 * Build group by clause.
3078 public function groupBy() {
3079 $this->storeGroupByArray();
3081 if (!empty($this->_groupByArray
)) {
3082 if ($this->optimisedForOnlyFullGroupBy
) {
3083 // We should probably deprecate this code path. What happens here is that
3084 // the group by is amended to reflect the select columns. This often breaks the
3085 // results. Retrofitting group strict group by onto existing report classes
3087 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
3090 $this->_groupBy
= ' GROUP BY ' . implode($this->_groupByArray
);
3096 * Build order by clause.
3098 public function orderBy() {
3099 $this->_orderBy
= "";
3100 $this->_sections
= [];
3101 $this->storeOrderByArray();
3102 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
3103 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
3105 $this->assign('sections', $this->_sections
);
3109 * Extract order by fields and store as an array.
3111 * In some cases other functions want to know which fields are selected for ordering by
3112 * Separating this into a separate function allows it to be called separately from constructing
3113 * the order by clause
3115 public function storeOrderByArray() {
3118 if (!empty($this->_params
['order_bys']) &&
3119 is_array($this->_params
['order_bys']) &&
3120 !empty($this->_params
['order_bys'])
3123 // Process order_bys in user-specified order
3124 foreach ($this->_params
['order_bys'] as $orderBy) {
3126 foreach ($this->_columns
as $tableName => $table) {
3127 if (array_key_exists('order_bys', $table)) {
3128 // For DAO columns defined in $this->_columns
3129 $fields = $table['order_bys'];
3131 elseif (array_key_exists('extends', $table)) {
3132 // For custom fields referenced in $this->_customGroupExtends
3133 $fields = CRM_Utils_Array
::value('fields', $table, []);
3138 if (!empty($fields) && is_array($fields)) {
3139 foreach ($fields as $fieldName => $field) {
3140 if ($fieldName == $orderBy['column']) {
3141 $orderByField = array_merge($field, $orderBy);
3142 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
3149 if (!empty($orderByField)) {
3150 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
3151 if ($this->groupConcatTested
) {
3152 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
3155 // Not sure when this is preferable to using tplField (which has
3156 // definitely been tested to work in cases then this does not.
3157 // in caution not switching unless report has been tested for
3158 // group concat functionality.
3159 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
3162 // Record any section headers for assignment to the template
3163 if (!empty($orderBy['section'])) {
3164 $orderByField['pageBreak'] = $orderBy['pageBreak'] ??
NULL;
3165 $this->_sections
[$orderByField['tplField']] = $orderByField;
3171 $this->_orderByArray
= $orderBys;
3173 $this->assign('sections', $this->_sections
);
3177 * Determine unselected columns.
3181 public function unselectedOrderByColumns() {
3182 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
3186 * Determine unselected columns.
3190 public function unselectedSectionColumns() {
3191 if (is_array($this->_sections
)) {
3192 return array_diff_key($this->_sections
, $this->getSelectColumns());
3200 * Build output rows.
3202 * @param string $sql
3203 * @param array $rows
3205 public function buildRows($sql, &$rows) {
3206 if (!$this->optimisedForOnlyFullGroupBy
) {
3207 CRM_Core_DAO
::disableFullGroupByMode();
3209 $dao = CRM_Core_DAO
::executeQuery($sql);
3210 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
3211 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
3213 CRM_Core_DAO
::reenableFullGroupByMode();
3214 if (!is_array($rows)) {
3218 // use this method to modify $this->_columnHeaders
3219 $this->modifyColumnHeaders();
3221 $unselectedSectionColumns = $this->unselectedSectionColumns();
3223 while ($dao->fetch()) {
3225 foreach ($this->_columnHeaders
as $key => $value) {
3226 if (property_exists($dao, $key)) {
3227 $row[$key] = $dao->$key;
3231 // section headers not selected for display need to be added to row
3232 foreach ($unselectedSectionColumns as $key => $values) {
3233 if (property_exists($dao, $key)) {
3234 $row[$key] = $dao->$key;
3243 * Calculate section totals.
3245 * When "order by" fields are marked as sections, this assigns to the template
3246 * an array of total counts for each section. This data is used by the Smarty
3247 * plugin {sectionTotal}.
3249 public function sectionTotals() {
3251 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3252 if (empty($this->_selectAliases
)) {
3256 if (!empty($this->_sections
)) {
3257 // build the query with no LIMIT clause
3258 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3259 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3261 // pull section aliases out of $this->_sections
3262 $sectionAliases = array_keys($this->_sections
);
3265 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3266 $ifnulls[] = "ifnull($alias, '') as $alias";
3268 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3269 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3271 // Group (un-limited) report by all aliases and get counts. This might
3272 // be done more efficiently when the contents of $sql are known, ie. by
3273 // overriding this method in the report class.
3275 $query = $this->_select
.
3276 ", count(*) as ct from ($sql) as subquery group by " .
3277 implode(", ", $sectionAliases);
3279 // initialize array of total counts
3281 $dao = CRM_Core_DAO
::executeQuery($query);
3282 while ($dao->fetch()) {
3284 // let $this->_alterDisplay translate any integer ids to human-readable values.
3285 $rows[0] = $dao->toArray();
3286 $this->alterDisplay($rows);
3287 $this->alterCustomDataDisplay($rows);
3290 // add totals for all permutations of section values
3293 $aliasCount = count($sectionAliases);
3294 foreach ($sectionAliases as $alias) {
3295 $values[] = $row[$alias];
3296 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3297 if ($i == $aliasCount) {
3298 // the last alias is the lowest-level section header; use count as-is
3299 $totals[$key] = $dao->ct
;
3302 // other aliases are higher level; roll count into their total
3303 $totals[$key] +
= $dao->ct
;
3307 $this->assign('sectionTotals', $totals);
3312 * Modify column headers.
3314 public function modifyColumnHeaders() {
3315 // use this method to modify $this->_columnHeaders
3319 * Move totals columns to the right edge of the table.
3321 * It seems like a more logical layout to have any totals columns on the far right regardless of
3322 * the location of the rest of their table.
3324 public function moveSummaryColumnsToTheRightHandSide() {
3325 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3326 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3330 * Assign rows to the template.
3332 * @param array $rows
3334 public function doTemplateAssignment(&$rows) {
3335 $this->assign('columnHeaders', $this->_columnHeaders
);
3336 $this->assign_by_ref('rows', $rows);
3337 $this->assign('statistics', $this->statistics($rows));
3341 * Build report statistics.
3343 * Override this method to build your own statistics.
3345 * @param array $rows
3349 public function statistics(&$rows) {
3352 $count = count($rows);
3353 // Why do we increment the count for rollup seems to artificially inflate the count.
3354 // It seems perhaps intentional to include the summary row in the count of results - although
3355 // this just seems odd.
3356 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3360 $this->countStat($statistics, $count);
3362 $this->groupByStat($statistics);
3364 $this->filterStat($statistics);
3370 * Add count statistics.
3372 * @param array $statistics
3375 public function countStat(&$statistics, $count) {
3376 $statistics['counts']['rowCount'] = [
3377 'title' => ts('Row(s) Listed'),
3379 'type' => CRM_Utils_Type
::T_INT
,
3382 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3383 $statistics['counts']['rowsFound'] = [
3384 'title' => ts('Total Row(s)'),
3385 'value' => $this->_rowsFound
,
3386 'type' => CRM_Utils_Type
::T_INT
,
3392 * Add group by statistics.
3394 * @param array $statistics
3396 public function groupByStat(&$statistics) {
3397 if (!empty($this->_params
['group_bys']) &&
3398 is_array($this->_params
['group_bys']) &&
3399 !empty($this->_params
['group_bys'])
3401 foreach ($this->_columns
as $tableName => $table) {
3402 if (array_key_exists('group_bys', $table)) {
3403 foreach ($table['group_bys'] as $fieldName => $field) {
3404 if (!empty($this->_params
['group_bys'][$fieldName])) {
3405 $combinations[] = $field['title'];
3410 $statistics['groups'][] = [
3411 'title' => ts('Grouping(s)'),
3412 'value' => implode(' & ', $combinations),
3416 // prevents an e-notice in statistics.tpl.
3417 $statistics['groups'] = [];
3422 * Filter statistics.
3424 * @param array $statistics
3426 public function filterStat(&$statistics) {
3427 foreach ($this->_columns
as $tableName => $table) {
3428 if (array_key_exists('filters', $table)) {
3429 foreach ($table['filters'] as $fieldName => $field) {
3430 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3431 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3432 CRM_Utils_Array
::value('operatorType', $field) !=
3433 CRM_Report_Form
::OP_MONTH
3435 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
3436 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
3437 if (!empty($this->_params
["{$fieldName}_relative"])) {
3438 [$from, $to] = CRM_Utils_Date
::getFromTo($this->_params
["{$fieldName}_relative"], NULL, NULL);
3440 if (strlen($to) === 10) {
3441 // If we just have the date we assume the end of that day.
3446 $from = date('l j F Y, g:iA', strtotime($from));
3449 $to = date('l j F Y, g:iA', strtotime($to));
3451 $statistics['filters'][] = [
3452 'title' => $field['title'],
3453 'value' => ts("Between %1 and %2", [1 => $from, 2 => $to]),
3456 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3457 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3459 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3460 $statistics['filters'][] = [
3461 'title' => $field['title'],
3462 'value' => $pair[$rel],
3467 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
3470 $pair = $this->getOperationPair(
3471 CRM_Utils_Array
::value('operatorType', $field),
3474 $min = $this->_params
["{$fieldName}_min"] ??
NULL;
3475 $max = $this->_params
["{$fieldName}_max"] ??
NULL;
3476 $val = $this->_params
["{$fieldName}_value"] ??
NULL;
3477 if (in_array($op, ['bw', 'nbw']) && ($min ||
$max)) {
3478 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3480 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3481 $this->setEntityRefDefaults($field, $tableName);
3482 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3484 CRM_Utils_Array
::value('api', $field['attributes'], []));
3486 foreach ($result['values'] as $v) {
3487 $values[] = $v['label'];
3489 $value = "{$pair[$op]} " . implode(', ', $values);
3491 elseif ($op == 'nll' ||
$op == 'nnll') {
3492 $value = $pair[$op];
3494 elseif (is_array($val) && (!empty($val))) {
3495 $options = CRM_Utils_Array
::value('options', $field, []);
3496 foreach ($val as $key => $valIds) {
3497 if (isset($options[$valIds])) {
3498 $val[$key] = $options[$valIds];
3501 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3502 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3503 $val = implode(', ', $val);
3504 $value = "{$pair[$op]} " . $val;
3506 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3507 isset($field['options']) &&
3508 is_array($field['options']) && !empty($field['options'])
3510 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3511 CRM_Utils_Array
::value($val, $field['options'], $val);
3514 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3517 if ($value && empty($field['no_display'])) {
3518 $statistics['filters'][] = [
3519 'title' => $field['title'] ??
NULL,
3520 'value' => CRM_Utils_String
::htmlToText($value),
3527 // Prevents an e-notice in statistics.tpl.
3528 $statistics['filters'] = [];
3534 * End post processing.
3536 * @param array|null $rows
3538 public function endPostProcess(&$rows = NULL) {
3539 $this->assign('report_class', get_class($this));
3541 // This is used by unit tests, where _outputMode is intentionally blank.
3542 // Is there a reason it couldn't just always do this? It effectively does
3543 // the same thing anyway by assigning it to the template (in
3544 // doTemplateAssignment()).
3545 if ($this->_storeResultSet
) {
3546 $this->_resultSet
= $rows;
3549 // Add contacts to group
3550 if ($this->_outputMode
== 'group') {
3551 $group = $this->_params
['groups'];
3552 $this->add2group($group);
3555 if ($this->_sendmail
) {
3558 elseif (!empty($this->outputHandler
)) {
3559 $this->outputHandler
->download();
3560 CRM_Utils_System
::civiExit();
3562 // else we don't need to do anything here since it must have been
3563 // outputMode=save or something like that
3568 * Set store result set indicator to TRUE.
3570 * This is used by unit tests, along with getResultSet(), to get just
3571 * the output rows unformatted.
3573 public function storeResultSet() {
3574 $this->_storeResultSet
= TRUE;
3582 public function getResultSet() {
3583 return $this->_resultSet
;
3587 * Get the sql used to generate the report.
3591 public function getReportSql() {
3592 return $this->sqlArray
;
3596 * Use the form name to create the tpl file name.
3600 public function getTemplateFileName() {
3601 $defaultTpl = parent
::getTemplateFileName();
3602 $template = CRM_Core_Smarty
::singleton();
3603 if (!$template->template_exists($defaultTpl)) {
3604 $defaultTpl = 'CRM/Report/Form.tpl';
3610 * Compile the report content.
3612 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3616 public function compileContent() {
3617 $templateFile = $this->getHookedTemplateFileName();
3618 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3619 CRM_Core_Form
::$_template->fetch($templateFile) .
3620 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3624 * Post process function.
3626 public function postProcess() {
3627 // get ready with post process params
3628 $this->beginPostProcess();
3631 $sql = $this->buildQuery();
3633 // build array of result based on column headers. This method also allows
3634 // modifying column headers before using it to build result set i.e $rows.
3636 $this->buildRows($sql, $rows);
3638 // format result set.
3639 $this->formatDisplay($rows);
3641 // assign variables to templates
3642 $this->doTemplateAssignment($rows);
3644 // do print / pdf / instance stuff if needed
3645 $this->endPostProcess($rows);
3651 * @param int|null $rowCount
3655 public function limit($rowCount = NULL) {
3656 $rowCount = $rowCount ??
$this->getRowCount();
3657 // lets do the pager if in html mode
3658 $this->_limit
= NULL;
3660 // CRM-14115, over-ride row count if rowCount is specified in URL
3661 if ($this->_dashBoardRowCount
) {
3662 $rowCount = $this->_dashBoardRowCount
;
3664 if ($this->addPaging
) {
3665 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3667 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3669 // @todo all http vars should be extracted in the preProcess
3670 // - not randomly in the class
3671 if (!$pageId && !empty($_POST)) {
3672 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3673 $pageId = max((int) $_POST['crmPID_B'], 1);
3675 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3676 $pageId = max((int) $_POST['crmPID'], 1);
3678 unset($_POST['crmPID_B'], $_POST['crmPID']);
3681 $pageId = $pageId ?
$pageId : 1;
3682 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3683 $offset = ($pageId - 1) * $rowCount;
3685 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3686 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3688 $this->_limit
= " LIMIT $offset, $rowCount";
3689 return [$offset, $rowCount];
3691 if ($this->_limitValue
) {
3692 if ($this->_offsetValue
) {
3693 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3696 $this->_limit
= " LIMIT " . $this->_limitValue
;
3704 * @param int|null $rowCount
3706 public function setPager($rowCount = NULL) {
3707 $rowCount = $rowCount ??
$this->getRowCount();
3708 // CRM-14115, over-ride row count if rowCount is specified in URL
3709 if ($this->_dashBoardRowCount
) {
3710 $rowCount = $this->_dashBoardRowCount
;
3713 if ($this->_limit
&& ($this->_limit
!= '')) {
3714 if (!$this->_rowsFound
) {
3715 $sql = "SELECT FOUND_ROWS();";
3716 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3719 'total' => $this->_rowsFound
,
3720 'rowCount' => $rowCount,
3721 'status' => ts('Records') . ' %%StatusMessage%%',
3722 'buttonBottom' => 'PagerBottomButton',
3723 'buttonTop' => 'PagerTopButton',
3725 if (!empty($this->controller
)) {
3726 // This happens when being called from the api Really we want the api to be able to
3727 // pass paging parameters, but at this stage just preventing test crashes.
3728 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3731 $pager = new CRM_Utils_Pager($params);
3732 $this->assign_by_ref('pager', $pager);
3733 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3738 * Build a group filter with contempt for large data sets.
3740 * This function has been retained as it takes time to migrate the reports over
3741 * to the new method which will not crash on large datasets.
3745 * @param string $field
3746 * @param mixed $value
3751 public function legacySlowGroupFilterClause($field, $value, $op) {
3752 $smartGroupQuery = "";
3754 $group = new CRM_Contact_DAO_Group();
3755 $group->is_active
= 1;
3758 while ($group->fetch()) {
3759 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3760 $group->saved_search_id
3762 $smartGroups[] = $group->id
;
3766 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3768 $smartGroupQuery = '';
3769 if (!empty($smartGroups)) {
3770 $smartGroups = implode(',', $smartGroups);
3771 $smartGroupQuery = " UNION DISTINCT
3772 SELECT DISTINCT smartgroup_contact.contact_id
3773 FROM civicrm_group_contact_cache smartgroup_contact
3774 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3777 $sqlOp = $this->getSQLOperator($op);
3778 if (!is_array($value)) {
3781 //include child groups if any
3782 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3784 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3786 $contactAlias = $this->_aliases
['civicrm_contact'];
3787 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3788 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3790 return " {$contactAlias}.id {$sqlOp} (
3791 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3792 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3793 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3794 {$smartGroupQuery} ) ";
3798 * Build where clause for groups.
3800 * @param string $field
3801 * @param mixed $value
3806 public function whereGroupClause($field, $value, $op) {
3807 if ($this->groupFilterNotOptimised
) {
3808 return $this->legacySlowGroupFilterClause($field, $value, $op);
3810 if ($op === 'notin') {
3811 return " group_temp_table.contact_id IS NULL ";
3813 // We will have used an inner join instead.
3818 * Create a table of the contact ids included by the group filter.
3820 * This function is called by both the api (tests) and the UI.
3822 * @throws \CiviCRM_API3_Exception
3824 public function buildGroupTempTable(): void
{
3825 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3828 $this->groupTempTable
= $this->createTemporaryTable('groups', 'contact_id INT', TRUE);
3829 $filteredGroups = (array) $this->_params
['gid_value'];
3830 CRM_Contact_BAO_GroupContactCache
::populateTemporaryTableWithContactsInGroups($filteredGroups, $this->groupTempTable
);
3831 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX contact_id(contact_id)");
3835 * Execute query and add it to the developer tab.
3837 * @param string $query
3838 * @param array $params
3840 * @return \CRM_Core_DAO|object
3842 protected function executeReportQuery($query, $params = []) {
3843 $this->addToDeveloperTab($query);
3844 return CRM_Core_DAO
::executeQuery($query, $params);
3848 * Build where clause for tags.
3850 * @param string $field
3851 * @param mixed $value
3856 public function whereTagClause($field, $value, $op) {
3857 // not using left join in query because if any contact
3858 // belongs to more than one tag, results duplicate
3860 $sqlOp = $this->getSQLOperator($op);
3861 if (!is_array($value)) {
3864 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3865 $entity_table = $this->_tagFilterTable
;
3866 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3867 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3868 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3869 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3873 * Generate membership organization clause.
3875 * @param mixed $value
3876 * @param string $op SQL Operator
3880 public function whereMembershipOrgClause($value, $op) {
3881 $sqlOp = $this->getSQLOperator($op);
3882 if (!is_array($value)) {
3886 $tmp_membership_org_sql_list = implode(', ', $value);
3887 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3888 SELECT DISTINCT mem.contact_id
3889 FROM civicrm_membership mem
3890 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3891 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3892 WHERE mt.member_of_contact_id IN (" .
3893 $tmp_membership_org_sql_list . ")
3894 AND mt.is_active = '1'
3895 AND mem_status.is_current_member = '1'
3896 AND mem_status.is_active = '1' ) ";
3900 * Generate Membership Type SQL Clause.
3902 * @param mixed $value
3908 public function whereMembershipTypeClause($value, $op) {
3909 $sqlOp = $this->getSQLOperator($op);
3910 if (!is_array($value)) {
3914 $tmp_membership_sql_list = implode(', ', $value);
3915 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3916 SELECT DISTINCT mem.contact_id
3917 FROM civicrm_membership mem
3918 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3919 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3920 WHERE mem.membership_type_id IN (" .
3921 $tmp_membership_sql_list . ")
3922 AND mt.is_active = '1'
3923 AND mem_status.is_current_member = '1'
3924 AND mem_status.is_active = '1' ) ";
3928 * Build contact acl clause
3929 * @deprecated in favor of buildPermissionClause
3931 * Note that if the buildPermissionClause function is called (which most reports do from
3932 * buildQuery then the results of this function are re-calculated and overwritten.
3934 * @param string $tableAlias
3936 public function buildACLClause($tableAlias = 'contact_a') {
3937 [$this->_aclFrom
, $this->_aclWhere
] = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3941 * Build the permission clause for all entities in this report
3943 public function buildPermissionClause() {
3945 foreach ($this->selectedTables() as $tableName) {
3946 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3947 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3948 $tableAlias = $this->_columns
[$tableName]['alias'];
3949 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3950 foreach ($clauses as $field => $clause) {
3951 // Skip contact_id field if redundant
3952 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3953 $ret["$tableName.$field"] = $clause;
3958 // Override output from buildACLClause
3959 $this->_aclFrom
= NULL;
3960 $this->_aclWhere
= implode(' AND ', $ret);
3964 * Add custom data to the columns.
3966 * @param bool $addFields
3967 * @param array $permCustomGroupIds
3969 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = []) {
3970 if (empty($this->_customGroupExtends
)) {
3973 if (!is_array($this->_customGroupExtends
)) {
3974 $this->_customGroupExtends
= [$this->_customGroupExtends
];
3976 $customGroupWhere = '';
3977 if (!empty($permCustomGroupIds)) {
3978 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3982 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3983 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format,
3984 cf.serialize as serialize
3985 FROM civicrm_custom_group cg
3986 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3987 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3989 cg.is_active = 1 AND
3990 cf.is_active = 1 AND
3991 cf.is_searchable = 1
3992 ORDER BY cg.weight, cf.weight";
3993 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3996 while ($customDAO->fetch()) {
3997 if ($customDAO->table_name
!= $curTable) {
3998 $curTable = $customDAO->table_name
;
3999 $curFields = $curFilters = [];
4002 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
4003 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
4004 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
4005 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
4007 foreach (['fields', 'filters', 'group_bys'] as $colKey) {
4008 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
4009 $this->_columns
[$curTable][$colKey] = [];
4013 $fieldName = 'custom_' . $customDAO->cf_id
;
4016 // this makes aliasing work in favor
4017 $curFields[$fieldName] = [
4018 'name' => $customDAO->column_name
,
4019 'title' => $customDAO->label
,
4020 'dataType' => $customDAO->data_type
,
4021 'htmlType' => $customDAO->html_type
,
4024 if ($this->_customGroupFilters
) {
4025 // this makes aliasing work in favor
4026 $curFilters[$fieldName] = [
4027 'name' => $customDAO->column_name
,
4028 'title' => $customDAO->label
,
4029 'dataType' => $customDAO->data_type
,
4030 'htmlType' => $customDAO->html_type
,
4034 switch ($customDAO->data_type
) {
4037 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
4038 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
4039 // CRM-6946, show time part for datetime date fields
4040 if ($customDAO->time_format
) {
4041 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
4046 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
4047 $curFilters[$fieldName]['options'] = ['' => ts('- select -')] + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4048 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
4052 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
4053 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
4057 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
4058 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
4059 // Use T_FLOAT instead of T_MONEY as the money number format happens
4060 // by calling CRM_Core_BAO_CustomField::displayValue in alterCustomDataDisplay
4061 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
4065 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
4066 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
4070 case 'StateProvince':
4072 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4074 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4075 if ((is_array($options) && count($options) != 0) ||
(!is_array($options) && $options !== FALSE)) {
4076 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4077 $curFilters[$fieldName]['options'] = $options;
4081 case 'ContactReference':
4082 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4083 $curFilters[$fieldName]['name'] = 'display_name';
4084 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4086 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4087 $curFields[$fieldName]['name'] = 'display_name';
4088 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4092 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4093 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4097 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
4098 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4099 if ($options !== FALSE) {
4100 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4101 $curFilters[$fieldName]['options'] = $options;
4105 if (!array_key_exists('type', $curFields[$fieldName])) {
4106 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], []);
4110 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
4112 if ($this->_customGroupFilters
) {
4113 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
4115 if ($this->_customGroupGroupBy
) {
4116 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
4122 * Build custom data from clause.
4124 * @param bool $joinsForFiltersOnly
4125 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
4127 public function customDataFrom($joinsForFiltersOnly = FALSE) {
4128 if (empty($this->_customGroupExtends
)) {
4131 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
4132 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
4133 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
4135 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
4136 while ($customTablesDAO->fetch()) {
4137 $customTables[] = $customTablesDAO->table_name
;
4140 foreach ($this->_columns
as $table => $prop) {
4141 if (in_array($table, $customTables)) {
4142 $extendsTable = $mapper[$prop['extends']];
4143 // Check field is required for rendering the report.
4144 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4147 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
4149 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
4151 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4152 // handle for ContactReference
4153 if (array_key_exists('fields', $prop)) {
4154 foreach ($prop['fields'] as $fieldName => $field) {
4155 if (CRM_Utils_Array
::value('dataType', $field) ==
4158 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4160 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4169 * Check if the field is selected.
4171 * @param string $prop
4175 public function isFieldSelected($prop) {
4180 if (!empty($this->_params
['fields'])) {
4181 foreach (array_keys($prop['fields']) as $fieldAlias) {
4182 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4183 if ($customFieldId) {
4184 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4188 //might be survey response field.
4189 if (!empty($this->_params
['fields']['survey_response']) &&
4190 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4198 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4199 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4200 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4201 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4208 if (!empty($this->_params
['order_bys'])) {
4209 foreach (array_keys($prop['fields']) as $fieldAlias) {
4210 foreach ($this->_params
['order_bys'] as $orderBy) {
4211 if ($fieldAlias == $orderBy['column'] &&
4212 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4219 return $this->isFieldFiltered($prop);
4224 * Check if the field is used as a filter.
4226 * @param string $prop
4230 protected function isFieldFiltered($prop) {
4231 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4232 foreach ($prop['filters'] as $fieldAlias => $val) {
4241 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4242 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4243 ||
($attach != 'relative' &&
4244 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4250 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4251 in_array($this->_params
[$fieldAlias . '_op'], ['nll', 'nnll'])
4262 * Check for empty order_by configurations and remove them.
4264 * Also set template to hide them.
4266 * @param array $formValues
4268 public function preProcessOrderBy(&$formValues) {
4269 // Object to show/hide form elements
4270 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4272 $_showHide->addShow('optionField_1');
4274 // Cycle through order_by options; skip any empty ones, and hide them as well
4277 if (!empty($formValues['order_bys'])) {
4278 foreach ($formValues['order_bys'] as $order_by) {
4279 if ($order_by['column'] && $order_by['column'] != '-') {
4280 $_showHide->addShow('optionField_' . $n);
4281 $orderBys[$n] = $order_by;
4286 for ($i = $n; $i <= 5; $i++
) {
4288 $_showHide->addHide('optionField_' . $i);
4292 // overwrite order_by options with modified values
4293 if (!empty($orderBys)) {
4294 $formValues['order_bys'] = $orderBys;
4297 $formValues['order_bys'] = [1 => ['column' => '-']];
4300 // assign show/hide data to template
4301 $_showHide->addToTemplate();
4305 * Check if table name has columns in SELECT clause.
4307 * @param string $tableName
4308 * Name of table (index of $this->_columns array).
4312 public function isTableSelected($tableName) {
4313 return in_array($tableName, $this->selectedTables());
4317 * Check if table name has columns in WHERE or HAVING clause.
4319 * @param string $tableName
4320 * Name of table (index of $this->_columns array).
4324 public function isTableFiltered($tableName) {
4325 // Cause the array to be generated if not previously done.
4326 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4327 $this->selectedTables();
4329 return in_array($tableName, $this->filteredTables
);
4333 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4335 * If the array is unset it will be built.
4340 public function selectedTables() {
4341 if (!$this->_selectedTables
) {
4342 $orderByColumns = [];
4343 if (array_key_exists('order_bys', $this->_params
) &&
4344 is_array($this->_params
['order_bys'])
4346 foreach ($this->_params
['order_bys'] as $orderBy) {
4347 $orderByColumns[] = $orderBy['column'];
4351 foreach ($this->_columns
as $tableName => $table) {
4352 if (array_key_exists('fields', $table)) {
4353 foreach ($table['fields'] as $fieldName => $field) {
4354 if (!empty($field['required']) ||
4355 !empty($this->_params
['fields'][$fieldName])
4357 $this->_selectedTables
[] = $tableName;
4362 if (array_key_exists('order_bys', $table)) {
4363 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4364 if (in_array($orderByName, $orderByColumns)) {
4365 $this->_selectedTables
[] = $tableName;
4370 if (array_key_exists('filters', $table)) {
4371 foreach ($table['filters'] as $filterName => $filter) {
4372 $filterOp = $this->_params
["{$filterName}_op"] ??
'';
4373 if ((isset($this->_params
["{$filterName}_value"])
4374 && !CRM_Utils_System
::isNull($this->_params
["{$filterName}_value"]))
4375 ||
!empty($this->_params
["{$filterName}_relative"])
4376 ||
$filterOp === 'nll'
4377 ||
$filterOp === 'nnll'
4379 $this->_selectedTables
[] = $tableName;
4380 $this->filteredTables
[] = $tableName;
4387 return $this->_selectedTables
;
4391 * Add campaign fields.
4392 * @param string $entityTable
4393 * @param bool $groupBy
4394 * Add GroupBy? Not appropriate for detail report.
4395 * @param bool $orderBy
4396 * Add OrderBy? Not appropriate for detail report.
4397 * @param bool $filters
4400 public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) {
4401 // Check if CiviCampaign is a) enabled and b) has active campaigns
4402 $config = CRM_Core_Config
::singleton();
4403 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents
);
4404 if ($campaignEnabled) {
4405 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE);
4406 // If we have a campaign, build out the relevant elements
4407 if (!empty($getCampaigns['campaigns'])) {
4408 $this->campaigns
= $getCampaigns['campaigns'];
4409 asort($this->campaigns
);
4410 $this->_columns
[$entityTable]['fields']['campaign_id'] = ['title' => ts('Campaign'), 'default' => 'false'];
4412 $this->_columns
[$entityTable]['filters']['campaign_id'] = [
4413 'title' => ts('Campaign'),
4414 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4415 'options' => $this->campaigns
,
4416 'type' => CRM_Utils_Type
::T_INT
,
4421 $this->_columns
[$entityTable]['group_bys']['campaign_id'] = ['title' => ts('Campaign')];
4425 $this->_columns
[$entityTable]['order_bys']['campaign_id'] = ['title' => ts('Campaign')];
4432 * Add address fields.
4434 * @deprecated - use getAddressColumns which is a more accurate description
4435 * and also accepts an array of options rather than a long list
4437 * adding address fields to construct function in reports
4439 * @param bool $groupBy
4440 * Add GroupBy? Not appropriate for detail report.
4441 * @param bool $orderBy
4442 * Add GroupBy? Not appropriate for detail report.
4443 * @param bool $filters
4444 * @param array $defaults
4447 * address fields for construct clause
4449 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = ['country_id' => TRUE]) {
4450 $defaultAddressFields = [
4451 'street_address' => ts('Street Address'),
4452 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4453 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4454 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4455 'street_number' => ts('Street Number'),
4456 'street_name' => ts('Street Name'),
4457 'street_unit' => ts('Street Unit'),
4458 'city' => ts('City'),
4459 'postal_code' => ts('Postal Code'),
4460 'postal_code_suffix' => ts('Postal Code Suffix'),
4461 'country_id' => ts('Country'),
4462 'state_province_id' => ts('State/Province'),
4463 'county_id' => ts('County'),
4466 'civicrm_address' => [
4467 'dao' => 'CRM_Core_DAO_Address',
4470 'title' => ts('Address Name'),
4471 'default' => $defaults['name'] ??
FALSE,
4475 'grouping' => 'location-fields',
4478 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4479 $addressFields['civicrm_address']['fields'][$fieldName] = [
4480 'title' => $fieldLabel,
4481 'default' => $defaults[$fieldName] ??
FALSE,
4485 $street_address_filters = $general_address_filters = [];
4487 // Address filter depends on whether street address parsing is enabled.
4489 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4492 if ($addressOptions['street_address_parsing']) {
4493 $street_address_filters = [
4494 'street_number' => [
4495 'title' => ts('Street Number'),
4496 'type' => CRM_Utils_Type
::T_INT
,
4497 'name' => 'street_number',
4500 'title' => ts('Street Name'),
4501 'name' => 'street_name',
4502 'type' => CRM_Utils_Type
::T_STRING
,
4507 $street_address_filters = [
4508 'street_address' => [
4509 'title' => ts('Street Address'),
4510 'type' => CRM_Utils_Type
::T_STRING
,
4511 'name' => 'street_address',
4515 $general_address_filters = [
4517 'title' => ts('Postal Code'),
4518 'type' => CRM_Utils_Type
::T_STRING
,
4519 'name' => 'postal_code',
4522 'title' => ts('City'),
4523 'type' => CRM_Utils_Type
::T_STRING
,
4527 'name' => 'country_id',
4528 'title' => ts('Country'),
4529 'type' => CRM_Utils_Type
::T_INT
,
4530 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4531 'options' => CRM_Core_PseudoConstant
::country(),
4533 'state_province_id' => [
4534 'name' => 'state_province_id',
4535 'title' => ts('State/Province'),
4536 'type' => CRM_Utils_Type
::T_INT
,
4537 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4541 'name' => 'county_id',
4542 'title' => ts('County'),
4543 'type' => CRM_Utils_Type
::T_INT
,
4544 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4549 $addressFields['civicrm_address']['filters'] = array_merge(
4550 $street_address_filters,
4551 $general_address_filters);
4554 $addressFields['civicrm_address']['order_bys'] = [
4555 'street_name' => ['title' => ts('Street Name')],
4556 'street_number' => ['title' => ts('Odd / Even Street Number')],
4557 'street_address' => NULL,
4559 'postal_code' => NULL,
4564 $addressFields['civicrm_address']['group_bys'] = [
4565 'street_address' => NULL,
4567 'postal_code' => NULL,
4568 'state_province_id' => [
4569 'title' => ts('State/Province'),
4572 'title' => ts('Country'),
4575 'title' => ts('County'),
4579 return $addressFields;
4583 * Do AlterDisplay processing on Address Fields.
4584 * If there are multiple address field values then
4585 * on basis of provided separator the code values are translated into respective labels
4588 * @param array $rows
4589 * @param int $rowNum
4590 * @param string $baseUrl
4591 * @param string $linkText
4592 * @param string $separator
4596 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4597 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4598 $entryFound = FALSE;
4600 'civicrm_address_country_id' => 'country',
4601 'civicrm_address_county_id' => 'county',
4602 'civicrm_address_state_province_id' => 'stateProvince',
4604 foreach ($columnMap as $fieldName => $fnName) {
4605 if (array_key_exists($fieldName, $row)) {
4606 if ($values = $row[$fieldName]) {
4607 $values = (array) explode($separator, $values);
4608 $rows[$rowNum][$fieldName] = [];
4609 $addressField = $fnName == 'stateProvince' ?
'state' : $fnName;
4610 foreach ($values as $value) {
4611 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant
::$fnName($value);
4613 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4615 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4616 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4617 $criteriaQueryParams,
4618 str_replace('civicrm_address_', '', $fieldName),
4619 str_replace('civicrm_address_', '', $fieldName),
4620 implode(',', $values)
4621 ), $this->_absoluteUrl
, $this->_id
4623 $rows[$rowNum]["{$fieldName}_link"] = $url;
4624 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", [1 => $linkText, 2 => $addressField]);
4635 * Do AlterDisplay processing on Address Fields.
4638 * @param array $rows
4639 * @param int $rowNum
4640 * @param string $baseUrl
4641 * @param string $linkText
4645 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4646 $entryFound = FALSE;
4647 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4648 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4649 $addLinks = ['gender_id' => 'Gender'];
4650 foreach (['prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language'] as $fieldName) {
4651 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4652 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4653 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4655 foreach ($rowValues as $rowValue) {
4657 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4660 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4661 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4662 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4669 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'do_not_trade', 'is_opt_out',
4671 foreach ($yesNoFields as $fieldName) {
4672 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4673 // Since these are essentially 'negative fields' it feels like it
4674 // makes sense to only highlight the exceptions hence no 'No'.
4675 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4680 // Handle employer id
4681 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4682 $employerId = $row['civicrm_contact_employer_id'];
4684 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact
::displayName($employerId);
4685 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
4686 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4695 * Adjusts dates passed in to YEAR() for fiscal year.
4697 * @param string $fieldName
4701 public function fiscalYearOffset($fieldName) {
4702 $config = CRM_Core_Config
::singleton();
4703 $fy = $config->fiscalYearStart
;
4704 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4705 ($fy['d'] == 1 && $fy['M'] == 1)
4707 return "YEAR( $fieldName )";
4709 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4710 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4714 * Add Address into From Table if required.
4716 * Prefix will be added to both tables as
4717 * it is assumed you are using it to get address of a secondary contact.
4719 * @param string $prefix
4720 * @param array $extra Additional options.
4721 * Not currently used in core but may be used in override extensions.
4723 protected function joinAddressFromContact($prefix = '', $extra = []) {
4724 $defaults = ['primary_only' => TRUE];
4725 $params = array_merge($defaults, $extra);
4726 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4727 $isJoinRequired = $this->_addressField
;
4728 foreach ($addressTables as $addressTable) {
4729 if ($this->isTableSelected($prefix . $addressTable)) {
4730 $isJoinRequired = TRUE;
4733 if ($isJoinRequired) {
4735 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4736 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4737 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id)";
4738 if ($params['primary_only']) {
4740 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4742 $this->_from
.= $fromJoin;
4747 * Add Country into From Table if required.
4749 * Prefix will be added to both tables as
4750 * it is assumed you are using it to get address of a secondary contact.
4752 * @param string $prefix
4753 * @param array $extra Additional options.
4754 * Not currently used in core but may be used in override extensions.
4756 protected function joinCountryFromAddress($prefix = '', $extra = []) {
4757 $defaults = ['primary_only' => TRUE];
4758 $params = array_merge($defaults, $extra);
4759 // include country field if country column is to be included
4760 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4761 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4762 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4765 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4766 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id";
4767 if ($params['primary_only']) {
4769 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4771 $this->_from
.= $fromJoin;
4776 * Add Phone into From Table if required.
4778 * Prefix will be added to both tables as
4779 * it is assumed you are using it to get address of a secondary contact.
4781 * @param string $prefix
4782 * @param array $extra Additional options.
4783 * Not currently used in core but may be used in override extensions.
4785 protected function joinPhoneFromContact($prefix = '', $extra = []) {
4786 $defaults = ['primary_only' => TRUE];
4787 $params = array_merge($defaults, $extra);
4788 // include phone field if phone column is to be included
4789 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4791 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4792 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id";
4793 if ($params['primary_only']) {
4795 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4797 $this->_from
.= $fromJoin;
4802 * Add Email into From Table if required.
4804 * Prefix will be added to both tables as
4805 * it is assumed you are using it to get address of a secondary contact.
4807 * @param string $prefix
4808 * @param array $extra Additional options.
4809 * Not currently used in core but may be used in override extensions.
4811 protected function joinEmailFromContact($prefix = '', $extra = []) {
4812 $defaults = ['primary_only' => TRUE];
4813 $params = array_merge($defaults, $extra);
4814 // include email field if email column is to be included
4815 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4817 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4818 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id";
4819 if ($params['primary_only']) {
4821 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1 ";
4823 $this->_from
.= $fromJoin;
4828 * Add Financial Transaction into From Table if required.
4830 public function addFinancialTrxnFromClause() {
4831 if ($this->isTableSelected('civicrm_financial_trxn')) {
4833 LEFT JOIN civicrm_entity_financial_trxn eftcc
4834 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4835 eftcc.entity_table = 'civicrm_contribution')
4836 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4837 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4842 * Get phone columns to add to array.
4844 * @param array $options
4845 * - prefix Prefix to add to table (in case of more than one instance of the table)
4846 * - prefix_label Label to give columns from this phone table instance
4849 * phone columns definition
4851 public function getPhoneColumns($options = []) {
4854 'prefix_label' => '',
4857 $options = array_merge($defaultOptions, $options);
4860 $options['prefix'] . 'civicrm_phone' => [
4861 'dao' => 'CRM_Core_DAO_Phone',
4863 $options['prefix'] . 'phone' => [
4864 'title' => $options['prefix_label'] . ts('Phone'),
4874 * Get a standard set of contact fields.
4875 * @deprecated - use getColumns('Contact') instead
4878 public function getBasicContactFields() {
4881 'title' => ts('Contact Name'),
4886 'no_display' => TRUE,
4890 'title' => ts('Contact Prefix'),
4893 'title' => ts('First Name'),
4896 'title' => ts('Nick Name'),
4899 'title' => ts('Middle Name'),
4902 'title' => ts('Last Name'),
4905 'title' => ts('Contact Suffix'),
4907 'source' => ['title' => ts('Contact Source')],
4908 'postal_greeting_display' => ['title' => ts('Postal Greeting')],
4909 'email_greeting_display' => ['title' => ts('Email Greeting')],
4910 'addressee_display' => ['title' => ts('Addressee')],
4912 'title' => ts('Contact Type'),
4914 'contact_sub_type' => [
4915 'title' => ts('Contact Subtype'),
4918 'title' => ts('Gender'),
4921 'title' => ts('Birth Date'),
4924 'title' => ts('Age'),
4925 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4928 'title' => ts('Contact Job title'),
4930 'organization_name' => [
4931 'title' => ts('Organization Name'),
4933 'external_identifier' => [
4934 'title' => ts('Contact identifier from external system'),
4936 'do_not_email' => [],
4937 'do_not_phone' => [],
4938 'do_not_mail' => [],
4940 'do_not_trade' => [],
4942 'is_deceased' => [],
4943 'preferred_language' => [],
4945 'title' => ts('Current Employer'),
4951 * Get a standard set of contact filters.
4953 * @param array $defaults
4957 public function getBasicContactFilters($defaults = []) {
4960 'title' => ts('Contact Name'),
4963 'title' => ts('Contact Source'),
4964 'type' => CRM_Utils_Type
::T_STRING
,
4967 'title' => ts('Contact ID'),
4968 'no_display' => TRUE,
4971 'title' => ts('Gender'),
4972 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4973 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4976 'title' => ts('Birth Date'),
4977 'operatorType' => CRM_Report_Form
::OP_DATE
,
4980 'title' => ts('Contact Type'),
4982 'contact_sub_type' => [
4983 'title' => ts('Contact Subtype'),
4985 'modified_date' => [
4986 'title' => ts('Contact Modified'),
4987 'operatorType' => CRM_Report_Form
::OP_DATE
,
4988 'type' => CRM_Utils_Type
::T_DATE
,
4991 'title' => ts('Deceased'),
4992 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4993 'default' => CRM_Utils_Array
::value('deceased', $defaults, 0),
4996 'title' => ts('Do not email'),
4997 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5000 'title' => ts('Do not phone'),
5001 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5004 'title' => ts('Do not mail'),
5005 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5008 'title' => ts('Do not SMS'),
5009 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5012 'title' => ts('Do not Trade'),
5013 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5016 'title' => ts('Do not bulk email'),
5017 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5019 'preferred_language' => [
5020 'title' => ts('Preferred Language'),
5023 'no_display' => TRUE,
5025 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5031 * Add contact to group.
5033 * @param int $groupID
5035 public function add2group($groupID) {
5036 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
5037 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
5038 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
5039 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
5040 $sql = str_replace('WITH ROLLUP', '', $sql);
5041 if (!$this->optimisedForOnlyFullGroupBy
) {
5042 CRM_Core_DAO
::disableFullGroupByMode();
5044 $dao = CRM_Core_DAO
::executeQuery($sql);
5045 CRM_Core_DAO
::reenableFullGroupByMode();
5048 // Add resulting contacts to group
5049 while ($dao->fetch()) {
5050 if ($dao->addtogroup_contact_id
) {
5051 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
5055 if (!empty($contact_ids)) {
5056 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
5057 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
5060 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
5066 * Apply common settings to entityRef fields.
5068 * @param array $field
5069 * @param string $table
5071 public function setEntityRefDefaults(&$field, $table) {
5072 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : [];
5073 $field['attributes'] +
= [
5074 'entity' => CRM_Core_DAO_AllCoreTables
::getEntityNameForTable($table),
5076 'placeholder' => ts('- select -'),
5081 * Add link fields to the row.
5083 * Function adds the _link & _hover fields to the row.
5086 * @param string $baseUrl
5087 * @param string $linkText
5088 * @param string $value
5089 * @param string $fieldName
5090 * @param string $tablePrefix
5091 * @param string $fieldLabel
5095 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
5096 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
5097 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
5098 "reset=1&force=1&{$criteriaQueryParams}&" .
5099 $fieldName . "_op=in&{$fieldName}_value={$value}",
5100 $this->_absoluteUrl
, $this->_id
5102 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
5103 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
5104 [1 => $linkText, 2 => $fieldLabel]
5109 * Get label for show results buttons.
5113 public function getResultsLabel() {
5114 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
5115 return $showResultsLabel;
5119 * Determine the output mode from the url or input.
5122 * - pdf : Render as pdf
5123 * - csv : Render as csv
5124 * - print : Render in print format
5125 * - save : save the report and display the new report
5126 * - copy : save the report as a new instance and display that.
5127 * - group : go to the add to group screen.
5129 * Potentially chart variations could also be included but the complexity
5130 * is that we might print a bar chart as a pdf.
5132 protected function setOutputMode() {
5133 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
5136 CRM_Core_DAO
::$_nullObject,
5138 CRM_Utils_Array
::value('task', $this->_params
)
5140 // if contacts are added to group
5141 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
5142 $this->_outputMode
= 'group';
5144 if (isset($this->_params
['task'])) {
5145 unset($this->_params
['task']);
5150 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5153 * @param $columnName
5155 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5156 // add new column with date value for the datetime field
5157 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5158 CRM_Core_DAO
::executeQuery($tempQuery);
5159 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5160 CRM_Core_DAO
::executeQuery($updateQuery);
5161 $this->_selectClauses
[] = "{$columnName}_date";
5162 $this->_select
.= ", {$columnName}_date";
5163 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5164 unset($this->_sections
["{$columnName}"]);
5165 $this->assign('sections', $this->_sections
);
5169 * Get an array of the columns that have been selected for display.
5173 public function getSelectColumns() {
5174 $selectColumns = [];
5175 foreach ($this->_columns
as $tableName => $table) {
5176 if (array_key_exists('fields', $table)) {
5177 foreach ($table['fields'] as $fieldName => $field) {
5178 if (!empty($field['required']) ||
5179 !empty($this->_params
['fields'][$fieldName])
5182 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5187 return $selectColumns;
5191 * Add location tables to the query if they are used for filtering.
5193 * This is for when we are running the query separately for filtering and retrieving display fields.
5195 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5196 if ($this->isTableFiltered('civicrm_email')) {
5198 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5199 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5200 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5202 if ($this->isTableFiltered('civicrm_phone')) {
5204 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5205 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5206 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5208 if ($this->isTableFiltered('civicrm_address')) {
5210 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5211 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5212 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5217 * Set the base table for the FROM clause.
5219 * Sets up the from clause, allowing for the possibility it might be a
5220 * temp table pre-filtered by groups if a group filter is in use.
5222 * @param string $baseTable
5223 * @param string $field
5224 * @param null $tableAlias
5226 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5228 $tableAlias = $this->_aliases
[$baseTable];
5230 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5231 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5232 $this->_from
.= " {$this->_aclFrom} ";
5236 * Join the temp table contacting contacts who are members of the filtered groups.
5238 * If we are using an IN filter we use an inner join, otherwise a left join.
5240 * @param string $baseTable
5241 * @param string $field
5242 * @param string $tableAlias
5244 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5245 if ($this->groupTempTable
) {
5246 if ($this->_params
['gid_op'] == 'in') {
5247 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5248 ON group_temp_table.contact_id = $tableAlias.{$field} ";
5252 LEFT JOIN $this->groupTempTable group_temp_table
5253 ON $tableAlias.{$field} = group_temp_table.contact_id ";
5259 * Get all labels for fields that are used in a group concat.
5261 * @param string $options
5262 * comma separated option values.
5263 * @param string $baoName
5264 * The BAO name for the field.
5265 * @param string $fieldName
5266 * The name of the field for which labels should be retrieved.
5270 public function getLabels($options, $baoName, $fieldName) {
5271 $types = explode(',', $options);
5273 foreach ($types as $value) {
5274 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5276 return implode(', ', array_filter($labels));
5280 * Add statistics columns.
5282 * If a group by is in play then add columns for the statistics fields.
5284 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5285 * column header field.
5287 * @param array $field
5288 * @param string $tableName
5289 * @param string $fieldName
5290 * @param array $select
5294 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5295 foreach ($field['statistics'] as $stat => $label) {
5296 $alias = "{$tableName}_{$fieldName}_{$stat}";
5297 switch (strtolower($stat)) {
5300 $select[] = "$stat({$field['dbAlias']}) as $alias";
5301 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5302 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5303 $this->_statFields
[$label] = $alias;
5304 $this->_selectAliases
[] = $alias;
5308 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5309 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5310 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5311 $this->_statFields
[$label] = $alias;
5312 $this->_selectAliases
[] = $alias;
5315 case 'count_distinct':
5316 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5317 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5318 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5319 $this->_statFields
[$label] = $alias;
5320 $this->_selectAliases
[] = $alias;
5324 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5325 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5326 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5327 $this->_statFields
[$label] = $alias;
5328 $this->_selectAliases
[] = $alias;
5336 * Add a basic field to the select clause.
5338 * @param string $tableName
5339 * @param string $fieldName
5340 * @param array $field
5341 * @param string $select
5344 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5345 $alias = "{$tableName}_{$fieldName}";
5346 $select[] = "{$field['dbAlias']} as $alias";
5347 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
5348 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
5349 $this->_selectAliases
[] = $alias;
5356 * @param array $table
5357 * @param string $tableName
5362 protected function setTableAlias($table, $tableName) {
5363 if (!isset($table['alias'])) {
5364 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5368 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5371 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5372 return $this->_aliases
[$tableName];
5376 * Function to add columns to reports.
5378 * This is ported from extended reports, which also adds join filters to the options.
5380 * @param string $type
5381 * @param array $options
5382 * - prefix - A string to prepend to the table name
5383 * - prefix_label A string to prepend to the fields
5384 * - fields (bool) - should the fields for this table be made available
5385 * - group_by (bool) - should the group bys for this table be made available.
5386 * - order_by (bool) - should the group bys for this table be made available.
5387 * - filters (bool) - should the filters for this table by made available.
5388 * - fields_defaults (array) array of fields that should be displayed by default.
5389 * - filters_defaults (array) array of fields that should be filtered by default.
5390 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5391 * - join_fields (array) fields available from join (requires additional custom code).
5392 * - group_by_defaults (array) array of group bys that should be applied by default.
5393 * - order_by_defaults (array) array of order bys that should be applied by default.
5394 * - custom_fields (array) array of entity types for custom fields (not usually required).
5395 * - contact_type (string) optional restriction on contact type for some tables.
5396 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5400 protected function getColumns($type, $options = []) {
5403 'prefix_label' => '',
5405 'group_bys' => FALSE,
5406 'order_bys' => TRUE,
5408 'join_filters' => FALSE,
5409 'fields_defaults' => [],
5410 'filters_defaults' => [],
5411 'group_bys_defaults' => [],
5412 'order_bys_defaults' => [],
5414 $options = array_merge($defaultOptions, $options);
5416 $fn = 'get' . $type . 'Columns';
5417 return $this->$fn($options);
5421 * Get columns for contact table.
5423 * @param array $options
5427 protected function getContactColumns($options = []) {
5429 'custom_fields' => CRM_Contact_BAO_ContactType
::basicTypes(),
5430 'fields_defaults' => ['display_name', 'id'],
5431 'order_bys_defaults' => ['sort_name ASC'],
5432 'contact_type' => NULL,
5435 $options = array_merge($defaultOptions, $options);
5437 $tableAlias = $options['prefix'] . 'contact';
5440 $options['prefix'] . 'display_name' => [
5441 'name' => 'display_name',
5442 'title' => $options['prefix_label'] . ts('Contact Name'),
5443 'is_fields' => TRUE,
5445 $options['prefix'] . 'sort_name' => [
5446 'name' => 'sort_name',
5447 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5448 'is_fields' => TRUE,
5449 'is_filters' => TRUE,
5450 'is_order_bys' => TRUE,
5452 $options['prefix'] . 'id' => [
5454 'title' => $options['prefix_label'] . ts('Contact ID'),
5455 'alter_display' => 'alterContactID',
5456 'type' => CRM_Utils_Type
::T_INT
,
5457 'is_order_bys' => TRUE,
5458 'is_group_bys' => TRUE,
5459 'is_fields' => TRUE,
5460 'is_filters' => TRUE,
5462 $options['prefix'] . 'external_identifier' => [
5463 'name' => 'external_identifier',
5464 'title' => $options['prefix_label'] . ts('External ID'),
5465 'type' => CRM_Utils_Type
::T_INT
,
5466 'is_fields' => TRUE,
5468 $options['prefix'] . 'contact_type' => [
5469 'title' => $options['prefix_label'] . ts('Contact Type'),
5470 'name' => 'contact_type',
5471 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5472 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5473 'is_fields' => TRUE,
5474 'is_filters' => TRUE,
5475 'is_group_bys' => TRUE,
5477 $options['prefix'] . 'contact_sub_type' => [
5478 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5479 'name' => 'contact_sub_type',
5480 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5481 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5482 'is_fields' => TRUE,
5483 'is_filters' => TRUE,
5484 'is_group_bys' => TRUE,
5486 $options['prefix'] . 'is_deleted' => [
5487 'title' => $options['prefix_label'] . ts('Is deleted'),
5488 'name' => 'is_deleted',
5489 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5490 'is_fields' => FALSE,
5491 'is_filters' => TRUE,
5492 'is_group_bys' => FALSE,
5494 $options['prefix'] . 'external_identifier' => [
5495 'title' => $options['prefix_label'] . ts('Contact identifier from external system'),
5496 'name' => 'external_identifier',
5497 'is_fields' => TRUE,
5498 'is_filters' => FALSE,
5499 'is_group_bys' => FALSE,
5500 'is_order_bys' => TRUE,
5502 $options['prefix'] . 'preferred_language' => [
5503 'title' => $options['prefix_label'] . ts('Preferred Language'),
5504 'name' => 'preferred_language',
5505 'is_fields' => TRUE,
5506 'is_filters' => TRUE,
5507 'is_group_bys' => TRUE,
5508 'is_order_bys' => TRUE,
5510 $options['prefix'] . 'preferred_communication_method' => [
5511 'title' => $options['prefix_label'] . ts('Preferred Communication Method'),
5512 'alter_display' => 'alterCommunicationtMethod',
5513 'name' => 'preferred_communication_method',
5514 'is_fields' => TRUE,
5515 'is_filters' => FALSE,
5516 'is_group_bys' => FALSE,
5517 'is_order_bys' => FALSE,
5521 'postal_greeting_display' => 'Postal Greeting',
5522 'email_greeting_display' => 'Email Greeting',
5523 'addressee_display' => 'Addressee',
5524 ] as $field => $title) {
5525 $spec[$options['prefix'] . $field] = [
5526 'title' => $options['prefix_label'] . ts($title),
5528 'is_fields' => TRUE,
5529 'is_filters' => FALSE,
5530 'is_group_bys' => FALSE,
5533 foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'do_not_trade', 'is_opt_out'] as $field) {
5534 $spec[$options['prefix'] . $field] = [
5536 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5537 'is_fields' => TRUE,
5538 'is_filters' => TRUE,
5539 'is_group_bys' => FALSE,
5542 $individualFields = [
5543 $options['prefix'] . 'first_name' => [
5544 'name' => 'first_name',
5545 'title' => $options['prefix_label'] . ts('First Name'),
5546 'is_fields' => TRUE,
5547 'is_filters' => TRUE,
5548 'is_order_bys' => TRUE,
5550 $options['prefix'] . 'middle_name' => [
5551 'name' => 'middle_name',
5552 'title' => $options['prefix_label'] . ts('Middle Name'),
5553 'is_fields' => TRUE,
5555 $options['prefix'] . 'last_name' => [
5556 'name' => 'last_name',
5557 'title' => $options['prefix_label'] . ts('Last Name'),
5558 'default_order' => 'ASC',
5559 'is_fields' => TRUE,
5561 $options['prefix'] . 'nick_name' => [
5562 'name' => 'nick_name',
5563 'title' => $options['prefix_label'] . ts('Nick Name'),
5564 'is_fields' => TRUE,
5566 $options['prefix'] . 'prefix_id' => [
5567 'name' => 'prefix_id',
5568 'title' => $options['prefix_label'] . ts('Prefix'),
5569 'options' => CRM_Contact_BAO_Contact
::buildOptions('prefix_id'),
5570 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5571 'is_fields' => TRUE,
5572 'is_filters' => TRUE,
5574 $options['prefix'] . 'suffix_id' => [
5575 'name' => 'suffix_id',
5576 'title' => $options['prefix_label'] . ts('Suffix'),
5577 'options' => CRM_Contact_BAO_Contact
::buildOptions('suffix_id'),
5578 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5579 'is_fields' => TRUE,
5580 'is_filters' => TRUE,
5582 $options['prefix'] . 'gender_id' => [
5583 'name' => 'gender_id',
5584 'title' => $options['prefix_label'] . ts('Gender'),
5585 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5586 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5587 'is_fields' => TRUE,
5588 'is_filters' => TRUE,
5591 'title' => $options['prefix_label'] . ts('Birth Date'),
5592 'operatorType' => CRM_Report_Form
::OP_DATE
,
5593 'type' => CRM_Utils_Type
::T_DATE
,
5594 'is_fields' => TRUE,
5595 'is_filters' => TRUE,
5598 'title' => $options['prefix_label'] . ts('Age'),
5599 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5600 'type' => CRM_Utils_Type
::T_INT
,
5601 'is_fields' => TRUE,
5603 $options['prefix'] . 'is_deceased' => [
5604 'title' => $options['prefix_label'] . ts('Is deceased'),
5605 'name' => 'is_deceased',
5606 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5607 'is_fields' => FALSE,
5608 'is_filters' => TRUE,
5609 'is_group_bys' => FALSE,
5611 $options['prefix'] . 'job_title' => [
5612 'name' => 'job_title',
5613 'is_fields' => TRUE,
5614 'is_filters' => FALSE,
5615 'is_group_bys' => FALSE,
5617 $options['prefix'] . 'employer_id' => [
5618 'title' => $options['prefix_label'] . ts('Current Employer'),
5619 'type' => CRM_Utils_Type
::T_INT
,
5620 'name' => 'employer_id',
5621 'is_fields' => TRUE,
5622 'is_filters' => FALSE,
5623 'is_group_bys' => TRUE,
5626 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5627 $spec = array_merge($spec, $individualFields);
5630 if (!empty($options['custom_fields'])) {
5631 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = [
5632 'extends' => $options['custom_fields'],
5633 'title' => $options['prefix_label'],
5634 'filters' => $options['filters'],
5635 'prefix' => $options['prefix'],
5636 'prefix_label' => $options['prefix_label'],
5640 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5644 * Get address columns to add to array.
5646 * @param array $options
5647 * - prefix Prefix to add to table (in case of more than one instance of the table)
5648 * - prefix_label Label to give columns from this address table instance
5649 * - group_bys enable these fields for group by - default false
5650 * - order_bys enable these fields for order by
5651 * - filters enable these fields for filtering
5653 * @return array address columns definition
5655 protected function getAddressColumns($options = []) {
5658 'prefix_label' => '',
5660 'group_bys' => FALSE,
5661 'order_bys' => TRUE,
5663 'join_filters' => FALSE,
5664 'fields_defaults' => [],
5665 'filters_defaults' => [],
5666 'group_bys_defaults' => [],
5667 'order_bys_defaults' => [],
5670 $options = array_merge($defaultOptions, $options);
5671 $defaults = $this->getDefaultsFromOptions($options);
5672 $tableAlias = $options['prefix'] . 'address';
5675 $options['prefix'] . 'name' => [
5676 'title' => $options['prefix_label'] . ts('Address Name'),
5678 'is_fields' => TRUE,
5680 $options['prefix'] . 'street_number' => [
5681 'name' => 'street_number',
5682 'title' => $options['prefix_label'] . ts('Street Number'),
5684 'is_fields' => TRUE,
5686 $options['prefix'] . 'odd_street_number' => [
5687 'title' => ts('Odd / Even Street Number'),
5688 'name' => 'odd_street_number',
5689 'type' => CRM_Utils_Type
::T_INT
,
5690 'no_display' => TRUE,
5692 'dbAlias' => "({$tableAlias}_civireport.street_number % 2)",
5693 'is_fields' => TRUE,
5694 'is_order_bys' => TRUE,
5696 $options['prefix'] . 'street_name' => [
5697 'name' => 'street_name',
5698 'title' => $options['prefix_label'] . ts('Street Name'),
5700 'is_fields' => TRUE,
5701 'is_filters' => TRUE,
5702 'operator' => 'like',
5703 'is_order_bys' => TRUE,
5705 $options['prefix'] . 'street_address' => [
5706 'title' => $options['prefix_label'] . ts('Street Address'),
5707 'name' => 'street_address',
5708 'is_fields' => TRUE,
5709 'is_filters' => TRUE,
5710 'is_group_bys' => TRUE,
5712 $options['prefix'] . 'supplemental_address_1' => [
5713 'title' => $options['prefix_label'] . ts('Supplementary Address Field 1'),
5714 'name' => 'supplemental_address_1',
5715 'is_fields' => TRUE,
5717 $options['prefix'] . 'supplemental_address_2' => [
5718 'title' => $options['prefix_label'] . ts('Supplementary Address Field 2'),
5719 'name' => 'supplemental_address_2',
5720 'is_fields' => TRUE,
5722 $options['prefix'] . 'supplemental_address_3' => [
5723 'title' => $options['prefix_label'] . ts('Supplementary Address Field 3'),
5724 'name' => 'supplemental_address_3',
5725 'is_fields' => TRUE,
5727 $options['prefix'] . 'street_number' => [
5728 'name' => 'street_number',
5729 'title' => $options['prefix_label'] . ts('Street Number'),
5731 'is_order_bys' => TRUE,
5732 'is_filters' => TRUE,
5733 'is_fields' => TRUE,
5735 $options['prefix'] . 'street_unit' => [
5736 'name' => 'street_unit',
5737 'title' => $options['prefix_label'] . ts('Street Unit'),
5739 'is_fields' => TRUE,
5741 $options['prefix'] . 'city' => [
5742 'title' => $options['prefix_label'] . ts('City'),
5744 'operator' => 'like',
5745 'is_fields' => TRUE,
5746 'is_filters' => TRUE,
5747 'is_group_bys' => TRUE,
5748 'is_order_bys' => TRUE,
5750 $options['prefix'] . 'postal_code' => [
5751 'title' => $options['prefix_label'] . ts('Postal Code'),
5752 'name' => 'postal_code',
5754 'is_fields' => TRUE,
5755 'is_filters' => TRUE,
5756 'is_group_bys' => TRUE,
5757 'is_order_bys' => TRUE,
5759 $options['prefix'] . 'postal_code_suffix' => [
5760 'title' => $options['prefix_label'] . ts('Postal Code Suffix'),
5761 'name' => 'postal_code_suffix',
5763 'is_fields' => TRUE,
5764 'is_filters' => TRUE,
5765 'is_group_bys' => TRUE,
5766 'is_order_bys' => TRUE,
5768 $options['prefix'] . 'county_id' => [
5769 'title' => $options['prefix_label'] . ts('County'),
5770 'alter_display' => 'alterCountyID',
5771 'name' => 'county_id',
5772 'type' => CRM_Utils_Type
::T_INT
,
5773 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5774 'options' => CRM_Core_PseudoConstant
::county(),
5775 'is_fields' => TRUE,
5776 'is_filters' => TRUE,
5777 'is_group_bys' => TRUE,
5779 $options['prefix'] . 'state_province_id' => [
5780 'title' => $options['prefix_label'] . ts('State/Province'),
5781 'alter_display' => 'alterStateProvinceID',
5782 'name' => 'state_province_id',
5783 'type' => CRM_Utils_Type
::T_INT
,
5784 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5785 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5786 'is_fields' => TRUE,
5787 'is_filters' => TRUE,
5788 'is_group_bys' => TRUE,
5790 $options['prefix'] . 'country_id' => [
5791 'title' => $options['prefix_label'] . ts('Country'),
5792 'alter_display' => 'alterCountryID',
5793 'name' => 'country_id',
5794 'is_fields' => TRUE,
5795 'is_filters' => TRUE,
5796 'is_group_bys' => TRUE,
5797 'type' => CRM_Utils_Type
::T_INT
,
5798 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5799 'options' => CRM_Core_PseudoConstant
::country(),
5801 $options['prefix'] . 'location_type_id' => [
5802 'name' => 'location_type_id',
5803 'title' => $options['prefix_label'] . ts('Location Type'),
5804 'type' => CRM_Utils_Type
::T_INT
,
5805 'is_fields' => TRUE,
5806 'alter_display' => 'alterLocationTypeID',
5808 $options['prefix'] . 'id' => [
5809 'title' => $options['prefix_label'] . ts('ID'),
5811 'is_fields' => TRUE,
5813 $options['prefix'] . 'is_primary' => [
5814 'name' => 'is_primary',
5815 'title' => $options['prefix_label'] . ts('Primary Address?'),
5816 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5817 'is_fields' => TRUE,
5820 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5824 * Build the columns.
5826 * The normal report class needs you to remember to do a few things that are often erratic
5828 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5829 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5830 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5831 * means any saved filters / fields on saved report instances. This will mean that matching names from
5832 * different tables may be ambigious, but it will smooth any code transition.
5833 * - note that it assumes the value being passed in is the actual table field name
5835 * 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
5836 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5838 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5839 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5840 * the core classes can start to move towards that.
5842 * @param array $specs
5843 * @param string $tableName
5844 * @param string $daoName
5845 * @param string $tableAlias
5846 * @param array $defaults
5847 * @param array $options
5851 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = [], $options = []) {
5853 $tableAlias = str_replace('civicrm_', '', $tableName);
5855 $types = ['filters', 'group_bys', 'order_bys', 'join_filters'];
5856 $columns = [$tableName => array_fill_keys($types, [])];
5857 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5858 $columns[$tableName]['dao'] = $daoName;
5859 $columns[$tableName]['alias'] = $tableAlias;
5861 foreach ($specs as $specName => $spec) {
5862 if (empty($spec['name'])) {
5863 $spec['name'] = $specName;
5866 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5867 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5868 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5869 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5870 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5873 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5874 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5877 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5878 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5881 foreach ($types as $type) {
5882 if ($options[$type] && !empty($spec['is_' . $type])) {
5883 $columns[$tableName][$type][$fieldAlias] = $spec;
5884 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5885 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5890 if (isset($options['grouping'])) {
5891 $columns[$tableName]['grouping'] = $options['grouping'];
5892 $columns[$tableName]['group_title'] = $options['group_title'] ??
'';
5898 * Store group bys into array - so we can check elsewhere what is grouped.
5900 protected function storeGroupByArray() {
5902 if (empty($this->_params
['group_bys'])
5903 ||
!is_array($this->_params
['group_bys'])) {
5904 $this->_params
['group_bys'] = [];
5907 foreach ($this->_columns
as $tableName => $table) {
5908 $table = $this->_columns
[$tableName];
5909 if (array_key_exists('group_bys', $table)) {
5910 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5911 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5912 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5913 if (!empty($field['chart'])) {
5914 $this->assign('chartSupported', TRUE);
5917 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5918 !empty($this->_params
['group_bys_freq'][$fieldName])
5921 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5923 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5927 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " YEAR({$field['dbAlias']})";
5931 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "YEAR({$field['dbAlias']}), QUARTER({$field['dbAlias']})";
5935 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "YEARWEEK({$field['dbAlias']})";
5939 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_MONTH FROM {$field['dbAlias']})";
5943 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "DATE({$field['dbAlias']})";
5948 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5949 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5964 protected function getDefaultsFromOptions($options) {
5966 'fields_defaults' => $options['fields_defaults'],
5967 'filters_defaults' => $options['filters_defaults'],
5968 'group_bys_defaults' => $options['group_bys_defaults'],
5969 'order_bys_defaults' => $options['order_bys_defaults'],
5975 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5977 * Full group by mode dictates that a field must either be in the group by function or
5978 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5981 * @param string $tableName
5982 * @param string $fieldName
5983 * @param string $field
5986 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5987 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5988 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5989 $label = $field['title'] ??
NULL;
5990 $alias = $field['tplField'] ??
"{$tableName}_{$fieldName}";
5991 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5992 $this->_selectAliases
[] = $alias;
5993 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5994 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5996 return "({$field['dbAlias']}) as $alias";
6002 * Generate clause for the selected filter.
6004 * @param array $field
6005 * Field specification
6006 * @param string $fieldName
6010 * Relevant where clause.
6012 protected function generateFilterClause($field, $fieldName) {
6013 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
6014 if (CRM_Utils_Array
::value('operatorType', $field) ==
6015 CRM_Report_Form
::OP_MONTH
6017 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
6018 $value = $this->_params
["{$fieldName}_value"] ??
NULL;
6019 if (is_array($value) && !empty($value)) {
6020 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
6025 $relative = $this->_params
["{$fieldName}_relative"] ??
NULL;
6026 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
6027 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
6028 $fromTime = $this->_params
["{$fieldName}_from_time"] ??
NULL;
6029 $toTime = $this->_params
["{$fieldName}_to_time"] ??
NULL;
6030 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
6034 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
6036 return $this->whereClause($field,
6038 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
6039 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
6040 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
6048 * Retrieve a suitable object from the factory depending on the report
6049 * parameters, which typically might just be dependent on outputMode.
6051 * If there is no suitable output handler, e.g. if outputMode is "copy",
6052 * then this sets it to NULL.
6054 public function setOutputHandler() {
6055 $this->outputHandler
= \Civi\Report\OutputHandlerFactory
::singleton()->create($this);
6059 * Send report by email
6061 public function sendEmail() {
6062 if (empty($this->outputHandler
)) {
6063 // It's possible to end up here with outputMode unset, so we use
6064 // the "print" handler which was the default before, i.e. include
6065 // it as html in the body.
6066 $oldOutputMode = $this->_outputMode ??
NULL;
6067 $this->_outputMode
= 'print';
6068 $this->setOutputHandler();
6069 $this->_outputMode
= $oldOutputMode;
6072 $mailBody = $this->outputHandler
->getMailBody();
6075 $attachmentFileName = $this->outputHandler
->getFileName();
6076 // It's not always in the form of an attachment, e.g. for 'print' the
6077 // output ends up in $mailBody above.
6078 if ($attachmentFileName) {
6079 $fullFilename = CRM_Core_Config
::singleton()->templateCompileDir
. CRM_Utils_File
::makeFileName($attachmentFileName);
6080 file_put_contents($fullFilename, $this->outputHandler
->getOutputString());
6082 'fullPath' => $fullFilename,
6083 'mime_type' => $this->outputHandler
->getMimeType(),
6084 'cleanName' => $attachmentFileName,
6085 'charset' => $this->outputHandler
->getCharset(),
6090 // @todo outputMode doesn't seem to get used by mailReport, which is good
6091 // since it shouldn't have any outputMode-related `if` statements in it.
6092 // Someday could remove the param from the function call.
6093 if (CRM_Report_Utils_Report
::mailReport($mailBody, $this->_id
, $this->_outputMode
, $attachments)) {
6094 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
6097 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');