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;
303 protected $_sections = NULL;
304 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
307 * Whether to generate absolute URLs (ex: in report emails).
311 public $_absoluteUrl = FALSE;
314 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
318 protected $_storeResultSet = FALSE;
321 * When _storeResultSet Flag is set use this var to store result set in form of array
325 protected $_resultSet = [];
328 * To what frequency group-by a date column
332 protected $_groupByDateFreq = [
334 'YEARWEEK' => 'Week',
335 'QUARTER' => 'Quarter',
340 * Variables to hold the acl inner join and where clause
343 protected $_aclFrom = NULL;
344 protected $_aclWhere = NULL;
347 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
349 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
353 protected $_selectedTables = [];
356 * Array of DAO tables having columns included in WHERE or HAVING clause
360 protected $filteredTables;
363 * Output mode e.g 'print', 'csv', 'pdf'.
367 protected $_outputMode;
370 * Format of any chart in use.
372 * (it's unclear if this could be merged with outputMode at this stage)
378 public $_having = NULL;
379 public $_select = NULL;
380 public $_selectClauses = [];
381 public $_columnHeaders = [];
382 public $_orderBy = NULL;
383 public $_orderByFields = [];
384 public $_orderByArray = [];
386 * Array of clauses to group by.
390 protected $_groupByArray = [];
391 public $_groupBy = NULL;
392 public $_whereClauses = [];
393 public $_havingClauses = [];
396 * DashBoardRowCount Dashboard row count.
400 public $_dashBoardRowCount;
403 * Is this being called without a form controller (ie. the report is being render outside the normal form
404 * - e.g the api is retrieving the rows.
408 public $noController = FALSE;
411 * Variable to hold the currency alias.
415 protected $_currencyColumn = NULL;
420 protected $_interval;
425 protected $_sendmail;
438 * Report description.
442 public $_description;
445 * Is an address field selected.
448 * This was intended to determine if the address table should be joined in
449 * The isTableSelected function is now preferred for this purpose
451 protected $_addressField;
454 * Is an email field selected.
457 * This was intended to determine if the email table should be joined in
458 * The isTableSelected function is now preferred for this purpose
460 protected $_emailField;
463 * Is a phone field selected.
466 * This was intended to determine if the phone table should be joined in
467 * The isTableSelected function is now preferred for this purpose
469 protected $_phoneField;
472 * Create new report instance? (or update existing) on save.
476 protected $_createNew;
479 * When a grand total row has calculated the status we pop it off to here.
481 * This allows us to access it from the stats function and avoid recalculating.
485 protected $rollupRow = [];
488 * Database attributes - character set and collation.
492 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
495 * SQL being run in this report.
497 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
505 * An instruction not to add a Group By.
507 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
509 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
510 * such as in pivot charts when no row header is set
514 protected $noGroupBy = FALSE;
517 * SQL being run in this report as an array.
519 * The sql in the report is stored in this variable in order to be returned to api & test calls.
527 * Tables created for the report that need removal afterwards.
529 * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x']
532 protected $temporaryTables = [];
535 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
538 public $optimisedForOnlyFullGroupBy = TRUE;
541 * Get the number of rows to show
544 public function getRowCount(): int {
545 return $this->_rowCount
;
549 * set the number of rows to show
550 * @param $rowCount int
552 public function setRowCount($rowCount): void
{
553 $this->_rowCount
= $rowCount;
559 public function __construct() {
560 parent
::__construct();
562 $this->setRowCount(\Civi
::settings()->get('default_pager_size'));
564 $this->addClass('crm-report-form');
566 if ($this->_tagFilter
) {
567 $this->buildTagFilter();
569 if ($this->_exposeContactID
) {
570 if (array_key_exists('civicrm_contact', $this->_columns
)) {
571 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = [
573 'title' => ts('Contact ID'),
579 if ($this->_groupFilter
) {
580 $this->buildGroupFilter();
583 // Get all custom groups
584 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
586 // Get the custom groupIds for which the user has VIEW permission
587 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
588 // and addCustomDataToColumns() will allow access to all custom groups.
589 $permCustomGroupIds = [];
590 if (!CRM_Core_Permission
::check('access all custom data')) {
591 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
592 // do not allow custom data for reports if user doesn't have
593 // permission to access custom data.
594 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
595 $this->_customGroupExtends
= [];
599 // merge custom data columns to _columns list, if any
600 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
602 // add / modify display columns, filters ..etc
603 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
605 //assign currencyColumn variable to tpl
606 $this->assign('currencyColumn', $this->_currencyColumn
);
610 * Shared pre-process function.
612 * If overriding preProcess function this should still be called.
616 public function preProcessCommon() {
617 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
618 // Ensure smarty variables are assigned here since this function is called from
619 // the report api and the main buildForm is not.
620 self
::$_template->ensureVariablesAreAssigned($this->expectedSmartyVariables
);
621 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
623 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
625 $this->assign('section', $this->_section
);
626 CRM_Core_Region
::instance('page-header')->add([
627 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
629 if (!$this->noController
) {
630 $this->setID($this->get('instanceId'));
633 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
635 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
639 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
640 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
641 if (!isset($_SERVER['QUERY_STRING'])) {
642 // in php 7.4 can do this with less lines with ??=
643 $_SERVER['QUERY_STRING'] = '';
645 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
649 $this->assign('instanceId', $this->_id
);
650 $params = ['id' => $this->_id
];
651 $this->_instanceValues
= [];
652 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
654 $this->_instanceValues
656 if (empty($this->_instanceValues
)) {
657 CRM_Core_Error
::statusBounce("Report could not be loaded.");
659 $this->_title
= $this->_instanceValues
['title'];
660 if (!empty($this->_instanceValues
['permission']) &&
661 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
662 CRM_Core_Permission
::check('administer Reports')
665 CRM_Utils_System
::permissionDenied();
666 CRM_Utils_System
::civiExit();
669 $formValues = $this->_instanceValues
['form_values'] ??
NULL;
671 $this->_formValues
= CRM_Utils_String
::unserialize($formValues);
674 $this->_formValues
= NULL;
677 $this->setOutputMode();
679 if ($this->_outputMode
== 'copy') {
680 $this->_createNew
= TRUE;
681 $this->_params
= $this->_formValues
;
682 $this->_params
['view_mode'] = 'criteria';
683 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', [
684 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
685 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
687 // Do not pass go. Do not collect another chance to re-run the same query.
688 CRM_Report_Form_Instance
::postProcess($this);
691 // lets always do a force if reset is found in the url.
692 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
693 // in the comment line above these 2.
694 if (!empty($_REQUEST['reset'])
695 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), ['save', 'criteria'])) {
700 $this->assign('mode', 'instance');
702 elseif (!$this->noController
) {
703 [$optionValueID, $optionValue] = CRM_Report_Utils_Report
::getValueIDFromUrl();
704 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
705 if (($instanceCount > 0) && $optionValueID) {
706 $this->assign('instanceUrl',
707 CRM_Utils_System
::url('civicrm/report/list',
708 "reset=1&ovid=$optionValueID"
712 if ($optionValueID) {
713 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
717 $this->assign('mode', 'template');
720 // lets display the Report Settings section
721 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
723 // Do not display Report Settings section if administer Reports permission is absent OR
724 // if report instance is reserved and administer reserved reports absent
725 if (!CRM_Core_Permission
::check('administer Reports') ||
726 (!empty($this->_instanceValues
['is_reserved']) &&
727 !CRM_Core_Permission
::check('administer reserved reports'))
729 $this->_instanceForm
= FALSE;
732 $this->assign('criteriaForm', FALSE);
733 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
734 if (CRM_Core_Permission
::check('administer Reports') ||
735 CRM_Core_Permission
::check('access Report Criteria')
737 if (empty($this->_instanceValues
['is_reserved']) ||
738 CRM_Core_Permission
::check('administer reserved reports')
740 $this->assign('criteriaForm', TRUE);
741 $this->_criteriaForm
= TRUE;
745 // Special permissions check for private instance if it's not the current contact instance
747 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
748 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
749 if (!CRM_Core_Permission
::check('access all private reports')) {
750 $this->_instanceForm
= FALSE;
751 $this->assign('criteriaForm', FALSE);
755 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
756 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
757 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
758 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
764 public function addBreadCrumb() {
768 'title' => ts('Report Templates'),
769 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
773 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
777 * Pre process function.
779 * Called prior to build form.
781 public function preProcess() {
782 $this->preProcessCommon();
785 $this->addBreadCrumb();
788 foreach ($this->_columns
as $tableName => $table) {
789 $this->setTableAlias($table, $tableName);
792 // higher preference to bao object
793 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
796 if (method_exists($daoOrBaoName, 'exportableFields')) {
797 $expFields = $daoOrBaoName::exportableFields();
800 $expFields = $daoOrBaoName::export();
804 $doNotCopy = ['required', 'default'];
806 $fieldGroups = ['fields', 'filters', 'group_bys', 'order_bys'];
807 foreach ($fieldGroups as $fieldGrp) {
808 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
809 foreach ($table[$fieldGrp] as $fieldName => $field) {
810 // $name is the field name used to reference the BAO/DAO export fields array
811 $name = $field['name'] ??
$fieldName;
813 // Sometimes the field name key in the BAO/DAO export fields array is
814 // different from the actual database field name.
815 // Unset $field['name'] so that actual database field name can be obtained
816 // from the BAO/DAO export fields array.
817 unset($field['name']);
819 if (array_key_exists($name, $expFields)) {
820 foreach ($doNotCopy as $dnc) {
821 // unset the values we don't want to be copied.
822 unset($expFields[$name][$dnc]);
825 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
828 foreach ($expFields[$name] as $property => $val) {
829 if (!array_key_exists($property, $field)) {
830 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
837 if (!empty($field['no_repeat'])) {
838 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
840 if (!empty($field['no_display'])) {
841 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
844 // set alias = table-name, unless already set
845 $alias = $field['alias'] ??
(
846 $this->_columns
[$tableName]['alias'] ??
$tableName
848 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
850 // set name = fieldName, unless already set
851 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
852 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
855 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
856 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
859 // set dbAlias = alias.name, unless already set
860 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
861 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
863 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
866 // a few auto fills for filters
867 if ($fieldGrp == 'filters') {
868 // fill operator types
869 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
870 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
871 case CRM_Utils_Type
::T_MONEY
:
872 case CRM_Utils_Type
::T_FLOAT
:
873 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
876 case CRM_Utils_Type
::T_INT
:
877 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
880 case CRM_Utils_Type
::T_DATE
:
881 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
884 case CRM_Utils_Type
::T_BOOLEAN
:
885 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
886 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
887 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
898 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
900 // with multiple options operator-type is generally multi-select
901 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
902 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
904 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
911 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
912 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
915 $this->_columns
[$tableName]['metadata'][$fieldName] = array_merge($this->_columns
[$tableName][$fieldGrp][$fieldName], $this->_columns
[$tableName]['metadata'][$fieldName]);
921 // copy filters to a separate handy variable
922 if (array_key_exists('filters', $table)) {
923 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
926 if (array_key_exists('group_bys', $table)) {
927 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
930 if (array_key_exists('fields', $table)) {
931 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
936 $this->setDefaultValues(FALSE);
939 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
940 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
941 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
942 CRM_Report_Utils_Get
::processChart($this->_defaults
);
945 $this->_formValues
= $this->_defaults
;
946 $this->postProcess();
951 * Set default values.
953 * @param bool $freeze
957 public function setDefaultValues($freeze = TRUE) {
960 // FIXME: generalizing form field naming conventions would reduce
961 // Lots of lines below.
962 foreach ($this->_columns
as $tableName => $table) {
963 if (array_key_exists('fields', $table)) {
964 foreach ($table['fields'] as $fieldName => $field) {
965 if (empty($field['no_display'])) {
966 if (!empty($field['required'])) {
968 $this->_defaults
['fields'][$fieldName] = 1;
971 // find element object, so that we could use quickform's freeze method
972 // for required elements
973 $obj = $this->getElementFromGroup("fields", $fieldName);
975 $freezeGroup[] = $obj;
979 elseif (isset($field['default'])) {
980 $this->_defaults
['fields'][$fieldName] = $field['default'];
986 if (array_key_exists('group_bys', $table)) {
987 foreach ($table['group_bys'] as $fieldName => $field) {
988 if (isset($field['default'])) {
989 if (!empty($field['frequency'])) {
990 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
992 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
996 if (array_key_exists('filters', $table)) {
997 foreach ($table['filters'] as $fieldName => $field) {
998 if (isset($field['default'])) {
999 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
1001 if (is_array($field['default'])) {
1002 $this->_defaults
["{$fieldName}_from"] = $field['default']['from'] ??
NULL;
1003 $this->_defaults
["{$fieldName}_to"] = $field['default']['to'] ??
NULL;
1004 $this->_defaults
["{$fieldName}_relative"] = 0;
1007 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
1011 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
1012 $this->_defaults
["{$fieldName}_min"] = $field['default']['min'] ??
NULL;
1013 $this->_defaults
["{$fieldName}_max"] = $field['default']['max'] ??
NULL;
1015 $this->_defaults
["{$fieldName}_value"] = $field['default'];
1018 //assign default value as "in" for multiselect
1019 //operator, To freeze the select element
1020 if (CRM_Utils_Array
::value('operatorType', $field) ==
1021 CRM_Report_Form
::OP_MULTISELECT
1023 $this->_defaults
["{$fieldName}_op"] = 'in';
1025 if (CRM_Utils_Array
::value('operatorType', $field) ==
1026 CRM_Report_Form
::OP_ENTITYREF
1028 $this->_defaults
["{$fieldName}_op"] = 'in';
1030 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
1031 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
1033 $this->_defaults
["{$fieldName}_op"] = 'mhas';
1035 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
1036 $this->_defaults
["{$fieldName}_op"] = $op;
1042 empty($this->_formValues
['order_bys']) &&
1043 (array_key_exists('order_bys', $table) &&
1044 is_array($table['order_bys']))
1046 if (!array_key_exists('order_bys', $this->_defaults
)) {
1047 $this->_defaults
['order_bys'] = [];
1049 foreach ($table['order_bys'] as $fieldName => $field) {
1050 if (!empty($field['default']) ||
!empty($field['default_order']) ||
1051 CRM_Utils_Array
::value('default_is_section', $field) ||
1052 !empty($field['default_weight'])
1055 'column' => $fieldName,
1056 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
1057 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
1060 if (!empty($field['default_weight'])) {
1061 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
1064 array_unshift($this->_defaults
['order_bys'], $order_by);
1070 foreach ($this->_options
as $fieldName => $field) {
1071 if (isset($field['default'])) {
1072 $this->_defaults
['options'][$fieldName] = $field['default'];
1077 if (!empty($this->_submitValues
)) {
1078 $this->preProcessOrderBy($this->_submitValues
);
1081 $this->preProcessOrderBy($this->_defaults
);
1084 // lets finish freezing task here itself
1085 if (!empty($freezeGroup)) {
1086 foreach ($freezeGroup as $elem) {
1091 if ($this->_formValues
) {
1092 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1095 if ($this->_instanceValues
) {
1096 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1099 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1101 return $this->_defaults
;
1105 * Get element from group.
1107 * @param string $group
1108 * @param string $grpFieldName
1112 public function getElementFromGroup($group, $grpFieldName) {
1113 $eleObj = $this->getElement($group);
1114 foreach ($eleObj->_elements
as $index => $obj) {
1115 if ($grpFieldName == $obj->_attributes
['name']) {
1123 * Setter for $_params.
1125 * @param array $params
1127 public function setParams($params) {
1128 $this->_params
= $params;
1132 * Getter for $_params.
1134 * @return void|array $params
1136 public function getParams() {
1137 return $this->_params
;
1143 * @param int $instanceID
1145 public function setID($instanceID) {
1146 $this->_id
= $instanceID;
1154 public function getID() {
1159 * Getter for _outputMode
1161 * Note you can implement hook_civicrm_alterReportVar('actions', ...)
1162 * which indirectly allows setting _outputMode if the user chooses
1167 public function getOutputMode():string {
1168 return $this->_outputMode
;
1172 * Getter for report header form field value
1176 public function getReportHeader():string {
1177 return $this->_formValues
['report_header'] ??
'';
1181 * Getter for report footer form field value
1185 public function getReportFooter():string {
1186 return $this->_formValues
['report_footer'] ??
'';
1190 * Setter for $_force.
1192 * @param bool $isForce
1194 public function setForce($isForce) {
1195 $this->_force
= $isForce;
1199 * Setter for $_limitValue.
1201 * @param int $_limitValue
1203 public function setLimitValue($_limitValue) {
1204 $this->_limitValue
= $_limitValue;
1208 * Setter for $_offsetValue.
1210 * @param int $_offsetValue
1212 public function setOffsetValue($_offsetValue) {
1213 $this->_offsetValue
= $_offsetValue;
1217 * Setter for $addPaging.
1219 * @param bool $value
1221 public function setAddPaging($value) {
1222 $this->addPaging
= $value;
1226 * Getter for $_defaultValues.
1230 public function getDefaultValues() {
1231 return $this->_defaults
;
1235 * Remove any temporary tables.
1237 public function cleanUpTemporaryTables() {
1238 foreach ($this->temporaryTables
as $temporaryTable) {
1239 CRM_Core_DAO
::executeQuery('DROP ' . ($temporaryTable['temporary'] ?
'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']);
1244 * Create a temporary table.
1246 * This function creates a table AND adds the details to the developer tab & $this->>temporary tables.
1248 * @param string $identifier
1249 * This is the key that will be used for the table in the temporaryTables property.
1250 * @param string $sql
1251 * Sql select statement or column description (the latter requires the columns flag)
1252 * @param bool $isColumns
1253 * Is the sql describing columns to create (rather than using a select query).
1254 * @param bool $isMemory
1255 * Create a memory table rather than a normal INNODB table.
1259 public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) {
1260 $tempTable = CRM_Utils_SQL_TempTable
::build();
1262 $tempTable->setMemory();
1265 $tempTable->createWithColumns($sql);
1268 $tempTable->createWithQuery($sql);
1270 $name = $tempTable->getName();
1271 // Developers may force tables to be durable to assist in debugging so lets check.
1272 $isNotTrueTemporary = $tempTable->isDurable();
1273 $this->addToDeveloperTab($tempTable->getCreateSql());
1274 $this->temporaryTables
[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name];
1279 * Add columns to report.
1281 public function addColumns() {
1284 foreach ($this->_columns
as $tableName => $table) {
1285 if (array_key_exists('fields', $table)) {
1286 foreach ($table['fields'] as $fieldName => $field) {
1288 if (empty($field['no_display'])) {
1289 foreach (['table', 'field'] as $var) {
1290 if (!empty($
{$var}['grouping'])) {
1291 if (!is_array($
{$var}['grouping'])) {
1292 $tableName = $
{$var}['grouping'];
1295 $tableName = array_keys($
{$var}['grouping']);
1296 $tableName = $tableName[0];
1297 $groupTitle = array_values($
{$var}['grouping']);
1298 $groupTitle = $groupTitle[0];
1303 if (!$groupTitle && isset($table['group_title'])) {
1304 $groupTitle = $table['group_title'];
1305 // Having a group_title is secret code for being a custom group
1306 // which cryptically translates to needing an accordion.
1307 // here we make that explicit.
1308 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1311 $colGroups[$tableName]['fields'][$fieldName] = $field['title'] ??
NULL;
1312 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1313 $colGroups[$tableName]['group_title'] = $groupTitle;
1315 $options[$fieldName] = $field['title'] ??
NULL;
1321 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1322 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1324 if (!empty($colGroups)) {
1325 $this->tabs
['FieldSelection'] = [
1326 'title' => ts('Columns'),
1327 'tpl' => 'FieldSelection',
1328 'div_label' => 'col-groups',
1331 // Note this assignment is only really required in buildForm. It is being 'over-called'
1332 // to reduce risk of being missed due to overridden functions.
1333 $this->assign('tabs', $this->tabs
);
1336 $this->assign('colGroups', $colGroups);
1340 * Add filters to report.
1342 public function addFilters() {
1343 $filters = $filterGroups = [];
1345 foreach ($this->_filters
as $table => $attributes) {
1346 $groupingKey = $this->_columns
[$table]['grouping'] ??
'';
1347 $filterGroups[$groupingKey]['tables'][$table] = [];
1348 // If a prior table hasn't set group title then set it.
1349 if (empty($filterGroups[$groupingKey]['group_title'])) {
1350 $filterGroups[$groupingKey]['group_title'] = $this->_columns
[$table]['group_title'] ??
'';
1352 // The presence of 'group_title' is secret code for 'display in an accordion'
1353 // here we make this explicit.
1354 if (!isset($filterGroups[$groupingKey]['use_accordion_for_field_selection'])) {
1355 if (isset($this->_columns
[$table]['use_accordion_for_field_selection'])) {
1356 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = $this->_columns
[$table]['use_accordion_for_field_selection'];
1359 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = isset($this->_columns
[$table]['group_title']);
1363 foreach ($attributes as $fieldName => $field) {
1364 $filterGroups[$groupingKey]['tables'][$table][$fieldName] = $field;
1365 // Filters is deprecated in favour of filterGroups.
1366 $filters[$table][$fieldName] = $field;
1367 // get ready with option value pair
1368 // @ 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
1370 $operations = $this->getOperationPair(
1371 CRM_Utils_Array
::value('operatorType', $field),
1374 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1375 case CRM_Report_Form
::OP_MONTH
:
1376 if (!array_key_exists('options', $field) ||
1377 !is_array($field['options']) ||
empty($field['options'])
1379 // If there's no option list for this filter, define one.
1380 $field['options'] = CRM_Utils_Date
::getFullMonthNames();
1382 // Add this option list to this column _columns. This is
1383 // required so that filter statistics show properly.
1384 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1386 case CRM_Report_Form
::OP_MULTISELECT
:
1387 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1388 // assume a multi-select field
1389 if (!empty($field['options']) ||
1390 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1392 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1393 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1396 if (count($operations) <= 1) {
1399 if ($fieldName == 'state_province_id' ||
1400 $fieldName == 'county_id'
1402 $this->addChainSelect($fieldName . '_value', [
1409 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], [
1410 'style' => 'min-width:250px',
1411 'class' => 'crm-select2 huge',
1413 'placeholder' => ts('- select -'),
1419 case CRM_Report_Form
::OP_SELECT
:
1420 // assume a select field
1421 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1422 if (!empty($field['options'])) {
1423 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1427 case CRM_Report_Form
::OP_ENTITYREF
:
1428 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1429 $this->setEntityRefDefaults($field, $table);
1430 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1433 case CRM_Report_Form
::OP_DATE
:
1434 // build datetime fields
1435 $this->addDatePickerRange($fieldName, $field['title'], FALSE, FALSE, 'From', 'To', $operations, '_to', '_from');
1438 case CRM_Report_Form
::OP_DATETIME
:
1439 // build datetime fields
1440 $this->addDatePickerRange($fieldName, $field['title'], TRUE, FALSE, 'From', 'To', $operations, '_to', '_from');
1443 case CRM_Report_Form
::OP_INT
:
1444 case CRM_Report_Form
::OP_FLOAT
:
1445 // and a min value input box
1446 $this->add('text', "{$fieldName}_min", ts('Min'));
1447 // and a max value input box
1448 $this->add('text', "{$fieldName}_max", ts('Max'));
1450 // default type is string
1451 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1452 ['onchange' => "return showHideMaxMinVal( '$fieldName', this.value );"]
1454 // we need text box for value input
1455 $this->add('text', "{$fieldName}_value", NULL, ['class' => 'huge']);
1460 if (!empty($filterGroups)) {
1461 $this->tabs
['Filters'] = [
1462 'title' => ts('Filters'),
1464 'div_label' => 'set-filters',
1467 $this->assign('filterGroups', $filterGroups);
1468 // Filters is deprecated in favour of filterGroups.
1469 $this->assign('filters', $filters);
1473 * Function to assign the tabs to the template in the correct order.
1475 * We want the tabs to wind up in this order (if not overridden).
1483 protected function assignTabs() {
1491 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1492 $order = array_merge($order, $this->tabs
);
1493 $this->assign('tabs', $order);
1497 * The intent is to add a tab for developers to view the sql.
1499 * Currently using dpm.
1501 * @param string $sql
1503 public function addToDeveloperTab($sql) {
1504 if (!CRM_Core_Permission
::check('view report sql')) {
1507 $ignored_output_modes = ['pdf', 'csv', 'print'];
1508 if (in_array($this->_outputMode
, $ignored_output_modes)) {
1511 $this->tabs
['Developer'] = [
1512 'title' => ts('Developer'),
1513 'tpl' => 'Developer',
1514 'div_label' => 'set-developer',
1517 $this->assignTabs();
1518 $this->sqlFormattedArray
= [];
1519 $this->sqlArray
[] = $sql;
1520 foreach ($this->sqlArray
as $sql) {
1521 foreach (['LEFT JOIN'] as $term) {
1522 $sql = str_replace($term, '<br> ' . $term, $sql);
1524 foreach (['FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';'] as $term) {
1525 $sql = str_replace($term, '<br><br>' . $term, $sql);
1527 $this->sqlFormattedArray
[] = $sql;
1528 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1530 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL
::getSqlModes());
1535 * Add options defined in $this->_options to the report.
1537 public function addOptions() {
1538 if (!empty($this->_options
)) {
1539 // FIXME: For now lets build all elements as checkboxes.
1540 // Once we clear with the format we can build elements based on type
1542 foreach ($this->_options
as $fieldName => $field) {
1545 if ($field['type'] == 'select') {
1546 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1548 elseif ($field['type'] == 'checkbox') {
1549 $options[$field['title']] = $fieldName;
1550 $this->addCheckBox($fieldName, NULL,
1552 NULL, NULL, NULL, $this->_fourColumnAttribute
1557 if (!empty($this->_options
) &&
1559 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1561 $this->tabs
['ReportOptions'] = [
1562 'title' => ts('Display Options'),
1563 'tpl' => 'ReportOptions',
1564 'div_label' => 'other-options',
1567 $this->assign('otherOptions', $this->_options
);
1571 * Add chart options to the report.
1573 public function addChartOptions() {
1574 if (!empty($this->_charts
)) {
1575 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1576 $this->assign('charts', $this->_charts
);
1577 $this->addElement('xbutton', $this->_chartButtonName
, ts('View'), ['type' => 'submit']);
1582 * Add group by options to the report.
1584 public function addGroupBys() {
1585 $options = $freqElements = [];
1587 foreach ($this->_columns
as $tableName => $table) {
1588 if (array_key_exists('group_bys', $table)) {
1589 foreach ($table['group_bys'] as $fieldName => $field) {
1590 if (!empty($field) && empty($field['no_display'])) {
1591 $options[$field['title']] = $fieldName;
1592 if (!empty($field['frequency'])) {
1593 $freqElements[$field['title']] = $fieldName;
1599 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1600 NULL, NULL, NULL, $this->_fourColumnAttribute
1602 $this->assign('groupByElements', $options);
1603 if (!empty($options)) {
1604 $this->tabs
['GroupBy'] = [
1605 'title' => ts('Grouping'),
1607 'div_label' => 'group-by-elements',
1611 foreach ($freqElements as $name) {
1612 $this->addElement('select', "group_bys_freq[$name]",
1613 ts('Frequency'), $this->_groupByDateFreq
1619 * Add data for order by tab.
1621 public function addOrderBys() {
1623 foreach ($this->_columns
as $tableName => $table) {
1625 // Report developer may define any column to order by; include these as order-by options.
1626 if (array_key_exists('order_bys', $table)) {
1627 foreach ($table['order_bys'] as $fieldName => $field) {
1628 if (!empty($field)) {
1629 $options[$fieldName] = $field['title'];
1634 // Add searchable custom fields as order-by options, if so requested
1635 // (These are already indexed, so allowing to order on them is cheap.)
1637 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1638 array_key_exists('extends', $table) && !empty($table['extends'])
1640 foreach ($table['fields'] as $fieldName => $field) {
1641 if (empty($field['no_display'])) {
1642 $options[$fieldName] = $field['title'];
1650 $this->assign('orderByOptions', $options);
1651 if (!empty($options)) {
1652 $this->tabs
['OrderBy'] = [
1653 'title' => ts('Sorting'),
1655 'div_label' => 'order-by-elements',
1659 if (!empty($options)) {
1661 '-' => ts(' - none - '),
1663 for ($i = 1; $i <= 5; $i++
) {
1664 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1665 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
1666 'ASC' => ts('Ascending'),
1667 'DESC' => ts('Descending'),
1669 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, ['id' => "order_by_section_$i"]);
1670 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, ['id' => "order_by_pagebreak_$i"]);
1676 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1678 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1679 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1682 public function buildInstanceAndButtons() {
1683 CRM_Report_Form_Instance
::buildForm($this);
1684 $this->_actionButtonName
= $this->getButtonName('submit');
1685 $this->addTaskMenu($this->getActions($this->_id
));
1687 $this->assign('instanceForm', $this->_instanceForm
);
1689 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1690 $permission = CRM_Core_Permission
::getPermission();
1691 if ($this->_instanceForm
&& $permission == CRM_Core_Permission
::EDIT
&&
1692 $this->_add2groupSupported
1694 $this->addElement('select', 'groups', ts('Group'),
1695 ['' => ts('Add Contacts to Group')] +
1696 CRM_Core_PseudoConstant
::nestedGroup(),
1697 ['class' => 'crm-select2 crm-action-menu fa-plus huge']
1699 $this->assign('group', TRUE);
1702 $this->addElement('xbutton', $this->_groupButtonName
, '', [
1704 'style' => 'display: none;',
1707 $this->addChartOptions();
1708 $showResultsLabel = $this->getResultsLabel();
1712 'name' => $showResultsLabel,
1713 'isDefault' => TRUE,
1719 * Has this form been submitted already?
1723 public function resultsDisplayed() {
1724 $buttonName = $this->controller
->getButtonName();
1725 return ($buttonName ||
$this->_outputMode
);
1729 * Get the actions for this report instance.
1731 * @param int $instanceId
1735 protected function getActions($instanceId) {
1736 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1737 if (empty($instanceId)) {
1738 $actions['report_instance.save'] = [
1739 'title' => ts('Create Report'),
1741 'is_confirm' => TRUE,
1742 'confirm_title' => ts('Create Report'),
1743 'confirm_refresh_fields' => json_encode([
1744 'title' => ['selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''],
1745 'description' => ['selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''],
1749 unset($actions['report_instance.delete']);
1752 if (!$this->_csvSupported
) {
1753 unset($actions['report_instance.csv']);
1756 CRM_Utils_Hook
::alterReportVar('actions', $actions, $this);
1762 * Main build form function.
1764 public function buildQuickForm() {
1765 $this->addColumns();
1767 $this->addFilters();
1769 $this->addOptions();
1771 $this->addGroupBys();
1773 $this->addOrderBys();
1775 $this->buildInstanceAndButtons();
1777 // Add form rule for report.
1782 $this->addFormRule([get_class($this), 'formRule'], $this);
1784 $this->assignTabs();
1788 * A form rule function for custom data.
1790 * The rule ensures that fields selected in group_by if any) should only be the ones
1791 * present in display/select fields criteria;
1792 * note: works if and only if any custom field selected in group_by.
1794 * @param array $fields
1795 * @param array $ignoreFields
1799 public function customDataFormRule($fields, $ignoreFields = []) {
1801 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1802 !empty($fields['group_bys'])
1804 foreach ($this->_columns
as $tableName => $table) {
1805 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1806 substr($tableName, 0, 12) == 'custom_value') &&
1807 !empty($this->_columns
[$tableName]['fields'])
1809 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1810 if (array_key_exists($fieldName, $fields['group_bys']) &&
1811 !array_key_exists($fieldName, $fields['fields'])
1813 $errors['fields'] = ts("Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.");
1815 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1816 foreach ($fields['fields'] as $fld => $val) {
1817 if (!array_key_exists($fld, $fields['group_bys']) &&
1818 !in_array($fld, $ignoreFields)
1820 $errors['fields'] = ts("Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.");
1832 * Get operators to display on form.
1834 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1836 * @param string $type
1837 * @param string $fieldName
1841 public function getOperationPair($type = "string", $fieldName = NULL) {
1842 // FIXME: At some point we should move these key-val pairs
1843 // to option_group and option_value table.
1845 case CRM_Report_Form
::OP_INT
:
1846 case CRM_Report_Form
::OP_FLOAT
:
1849 'lte' => ts('Is less than or equal to'),
1850 'gte' => ts('Is greater than or equal to'),
1851 'bw' => ts('Is between'),
1852 'eq' => ts('Is equal to'),
1853 'lt' => ts('Is less than'),
1854 'gt' => ts('Is greater than'),
1855 'neq' => ts('Is not equal to'),
1856 'nbw' => ts('Is not between'),
1857 'nll' => ts('Is empty (Null)'),
1858 'nnll' => ts('Is not empty (Null)'),
1862 case CRM_Report_Form
::OP_SELECT
:
1864 'eq' => ts('Is equal to'),
1868 case CRM_Report_Form
::OP_MONTH
:
1869 case CRM_Report_Form
::OP_MULTISELECT
:
1870 case CRM_Report_Form
::OP_ENTITYREF
:
1873 'in' => ts('Is one of'),
1874 'notin' => ts('Is not one of'),
1875 'nll' => ts('Is empty (Null)'),
1876 'nnll' => ts('Is not empty (Null)'),
1880 case CRM_Report_Form
::OP_DATE
:
1883 'nll' => ts('Is empty (Null)'),
1884 'nnll' => ts('Is not empty (Null)'),
1888 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1889 // use this operator for the values, concatenated with separator. For e.g if
1890 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1892 'mhas' => ts('Is one of'),
1893 'mnot' => ts('Is not one of'),
1894 'nll' => ts('Is empty (Null)'),
1895 'nnll' => ts('Is not empty (Null)'),
1902 'has' => ts('Contains'),
1903 'sw' => ts('Starts with'),
1904 'ew' => ts('Ends with'),
1905 'nhas' => ts('Does not contain'),
1906 'eq' => ts('Is equal to'),
1907 'neq' => ts('Is not equal to'),
1908 'nll' => ts('Is empty (Null)'),
1909 'nnll' => ts('Is not empty (Null)'),
1916 * Build the tag filter field to display on the filters tab.
1918 public function buildTagFilter() {
1919 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1920 if (!empty($contactTags)) {
1921 $this->_columns
['civicrm_tag'] = [
1922 'dao' => 'CRM_Core_DAO_Tag',
1926 'title' => ts('Tag'),
1927 'type' => CRM_Utils_Type
::T_INT
,
1929 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1930 'options' => $contactTags,
1938 * Adds group filters to _columns (called from _Construct).
1940 public function buildGroupFilter() {
1941 $this->_columns
['civicrm_group']['filters'] = [
1943 'name' => 'group_id',
1944 'title' => ts('Group'),
1945 'type' => CRM_Utils_Type
::T_INT
,
1946 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1948 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1951 if (empty($this->_columns
['civicrm_group']['dao'])) {
1952 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1954 if (empty($this->_columns
['civicrm_group']['alias'])) {
1955 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1960 * Get SQL operator from form text version.
1962 * @param string $operator
1966 public function getSQLOperator($operator = "like") {
1967 switch ($operator) {
2000 return 'IS NOT NULL';
2009 * Generate where clause.
2011 * This can be overridden in reports for special treatment of a field
2013 * @param array $field Field specifications
2014 * @param string $op Query operator (not an exact match to sql)
2015 * @param mixed $value
2019 * @return null|string
2021 public function whereClause(&$field, $op, $value, $min, $max) {
2023 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
2025 // CRM-18010: Ensure type of each report filters
2027 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
2034 if (($min !== NULL && strlen($min) > 0) ||
2035 ($max !== NULL && strlen($max) > 0)
2039 $min = CRM_Utils_Type
::escape($min, $type);
2041 $clauses[] = "( {$field['dbAlias']} >= $min )";
2044 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
2048 $max = CRM_Utils_Type
::escape($max, $type);
2050 $clauses[] = "( {$field['dbAlias']} <= $max )";
2053 $clauses[] = "( {$field['dbAlias']} > $max )";
2057 if (!empty($clauses)) {
2059 $clause = implode(' AND ', $clauses);
2062 $clause = '(' . implode('OR', $clauses) . ')';
2070 if ($value !== NULL && strlen($value) > 0) {
2071 $value = CRM_Utils_Type
::escape($value, $type);
2072 if (strpos($value, '%') === FALSE) {
2073 $value = "'%{$value}%'";
2076 $value = "'{$value}'";
2078 $sqlOP = $this->getSQLOperator($op);
2079 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2085 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
2086 $value = explode(',', $value);
2088 if ($value !== NULL && is_array($value) && count($value) > 0) {
2089 $sqlOP = $this->getSQLOperator($op);
2090 if (CRM_Utils_Array
::value('type', $field) ==
2091 CRM_Utils_Type
::T_STRING
2093 //cycle through selections and escape values
2094 foreach ($value as $key => $selection) {
2095 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
2098 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
2102 // for numerical values
2103 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
2106 if ($op == 'notin') {
2107 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
2110 $clause = "( " . $clause . " )";
2117 // multiple has or multiple not
2118 if ($value !== NULL && count($value) > 0) {
2119 $value = CRM_Utils_Type
::escapeAll($value, $type);
2120 $operator = $op == 'mnot' ?
'NOT' : '';
2121 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2122 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2128 if ($value !== NULL && strlen($value) > 0) {
2129 $value = CRM_Utils_Type
::escape($value, $type);
2130 if (strpos($value, '%') === FALSE) {
2132 $value = "'{$value}%'";
2135 $value = "'%{$value}'";
2139 $value = "'{$value}'";
2141 $sqlOP = $this->getSQLOperator($op);
2142 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2147 if ($type == 'String') {
2148 $sqlOP = $this->getSQLOperator($op);
2149 $clause = "( {$field['dbAlias']} $sqlOP OR {$field['dbAlias']} = '' )";
2152 $sqlOP = $this->getSQLOperator($op);
2153 $clause = "( {$field['dbAlias']} $sqlOP )";
2158 if ($type == 'String') {
2159 $sqlOP = $this->getSQLOperator($op);
2160 $clause = "( {$field['dbAlias']} $sqlOP AND {$field['dbAlias']} <> '' )";
2163 $sqlOP = $this->getSQLOperator($op);
2164 $clause = "( {$field['dbAlias']} $sqlOP )";
2171 //CRM-18457: some custom field passes value in array format against binary operator
2172 if (is_array($value) && count($value)) {
2177 if ($value !== NULL && $value !== '') {
2178 if (isset($field['clause'])) {
2179 // FIXME: we not doing escape here. Better solution is to use two
2180 // different types - data-type and filter-type
2181 $clause = $field['clause'];
2183 elseif (!is_array($value)) {
2184 $value = CRM_Utils_Type
::escape($value, $type);
2185 $sqlOP = $this->getSQLOperator($op);
2186 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
2187 $value = "'{$value}'";
2189 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2195 //dev/core/544 Add report support for multiple contact subTypes
2196 if ($field['name'] == 'contact_sub_type' && $clause) {
2197 $clause = $this->whereSubtypeClause($field, $value, $op);
2199 if (!empty($field['group']) && $clause) {
2200 $clause = $this->whereGroupClause($field, $value, $op);
2202 elseif (!empty($field['tag']) && $clause) {
2203 // not using left join in query because if any contact
2204 // belongs to more than one tag, results duplicate
2206 $clause = $this->whereTagClause($field, $value, $op);
2208 elseif (!empty($field['membership_org']) && $clause) {
2209 $clause = $this->whereMembershipOrgClause($value, $op);
2211 elseif (!empty($field['membership_type']) && $clause) {
2212 $clause = $this->whereMembershipTypeClause($value, $op);
2218 * Get SQL where clause for contact subtypes
2219 * @param string $field
2220 * @param mixed $value
2221 * @param string $op SQL Operator
2225 public function whereSubtypeClause($field, $value, $op) {
2226 // Get the correct SQL operator.
2231 $clauseSeparator = ' AND ';
2237 $clauseSeparator = ' OR ';
2240 $sqlOp = $this->getSQLOperator($op);
2241 if ($sqlOp == 'IS NULL' ||
$sqlOp == 'IS NOT NULL') {
2242 $clause = "{$field['dbAlias']} $sqlOp";
2246 foreach ($value as $item) {
2247 $subclauses[] = "( {$field['dbAlias']} $sqlOp '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $item . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' )";
2249 $clause = implode($clauseSeparator, $subclauses);
2251 $clause = "( $clause )";
2253 $clause = "( ( {$field['dbAlias']} IS NULL ) OR $clause )";
2259 * Get SQL where clause for a date field.
2261 * @param string $fieldName
2262 * @param string $relative
2263 * @param string $from
2265 * @param string $type
2266 * @param string $fromTime
2267 * @param string $toTime
2269 * @return null|string
2271 public function dateClause(
2273 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2276 if (array_key_exists($relative, $this->getOperationPair(CRM_Report_Form
::OP_DATE
))) {
2277 $sqlOP = $this->getSQLOperator($relative);
2278 return "( {$fieldName} {$sqlOP} )";
2280 if (strlen($to) === 10) {
2281 // If we just have the date we assume the end of that day.
2286 [$from, $to] = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2290 $clauses[] = "( {$fieldName} >= " . date('YmdHis', strtotime($from)) . ')';
2294 $clauses[] = "( {$fieldName} <= " . date('YmdHis', strtotime($to)) . ')';
2296 if (!empty($clauses)) {
2297 return implode(' AND ', $clauses);
2304 * Get values for from and to for date ranges.
2308 * @param bool $relative
2309 * @param string $from
2311 * @param string $fromTime
2312 * @param string $toTime
2316 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2317 if (!empty($fromTime) ||
!empty($toTime)) {
2318 throw new CRM_Core_Exception('Report template needs to be updated as getFromTo no longer supports fromTime or ToTime Parameters');
2320 return CRM_Utils_Date
::getFromTo($relative, $from, $to);
2324 * Alter display of rows.
2326 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2327 * such as rendering contacts as links.
2329 * @param array $rows
2330 * Rows generated by SQL, with an array for each row.
2332 public function alterDisplay(&$rows) {
2336 * Alter the way in which custom data fields are displayed.
2338 * @param array $rows
2340 public function alterCustomDataDisplay(&$rows) {
2341 // custom code to alter rows having custom values
2342 if (empty($this->_customGroupExtends
)) {
2347 $customFieldIds = [];
2348 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2349 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2350 $customFieldIds[$fieldAlias] = $fieldId;
2353 if (empty($customFieldIds)) {
2357 // skip for type date and ContactReference since date format is already handled
2359 SELECT cg.table_name, cf.id
2360 FROM civicrm_custom_field cf
2361 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2362 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2363 cg.is_active = 1 AND
2364 cf.is_active = 1 AND
2365 cf.is_searchable = 1 AND
2366 cf.data_type NOT IN ('ContactReference', 'Date') AND
2367 cf.id IN (" . implode(",", $customFieldIds) . ")";
2369 $dao = CRM_Core_DAO
::executeQuery($query);
2370 while ($dao->fetch()) {
2371 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2374 $entryFound = FALSE;
2375 foreach ($rows as $rowNum => $row) {
2376 foreach ($row as $tableCol => $val) {
2377 if (array_key_exists($tableCol, $customFields)) {
2378 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2383 // skip looking further in rows, if first row itself doesn't
2384 // have the column we need
2392 * Remove duplicate rows.
2394 * @param array $rows
2396 public function removeDuplicates(&$rows) {
2397 if (empty($this->_noRepeats
)) {
2402 foreach ($rows as $key => $list) {
2403 foreach ($list as $colName => $colVal) {
2404 if (array_key_exists($colName, $checkList) &&
2405 $checkList[$colName] == $colVal
2407 $rows[$key][$colName] = "";
2409 if (in_array($colName, $this->_noRepeats
)) {
2410 $checkList[$colName] = $colVal;
2417 * Fix subtotal display.
2420 * @param array $fields
2421 * @param bool $subtotal
2423 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2424 foreach ($row as $colName => $colVal) {
2425 if (in_array($colName, $fields)) {
2427 elseif (isset($this->_columnHeaders
[$colName])) {
2429 $row[$colName] = 'Subtotal';
2433 unset($row[$colName]);
2440 * Calculate grant total.
2442 * @param array $rows
2446 public function grandTotal(&$rows) {
2447 if (!$this->_rollup ||
count($rows) == 1) {
2451 $this->moveSummaryColumnsToTheRightHandSide();
2453 if ($this->_limit
&& count($rows) >= $this->getRowCount()) {
2457 $this->rollupRow
= array_pop($rows);
2459 foreach ($this->_columnHeaders
as $fld => $val) {
2460 if (!in_array($fld, $this->_statFields
)) {
2461 if (!$this->_grandFlag
) {
2462 $this->rollupRow
[$fld] = ts('Grand Total');
2463 $this->_grandFlag
= TRUE;
2466 $this->rollupRow
[$fld] = "";
2471 $this->assign('grandStat', $this->rollupRow
);
2476 * Format display output.
2478 * @param array $rows
2479 * @param bool $pager
2481 public function formatDisplay(&$rows, $pager = TRUE) {
2482 // set pager based on if any limit was applied in the query.
2486 $chartEnabled = !empty($this->_params
['charts']) && !empty($rows);
2487 $this->assign('chartEnabled', $chartEnabled);
2488 // allow building charts if any
2489 if ($chartEnabled) {
2490 $this->buildChart($rows);
2491 $this->_chartId
= "{$this->_params['charts']}_" .
2492 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2493 CRM_Core_Config
::singleton()->userSystem
->getSessionId();
2494 $this->assign('chartId', $this->_chartId
);
2497 // unset columns not to be displayed.
2498 foreach ($this->_columnHeaders
as $key => $value) {
2499 if (!empty($value['no_display'])) {
2500 unset($this->_columnHeaders
[$key]);
2502 foreach (['colspan', 'type'] as $expectedKey) {
2503 if (!isset($this->_columnHeaders
[$key][$expectedKey])) {
2504 // Ensure it is set to prevent smarty notices.
2505 $this->_columnHeaders
[$key][$expectedKey] = FALSE;
2510 // unset columns not to be displayed.
2511 if (!empty($rows)) {
2512 foreach ($this->_noDisplay
as $noDisplayField) {
2513 foreach ($rows as $rowNum => $row) {
2514 unset($this->_columnHeaders
[$noDisplayField]);
2515 $expectedKeys = ['class'];
2516 foreach ($expectedKeys as $expectedKey) {
2517 if (!array_key_exists($expectedKey, $row)) {
2518 $rows[$rowNum][$expectedKey] = NULL;
2525 // Find alter display functions.
2526 $firstRow = reset($rows);
2528 $selectedFields = array_keys($firstRow);
2529 $alterFunctions = $alterMap = $alterSpecs = [];
2530 foreach ($this->_columns
as $tableName => $table) {
2531 if (array_key_exists('metadata', $table)) {
2532 foreach ($table['metadata'] as $field => $specs) {
2533 if (in_array($tableName . '_' . $field, $selectedFields)) {
2534 if (array_key_exists('alter_display', $specs)) {
2535 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2536 $alterMap[$tableName . '_' . $field] = $field;
2537 $alterSpecs[$tableName . '_' . $field] = NULL;
2539 // Add any alters that can be intuited from the field specs.
2540 // So far only boolean but a lot more could be.
2541 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2542 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2543 $alterMap[$tableName . '_' . $field] = $field;
2544 $alterSpecs[$tableName . '_' . $field] = NULL;
2551 // Run the alter display functions
2552 foreach ($rows as $index => & $row) {
2553 foreach ($row as $selectedField => $value) {
2554 if (array_key_exists($selectedField, $alterFunctions) && isset($value)) {
2555 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2561 // use this method for formatting rows for display purpose.
2562 $this->alterDisplay($rows);
2563 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2565 // build array of section totals
2566 $this->sectionTotals();
2568 // process grand-total row
2569 $this->grandTotal($rows);
2571 // use this method for formatting custom rows for display purpose.
2572 $this->alterCustomDataDisplay($rows);
2578 * @param $selectedfield
2579 * @param $criteriaFieldName
2583 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2584 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2585 $row[$selectedfield . '_link'] = $url;
2586 $row[$selectedfield . '_hover'] = ts("%1 for this state.", [
2590 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2591 if (!is_array($states)) {
2599 * @param $selectedField
2600 * @param $criteriaFieldName
2604 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2605 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2606 $row[$selectedField . '_link'] = $url;
2607 $row[$selectedField . '_hover'] = ts("%1 for this country.", [
2610 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2611 if (!is_array($countries)) {
2619 * @param $selectedfield
2620 * @param $criteriaFieldName
2624 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2625 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2626 $row[$selectedfield . '_link'] = $url;
2627 $row[$selectedfield . '_hover'] = ts("%1 for this county.", [
2630 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2631 if (!is_array($counties)) {
2639 * @param $selectedfield
2640 * @param $criteriaFieldName
2644 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2645 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value);
2655 protected function alterContactID($value, &$row, $fieldname) {
2656 $nameField = substr($fieldname, 0, -2) . 'name';
2657 static $first = TRUE;
2658 static $viewContactList = FALSE;
2660 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2663 if (!$viewContactList) {
2666 if (array_key_exists($nameField, $row)) {
2667 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2670 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2682 protected function alterCommunicationtMethod($value, &$row, $fieldname) {
2683 $communicationMethods = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
2685 // Explode padded values.
2686 $values = CRM_utils_array
::explodePadded($value);
2687 // Flip values, compute intersection with $communicationMethods, and implode with commas.
2688 $value = implode(', ', array_intersect_key($communicationMethods, array_flip($values)));
2697 protected function alterBoolean($value) {
2698 $options = [0 => '', 1 => ts('Yes')];
2699 if (isset($options[$value])) {
2700 return $options[$value];
2708 * @param array $rows
2710 public function buildChart(&$rows) {
2711 // override this method for building charts.
2714 // select() method below has been added recently (v3.3), and many of the report templates might
2715 // still be having their own select() method. We should fix them as and when encountered and move
2716 // towards generalizing the select() method below.
2719 * Generate the SELECT clause and set class variable $_select.
2721 public function select() {
2722 $select = $this->_selectAliases
= [];
2723 $this->storeGroupByArray();
2725 foreach ($this->_columns
as $tableName => $table) {
2726 if (array_key_exists('fields', $table)) {
2727 foreach ($table['fields'] as $fieldName => $field) {
2728 if ($tableName == 'civicrm_address') {
2729 // deprecated, use $this->isTableSelected.
2730 $this->_addressField
= TRUE;
2732 if ($tableName == 'civicrm_email') {
2733 $this->_emailField
= TRUE;
2735 if ($tableName == 'civicrm_phone') {
2736 $this->_phoneField
= TRUE;
2739 if (!empty($field['required']) ||
2740 !empty($this->_params
['fields'][$fieldName])
2743 // 1. In many cases we want select clause to be built in slightly different way
2744 // for a particular field of a particular type.
2745 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2747 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2748 if ($selectClause) {
2749 $select[] = $selectClause;
2753 // include statistics columns only if set
2754 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2755 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2759 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2760 if ($selectClause) {
2761 $select[] = $selectClause;
2764 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2771 // select for group bys
2772 if (array_key_exists('group_bys', $table)) {
2773 foreach ($table['group_bys'] as $fieldName => $field) {
2775 if ($tableName == 'civicrm_address') {
2776 $this->_addressField
= TRUE;
2778 if ($tableName == 'civicrm_email') {
2779 $this->_emailField
= TRUE;
2781 if ($tableName == 'civicrm_phone') {
2782 $this->_phoneField
= TRUE;
2784 // 1. In many cases we want select clause to be built in slightly different way
2785 // for a particular field of a particular type.
2786 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2788 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2789 if ($selectClause) {
2790 $select[] = $selectClause;
2794 if (!empty($this->_params
['group_bys']) &&
2795 !empty($this->_params
['group_bys'][$fieldName]) &&
2796 !empty($this->_params
['group_bys_freq'])
2798 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2800 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2801 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2802 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2803 $field['title'] = 'Week';
2807 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2808 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2809 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2810 $field['title'] = 'Year';
2814 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2815 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2816 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2817 $field['title'] = 'Month';
2821 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2822 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2823 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2824 $field['title'] = 'Quarter';
2827 // for graphs and charts -
2828 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2829 $this->_interval
= $field['title'];
2830 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2831 = $field['title'] . ' Beginning';
2832 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2833 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2835 // just to make sure these values are transferred to rows.
2836 // since we 'll need them for calculation purpose,
2837 // e.g making subtotals look nicer or graphs
2838 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
2839 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
2846 if (empty($select)) {
2847 // CRM-21412 Do not give fatal error on report when no fields selected
2851 $this->_selectClauses
= $select;
2852 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2856 * Build select clause for a single field.
2858 * @param string $tableName
2859 * @param string $tableKey
2860 * @param string $fieldName
2861 * @param string $field
2865 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2866 if (!empty($field['pseudofield'])) {
2867 $alias = "{$tableName}_{$fieldName}";
2868 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
2869 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
2870 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = $field['dbAlias'] ??
NULL;
2871 $this->_selectAliases
[] = $alias;
2872 return ' 1 as ' . $alias;
2878 * Build where clause.
2880 public function where() {
2881 $this->storeWhereHavingClauseArray();
2883 if (empty($this->_whereClauses
)) {
2884 $this->_where
= "WHERE ( 1 ) ";
2885 $this->_having
= "";
2888 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2891 if ($this->_aclWhere
) {
2892 $this->_where
.= " AND {$this->_aclWhere} ";
2895 if (!empty($this->_havingClauses
)) {
2896 // use this clause to construct group by clause.
2897 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2902 * Store Where clauses into an array.
2904 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2905 * temp table that may not be part of the final where clause or added
2906 * in other functions
2908 public function storeWhereHavingClauseArray() {
2909 foreach ($this->_columns
as $tableName => $table) {
2910 if (array_key_exists('filters', $table)) {
2911 foreach ($table['filters'] as $fieldName => $field) {
2912 // respect pseudofield to filter spec so fields can be marked as
2913 // not to be handled here
2914 if (!empty($field['pseudofield'])) {
2917 $clause = $this->generateFilterClause($field, $fieldName);
2919 if (!empty($clause)) {
2920 if (!empty($field['having'])) {
2921 $this->_havingClauses
[] = $clause;
2924 $this->_whereClauses
[] = $clause;
2936 public function processReportMode() {
2937 $this->setOutputMode();
2940 = CRM_Utils_Request
::retrieve(
2943 CRM_Core_DAO
::$_nullObject
2946 if ($this->_sendmail
&& !$this->_outputMode
) {
2947 // If we're here from the mail_report job, then the default there gets
2948 // set to pdf before we get here, but if we're somehow here and sending
2949 // by email and don't have a format set, then use print.
2950 // @todo Is this on purpose - why would they be different defaults?
2951 $this->_outputMode
= 'print';
2954 // _outputMode means multiple things and can cover export to file formats,
2955 // like csv, or actions with no output, like save. So this will only set
2956 // a handler if it's one of the former. But it's also possible we have a
2957 // really interesting handler out there. But the point is we don't need to
2958 // know, just to know that a handler doesn't always get set by this call.
2959 $this->setOutputHandler();
2961 if (!empty($this->outputHandler
)) {
2962 if ($this->_sendmail
) {
2963 // If we're sending by email these are the only options that make
2965 $this->printOnly
= TRUE;
2966 $this->addPaging
= FALSE;
2967 $this->_absoluteUrl
= TRUE;
2970 // otherwise ask the handler
2971 $this->printOnly
= $this->outputHandler
->isPrintOnly();
2972 $this->addPaging
= $this->outputHandler
->isAddPaging();
2973 $this->_absoluteUrl
= $this->outputHandler
->isAbsoluteUrl();
2976 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2977 $this->_createNew
= TRUE;
2980 $this->assign('outputMode', $this->_outputMode
);
2981 $this->assign('printOnly', $this->printOnly
);
2982 // Get today's date to include in printed reports
2983 if ($this->printOnly
) {
2984 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2985 $this->assign('reportDate', $reportDate);
2990 * Post Processing function for Form.
2992 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2993 * This function is not accessed when the api calls the report.
2995 public function beginPostProcess() {
2996 $this->setParams($this->controller
->exportValues($this->_name
));
2997 if (empty($this->_params
) &&
3000 $this->setParams($this->_formValues
);
3003 // hack to fix params when submitted from dashboard, CRM-8532
3004 // fields array is missing because form building etc is skipped
3005 // in dashboard mode for report
3006 //@todo - this could be done in the dashboard no we have a setter
3007 if (empty($this->_params
['fields']) && !$this->_noFields
) {
3008 $this->setParams($this->_formValues
);
3011 $this->processReportMode();
3013 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
3014 $this->_createNew
= ($this->_outputMode
== 'copy');
3015 CRM_Report_Form_Instance
::postProcess($this);
3017 if ($this->_outputMode
== 'delete') {
3018 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
3021 $this->_formValues
= $this->_params
;
3023 $this->beginPostProcessCommon();
3027 * BeginPostProcess function run in both report mode and non-report mode (api).
3029 public function beginPostProcessCommon() {
3033 * Build the report query.
3035 * @param bool $applyLimit
3039 public function buildQuery($applyLimit = TRUE) {
3040 $this->buildGroupTempTable();
3043 $this->customDataFrom();
3044 $this->buildPermissionClause();
3049 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
3050 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
3052 $clause = "{$field['dbAlias']} as {$alias}";
3054 $this->_select
.= ", $clause ";
3057 if ($applyLimit && empty($this->_params
['charts'])) {
3060 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
3062 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
3063 $this->addToDeveloperTab($sql);
3068 * Build group by clause.
3070 public function groupBy() {
3071 $this->storeGroupByArray();
3073 if (!empty($this->_groupByArray
)) {
3074 if ($this->optimisedForOnlyFullGroupBy
) {
3075 // We should probably deprecate this code path. What happens here is that
3076 // the group by is amended to reflect the select columns. This often breaks the
3077 // results. Retrofitting group strict group by onto existing report classes
3079 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
3082 $this->_groupBy
= ' GROUP BY ' . implode($this->_groupByArray
);
3088 * Build order by clause.
3090 public function orderBy() {
3091 $this->_orderBy
= "";
3092 $this->_sections
= [];
3093 $this->storeOrderByArray();
3094 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
3095 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
3097 $this->assign('sections', $this->_sections
);
3101 * Extract order by fields and store as an array.
3103 * In some cases other functions want to know which fields are selected for ordering by
3104 * Separating this into a separate function allows it to be called separately from constructing
3105 * the order by clause
3107 public function storeOrderByArray() {
3110 if (!empty($this->_params
['order_bys']) &&
3111 is_array($this->_params
['order_bys']) &&
3112 !empty($this->_params
['order_bys'])
3115 // Process order_bys in user-specified order
3116 foreach ($this->_params
['order_bys'] as $orderBy) {
3118 foreach ($this->_columns
as $tableName => $table) {
3119 if (array_key_exists('order_bys', $table)) {
3120 // For DAO columns defined in $this->_columns
3121 $fields = $table['order_bys'];
3123 elseif (array_key_exists('extends', $table)) {
3124 // For custom fields referenced in $this->_customGroupExtends
3125 $fields = CRM_Utils_Array
::value('fields', $table, []);
3130 if (!empty($fields) && is_array($fields)) {
3131 foreach ($fields as $fieldName => $field) {
3132 if ($fieldName == $orderBy['column']) {
3133 $orderByField = array_merge($field, $orderBy);
3134 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
3141 if (!empty($orderByField)) {
3142 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
3143 if ($this->groupConcatTested
) {
3144 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
3147 // Not sure when this is preferable to using tplField (which has
3148 // definitely been tested to work in cases then this does not.
3149 // in caution not switching unless report has been tested for
3150 // group concat functionality.
3151 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
3154 // Record any section headers for assignment to the template
3155 if (!empty($orderBy['section'])) {
3156 $orderByField['pageBreak'] = $orderBy['pageBreak'] ??
NULL;
3157 $this->_sections
[$orderByField['tplField']] = $orderByField;
3163 $this->_orderByArray
= $orderBys;
3165 $this->assign('sections', $this->_sections
);
3169 * Determine unselected columns.
3173 public function unselectedOrderByColumns() {
3174 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
3178 * Determine unselected columns.
3182 public function unselectedSectionColumns() {
3183 if (is_array($this->_sections
)) {
3184 return array_diff_key($this->_sections
, $this->getSelectColumns());
3192 * Build output rows.
3194 * @param string $sql
3195 * @param array $rows
3197 public function buildRows($sql, &$rows) {
3198 if (!$this->optimisedForOnlyFullGroupBy
) {
3199 CRM_Core_DAO
::disableFullGroupByMode();
3201 $dao = CRM_Core_DAO
::executeQuery($sql);
3202 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
3203 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
3205 CRM_Core_DAO
::reenableFullGroupByMode();
3206 if (!is_array($rows)) {
3210 // use this method to modify $this->_columnHeaders
3211 $this->modifyColumnHeaders();
3213 $unselectedSectionColumns = $this->unselectedSectionColumns();
3215 while ($dao->fetch()) {
3217 foreach ($this->_columnHeaders
as $key => $value) {
3218 if (property_exists($dao, $key)) {
3219 $row[$key] = $dao->$key;
3223 // section headers not selected for display need to be added to row
3224 foreach ($unselectedSectionColumns as $key => $values) {
3225 if (property_exists($dao, $key)) {
3226 $row[$key] = $dao->$key;
3235 * Calculate section totals.
3237 * When "order by" fields are marked as sections, this assigns to the template
3238 * an array of total counts for each section. This data is used by the Smarty
3239 * plugin {sectionTotal}.
3241 public function sectionTotals() {
3243 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3244 if (empty($this->_selectAliases
)) {
3248 if (!empty($this->_sections
)) {
3249 // build the query with no LIMIT clause
3250 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3251 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3253 // pull section aliases out of $this->_sections
3254 $sectionAliases = array_keys($this->_sections
);
3257 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3258 $ifnulls[] = "ifnull($alias, '') as $alias";
3260 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3261 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3263 // Group (un-limited) report by all aliases and get counts. This might
3264 // be done more efficiently when the contents of $sql are known, ie. by
3265 // overriding this method in the report class.
3267 $query = $this->_select
.
3268 ", count(*) as ct from ($sql) as subquery group by " .
3269 implode(", ", $sectionAliases);
3271 // initialize array of total counts
3273 $dao = CRM_Core_DAO
::executeQuery($query);
3274 while ($dao->fetch()) {
3276 // let $this->_alterDisplay translate any integer ids to human-readable values.
3277 $rows[0] = $dao->toArray();
3278 $this->alterDisplay($rows);
3279 $this->alterCustomDataDisplay($rows);
3282 // add totals for all permutations of section values
3285 $aliasCount = count($sectionAliases);
3286 foreach ($sectionAliases as $alias) {
3287 $values[] = $row[$alias];
3288 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3289 if ($i == $aliasCount) {
3290 // the last alias is the lowest-level section header; use count as-is
3291 $totals[$key] = $dao->ct
;
3294 // other aliases are higher level; roll count into their total
3295 $totals[$key] +
= $dao->ct
;
3299 $this->assign('sectionTotals', $totals);
3304 * Modify column headers.
3306 public function modifyColumnHeaders() {
3307 // use this method to modify $this->_columnHeaders
3311 * Move totals columns to the right edge of the table.
3313 * It seems like a more logical layout to have any totals columns on the far right regardless of
3314 * the location of the rest of their table.
3316 public function moveSummaryColumnsToTheRightHandSide() {
3317 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3318 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3322 * Assign rows to the template.
3324 * @param array $rows
3326 public function doTemplateAssignment(&$rows) {
3327 $this->assign('columnHeaders', $this->_columnHeaders
);
3328 $this->assign_by_ref('rows', $rows);
3329 $this->assign('statistics', $this->statistics($rows));
3333 * Build report statistics.
3335 * Override this method to build your own statistics.
3337 * @param array $rows
3341 public function statistics(&$rows) {
3344 $count = count($rows);
3345 // Why do we increment the count for rollup seems to artificially inflate the count.
3346 // It seems perhaps intentional to include the summary row in the count of results - although
3347 // this just seems odd.
3348 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3352 $this->countStat($statistics, $count);
3354 $this->groupByStat($statistics);
3356 $this->filterStat($statistics);
3362 * Add count statistics.
3364 * @param array $statistics
3367 public function countStat(&$statistics, $count) {
3368 $statistics['counts']['rowCount'] = [
3369 'title' => ts('Row(s) Listed'),
3371 'type' => CRM_Utils_Type
::T_INT
,
3374 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3375 $statistics['counts']['rowsFound'] = [
3376 'title' => ts('Total Row(s)'),
3377 'value' => $this->_rowsFound
,
3378 'type' => CRM_Utils_Type
::T_INT
,
3384 * Add group by statistics.
3386 * @param array $statistics
3388 public function groupByStat(&$statistics) {
3389 if (!empty($this->_params
['group_bys']) &&
3390 is_array($this->_params
['group_bys']) &&
3391 !empty($this->_params
['group_bys'])
3393 foreach ($this->_columns
as $tableName => $table) {
3394 if (array_key_exists('group_bys', $table)) {
3395 foreach ($table['group_bys'] as $fieldName => $field) {
3396 if (!empty($this->_params
['group_bys'][$fieldName])) {
3397 $combinations[] = $field['title'];
3402 $statistics['groups'][] = [
3403 'title' => ts('Grouping(s)'),
3404 'value' => implode(' & ', $combinations),
3408 // prevents an e-notice in statistics.tpl.
3409 $statistics['groups'] = [];
3414 * Filter statistics.
3416 * @param array $statistics
3418 public function filterStat(&$statistics) {
3419 foreach ($this->_columns
as $tableName => $table) {
3420 if (array_key_exists('filters', $table)) {
3421 foreach ($table['filters'] as $fieldName => $field) {
3422 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3423 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3424 CRM_Utils_Array
::value('operatorType', $field) !=
3425 CRM_Report_Form
::OP_MONTH
3427 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
3428 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
3429 if (!empty($this->_params
["{$fieldName}_relative"])) {
3430 [$from, $to] = CRM_Utils_Date
::getFromTo($this->_params
["{$fieldName}_relative"], NULL, NULL);
3432 if (strlen($to) === 10) {
3433 // If we just have the date we assume the end of that day.
3438 $from = date('l j F Y, g:iA', strtotime($from));
3441 $to = date('l j F Y, g:iA', strtotime($to));
3443 $statistics['filters'][] = [
3444 'title' => $field['title'],
3445 'value' => ts("Between %1 and %2", [1 => $from, 2 => $to]),
3448 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3449 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3451 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3452 $statistics['filters'][] = [
3453 'title' => $field['title'],
3454 'value' => $pair[$rel],
3459 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
3462 $pair = $this->getOperationPair(
3463 CRM_Utils_Array
::value('operatorType', $field),
3466 $min = $this->_params
["{$fieldName}_min"] ??
NULL;
3467 $max = $this->_params
["{$fieldName}_max"] ??
NULL;
3468 $val = $this->_params
["{$fieldName}_value"] ??
NULL;
3469 if (in_array($op, ['bw', 'nbw']) && ($min ||
$max)) {
3470 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3472 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3473 $this->setEntityRefDefaults($field, $tableName);
3474 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3476 CRM_Utils_Array
::value('api', $field['attributes'], []));
3478 foreach ($result['values'] as $v) {
3479 $values[] = $v['label'];
3481 $value = "{$pair[$op]} " . implode(', ', $values);
3483 elseif ($op == 'nll' ||
$op == 'nnll') {
3484 $value = $pair[$op];
3486 elseif (is_array($val) && (!empty($val))) {
3487 $options = CRM_Utils_Array
::value('options', $field, []);
3488 foreach ($val as $key => $valIds) {
3489 if (isset($options[$valIds])) {
3490 $val[$key] = $options[$valIds];
3493 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3494 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3495 $val = implode(', ', $val);
3496 $value = "{$pair[$op]} " . $val;
3498 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3499 isset($field['options']) &&
3500 is_array($field['options']) && !empty($field['options'])
3502 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3503 CRM_Utils_Array
::value($val, $field['options'], $val);
3506 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3509 if ($value && empty($field['no_display'])) {
3510 $statistics['filters'][] = [
3511 'title' => $field['title'] ??
NULL,
3512 'value' => CRM_Utils_String
::htmlToText($value),
3519 // Prevents an e-notice in statistics.tpl.
3520 $statistics['filters'] = [];
3526 * End post processing.
3528 * @param array|null $rows
3530 public function endPostProcess(&$rows = NULL) {
3531 $this->assign('report_class', get_class($this));
3533 // This is used by unit tests, where _outputMode is intentionally blank.
3534 // Is there a reason it couldn't just always do this? It effectively does
3535 // the same thing anyway by assigning it to the template (in
3536 // doTemplateAssignment()).
3537 if ($this->_storeResultSet
) {
3538 $this->_resultSet
= $rows;
3541 // Add contacts to group
3542 if ($this->_outputMode
== 'group') {
3543 $group = $this->_params
['groups'];
3544 $this->add2group($group);
3547 if ($this->_sendmail
) {
3550 elseif (!empty($this->outputHandler
)) {
3551 $this->outputHandler
->download();
3552 CRM_Utils_System
::civiExit();
3554 // else we don't need to do anything here since it must have been
3555 // outputMode=save or something like that
3560 * Set store result set indicator to TRUE.
3562 * This is used by unit tests, along with getResultSet(), to get just
3563 * the output rows unformatted.
3565 public function storeResultSet() {
3566 $this->_storeResultSet
= TRUE;
3574 public function getResultSet() {
3575 return $this->_resultSet
;
3579 * Get the sql used to generate the report.
3583 public function getReportSql() {
3584 return $this->sqlArray
;
3588 * Use the form name to create the tpl file name.
3592 public function getTemplateFileName() {
3593 $defaultTpl = parent
::getTemplateFileName();
3594 $template = CRM_Core_Smarty
::singleton();
3595 if (!$template->template_exists($defaultTpl)) {
3596 $defaultTpl = 'CRM/Report/Form.tpl';
3602 * Compile the report content.
3604 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3608 public function compileContent() {
3609 $templateFile = $this->getHookedTemplateFileName();
3610 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3611 CRM_Core_Form
::$_template->fetch($templateFile) .
3612 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3616 * Post process function.
3618 public function postProcess() {
3619 // get ready with post process params
3620 $this->beginPostProcess();
3623 $sql = $this->buildQuery();
3625 // build array of result based on column headers. This method also allows
3626 // modifying column headers before using it to build result set i.e $rows.
3628 $this->buildRows($sql, $rows);
3630 // format result set.
3631 $this->formatDisplay($rows);
3633 // assign variables to templates
3634 $this->doTemplateAssignment($rows);
3636 // do print / pdf / instance stuff if needed
3637 $this->endPostProcess($rows);
3643 * @param int|null $rowCount
3647 public function limit($rowCount = NULL) {
3648 $rowCount = $rowCount ??
$this->getRowCount();
3649 // lets do the pager if in html mode
3650 $this->_limit
= NULL;
3652 // CRM-14115, over-ride row count if rowCount is specified in URL
3653 if ($this->_dashBoardRowCount
) {
3654 $rowCount = $this->_dashBoardRowCount
;
3656 if ($this->addPaging
) {
3657 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3659 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3661 // @todo all http vars should be extracted in the preProcess
3662 // - not randomly in the class
3663 if (!$pageId && !empty($_POST)) {
3664 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3665 $pageId = max((int) $_POST['crmPID_B'], 1);
3667 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3668 $pageId = max((int) $_POST['crmPID'], 1);
3670 unset($_POST['crmPID_B'], $_POST['crmPID']);
3673 $pageId = $pageId ?
$pageId : 1;
3674 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3675 $offset = ($pageId - 1) * $rowCount;
3677 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3678 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3680 $this->_limit
= " LIMIT $offset, $rowCount";
3681 return [$offset, $rowCount];
3683 if ($this->_limitValue
) {
3684 if ($this->_offsetValue
) {
3685 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3688 $this->_limit
= " LIMIT " . $this->_limitValue
;
3696 * @param int|null $rowCount
3698 public function setPager($rowCount = NULL) {
3699 $rowCount = $rowCount ??
$this->getRowCount();
3700 // CRM-14115, over-ride row count if rowCount is specified in URL
3701 if ($this->_dashBoardRowCount
) {
3702 $rowCount = $this->_dashBoardRowCount
;
3705 if ($this->_limit
&& ($this->_limit
!= '')) {
3706 if (!$this->_rowsFound
) {
3707 $sql = "SELECT FOUND_ROWS();";
3708 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3711 'total' => $this->_rowsFound
,
3712 'rowCount' => $rowCount,
3713 'status' => ts('Records') . ' %%StatusMessage%%',
3714 'buttonBottom' => 'PagerBottomButton',
3715 'buttonTop' => 'PagerTopButton',
3717 if (!empty($this->controller
)) {
3718 // This happens when being called from the api Really we want the api to be able to
3719 // pass paging parameters, but at this stage just preventing test crashes.
3720 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3723 $pager = new CRM_Utils_Pager($params);
3724 $this->assign_by_ref('pager', $pager);
3725 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3730 * Build a group filter with contempt for large data sets.
3732 * This function has been retained as it takes time to migrate the reports over
3733 * to the new method which will not crash on large datasets.
3737 * @param string $field
3738 * @param mixed $value
3743 public function legacySlowGroupFilterClause($field, $value, $op) {
3744 $smartGroupQuery = "";
3746 $group = new CRM_Contact_DAO_Group();
3747 $group->is_active
= 1;
3750 while ($group->fetch()) {
3751 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3752 $group->saved_search_id
3754 $smartGroups[] = $group->id
;
3758 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3760 $smartGroupQuery = '';
3761 if (!empty($smartGroups)) {
3762 $smartGroups = implode(',', $smartGroups);
3763 $smartGroupQuery = " UNION DISTINCT
3764 SELECT DISTINCT smartgroup_contact.contact_id
3765 FROM civicrm_group_contact_cache smartgroup_contact
3766 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3769 $sqlOp = $this->getSQLOperator($op);
3770 if (!is_array($value)) {
3773 //include child groups if any
3774 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3776 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3778 $contactAlias = $this->_aliases
['civicrm_contact'];
3779 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3780 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3782 return " {$contactAlias}.id {$sqlOp} (
3783 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3784 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3785 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3786 {$smartGroupQuery} ) ";
3790 * Build where clause for groups.
3792 * @param string $field
3793 * @param mixed $value
3798 public function whereGroupClause($field, $value, $op) {
3799 if ($this->groupFilterNotOptimised
) {
3800 return $this->legacySlowGroupFilterClause($field, $value, $op);
3802 if ($op === 'notin') {
3803 return " group_temp_table.contact_id IS NULL ";
3805 // We will have used an inner join instead.
3810 * Create a table of the contact ids included by the group filter.
3812 * This function is called by both the api (tests) and the UI.
3814 * @throws \CiviCRM_API3_Exception
3816 public function buildGroupTempTable(): void
{
3817 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3820 $this->groupTempTable
= $this->createTemporaryTable('groups', 'contact_id INT', TRUE);
3821 $filteredGroups = (array) $this->_params
['gid_value'];
3822 CRM_Contact_BAO_GroupContactCache
::populateTemporaryTableWithContactsInGroups($filteredGroups, $this->groupTempTable
);
3823 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX contact_id(contact_id)");
3827 * Execute query and add it to the developer tab.
3829 * @param string $query
3830 * @param array $params
3832 * @return \CRM_Core_DAO|object
3834 protected function executeReportQuery($query, $params = []) {
3835 $this->addToDeveloperTab($query);
3836 return CRM_Core_DAO
::executeQuery($query, $params);
3840 * Build where clause for tags.
3842 * @param string $field
3843 * @param mixed $value
3848 public function whereTagClause($field, $value, $op) {
3849 // not using left join in query because if any contact
3850 // belongs to more than one tag, results duplicate
3852 $sqlOp = $this->getSQLOperator($op);
3853 if (!is_array($value)) {
3856 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3857 $entity_table = $this->_tagFilterTable
;
3858 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3859 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3860 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3861 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3865 * Generate membership organization clause.
3867 * @param mixed $value
3868 * @param string $op SQL Operator
3872 public function whereMembershipOrgClause($value, $op) {
3873 $sqlOp = $this->getSQLOperator($op);
3874 if (!is_array($value)) {
3878 $tmp_membership_org_sql_list = implode(', ', $value);
3879 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3880 SELECT DISTINCT mem.contact_id
3881 FROM civicrm_membership mem
3882 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3883 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3884 WHERE mt.member_of_contact_id IN (" .
3885 $tmp_membership_org_sql_list . ")
3886 AND mt.is_active = '1'
3887 AND mem_status.is_current_member = '1'
3888 AND mem_status.is_active = '1' ) ";
3892 * Generate Membership Type SQL Clause.
3894 * @param mixed $value
3900 public function whereMembershipTypeClause($value, $op) {
3901 $sqlOp = $this->getSQLOperator($op);
3902 if (!is_array($value)) {
3906 $tmp_membership_sql_list = implode(', ', $value);
3907 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3908 SELECT DISTINCT mem.contact_id
3909 FROM civicrm_membership mem
3910 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3911 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3912 WHERE mem.membership_type_id IN (" .
3913 $tmp_membership_sql_list . ")
3914 AND mt.is_active = '1'
3915 AND mem_status.is_current_member = '1'
3916 AND mem_status.is_active = '1' ) ";
3920 * Buld contact acl clause
3921 * @deprecated in favor of buildPermissionClause
3923 * Note that if the buildPermissionClause function is called (which most reports do from
3924 * buildQuery then the results of this function are re-calculated and overwritten.
3926 * @param string $tableAlias
3928 public function buildACLClause($tableAlias = 'contact_a') {
3929 [$this->_aclFrom
, $this->_aclWhere
] = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3933 * Build the permision clause for all entities in this report
3935 public function buildPermissionClause() {
3937 foreach ($this->selectedTables() as $tableName) {
3938 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3939 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3940 $tableAlias = $this->_columns
[$tableName]['alias'];
3941 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3942 foreach ($clauses as $field => $clause) {
3943 // Skip contact_id field if redundant
3944 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3945 $ret["$tableName.$field"] = $clause;
3950 // Override output from buildACLClause
3951 $this->_aclFrom
= NULL;
3952 $this->_aclWhere
= implode(' AND ', $ret);
3956 * Add custom data to the columns.
3958 * @param bool $addFields
3959 * @param array $permCustomGroupIds
3961 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = []) {
3962 if (empty($this->_customGroupExtends
)) {
3965 if (!is_array($this->_customGroupExtends
)) {
3966 $this->_customGroupExtends
= [$this->_customGroupExtends
];
3968 $customGroupWhere = '';
3969 if (!empty($permCustomGroupIds)) {
3970 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3974 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3975 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format,
3976 cf.serialize as serialize
3977 FROM civicrm_custom_group cg
3978 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3979 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3981 cg.is_active = 1 AND
3982 cf.is_active = 1 AND
3983 cf.is_searchable = 1
3984 ORDER BY cg.weight, cf.weight";
3985 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3988 while ($customDAO->fetch()) {
3989 if ($customDAO->table_name
!= $curTable) {
3990 $curTable = $customDAO->table_name
;
3991 $curFields = $curFilters = [];
3994 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3995 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3996 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3997 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3999 foreach (['fields', 'filters', 'group_bys'] as $colKey) {
4000 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
4001 $this->_columns
[$curTable][$colKey] = [];
4005 $fieldName = 'custom_' . $customDAO->cf_id
;
4008 // this makes aliasing work in favor
4009 $curFields[$fieldName] = [
4010 'name' => $customDAO->column_name
,
4011 'title' => $customDAO->label
,
4012 'dataType' => $customDAO->data_type
,
4013 'htmlType' => $customDAO->html_type
,
4016 if ($this->_customGroupFilters
) {
4017 // this makes aliasing work in favor
4018 $curFilters[$fieldName] = [
4019 'name' => $customDAO->column_name
,
4020 'title' => $customDAO->label
,
4021 'dataType' => $customDAO->data_type
,
4022 'htmlType' => $customDAO->html_type
,
4026 switch ($customDAO->data_type
) {
4029 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
4030 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
4031 // CRM-6946, show time part for datetime date fields
4032 if ($customDAO->time_format
) {
4033 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
4038 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
4039 $curFilters[$fieldName]['options'] = ['' => ts('- select -')] + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4040 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
4044 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
4045 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
4049 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
4050 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
4051 // Use T_FLOAT instead of T_MONEY as the money number format happens
4052 // by calling CRM_Core_BAO_CustomField::displayValue in alterCustomDataDisplay
4053 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
4057 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
4058 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
4062 case 'StateProvince':
4064 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4066 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4067 if ((is_array($options) && count($options) != 0) ||
(!is_array($options) && $options !== FALSE)) {
4068 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4069 $curFilters[$fieldName]['options'] = $options;
4073 case 'ContactReference':
4074 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4075 $curFilters[$fieldName]['name'] = 'display_name';
4076 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4078 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4079 $curFields[$fieldName]['name'] = 'display_name';
4080 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4084 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4085 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4089 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
4090 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4091 if ($options !== FALSE) {
4092 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4093 $curFilters[$fieldName]['options'] = $options;
4097 if (!array_key_exists('type', $curFields[$fieldName])) {
4098 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], []);
4102 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
4104 if ($this->_customGroupFilters
) {
4105 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
4107 if ($this->_customGroupGroupBy
) {
4108 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
4114 * Build custom data from clause.
4116 * @param bool $joinsForFiltersOnly
4117 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
4119 public function customDataFrom($joinsForFiltersOnly = FALSE) {
4120 if (empty($this->_customGroupExtends
)) {
4123 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
4124 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
4125 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
4127 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
4128 while ($customTablesDAO->fetch()) {
4129 $customTables[] = $customTablesDAO->table_name
;
4132 foreach ($this->_columns
as $table => $prop) {
4133 if (in_array($table, $customTables)) {
4134 $extendsTable = $mapper[$prop['extends']];
4135 // Check field is required for rendering the report.
4136 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4139 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
4141 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
4143 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4144 // handle for ContactReference
4145 if (array_key_exists('fields', $prop)) {
4146 foreach ($prop['fields'] as $fieldName => $field) {
4147 if (CRM_Utils_Array
::value('dataType', $field) ==
4150 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4152 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4161 * Check if the field is selected.
4163 * @param string $prop
4167 public function isFieldSelected($prop) {
4172 if (!empty($this->_params
['fields'])) {
4173 foreach (array_keys($prop['fields']) as $fieldAlias) {
4174 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4175 if ($customFieldId) {
4176 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4180 //might be survey response field.
4181 if (!empty($this->_params
['fields']['survey_response']) &&
4182 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4190 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4191 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4192 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4193 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4200 if (!empty($this->_params
['order_bys'])) {
4201 foreach (array_keys($prop['fields']) as $fieldAlias) {
4202 foreach ($this->_params
['order_bys'] as $orderBy) {
4203 if ($fieldAlias == $orderBy['column'] &&
4204 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4211 return $this->isFieldFiltered($prop);
4216 * Check if the field is used as a filter.
4218 * @param string $prop
4222 protected function isFieldFiltered($prop) {
4223 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4224 foreach ($prop['filters'] as $fieldAlias => $val) {
4233 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4234 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4235 ||
($attach != 'relative' &&
4236 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4242 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4243 in_array($this->_params
[$fieldAlias . '_op'], ['nll', 'nnll'])
4254 * Check for empty order_by configurations and remove them.
4256 * Also set template to hide them.
4258 * @param array $formValues
4260 public function preProcessOrderBy(&$formValues) {
4261 // Object to show/hide form elements
4262 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4264 $_showHide->addShow('optionField_1');
4266 // Cycle through order_by options; skip any empty ones, and hide them as well
4269 if (!empty($formValues['order_bys'])) {
4270 foreach ($formValues['order_bys'] as $order_by) {
4271 if ($order_by['column'] && $order_by['column'] != '-') {
4272 $_showHide->addShow('optionField_' . $n);
4273 $orderBys[$n] = $order_by;
4278 for ($i = $n; $i <= 5; $i++
) {
4280 $_showHide->addHide('optionField_' . $i);
4284 // overwrite order_by options with modified values
4285 if (!empty($orderBys)) {
4286 $formValues['order_bys'] = $orderBys;
4289 $formValues['order_bys'] = [1 => ['column' => '-']];
4292 // assign show/hide data to template
4293 $_showHide->addToTemplate();
4297 * Check if table name has columns in SELECT clause.
4299 * @param string $tableName
4300 * Name of table (index of $this->_columns array).
4304 public function isTableSelected($tableName) {
4305 return in_array($tableName, $this->selectedTables());
4309 * Check if table name has columns in WHERE or HAVING clause.
4311 * @param string $tableName
4312 * Name of table (index of $this->_columns array).
4316 public function isTableFiltered($tableName) {
4317 // Cause the array to be generated if not previously done.
4318 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4319 $this->selectedTables();
4321 return in_array($tableName, $this->filteredTables
);
4325 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4327 * If the array is unset it will be built.
4332 public function selectedTables() {
4333 if (!$this->_selectedTables
) {
4334 $orderByColumns = [];
4335 if (array_key_exists('order_bys', $this->_params
) &&
4336 is_array($this->_params
['order_bys'])
4338 foreach ($this->_params
['order_bys'] as $orderBy) {
4339 $orderByColumns[] = $orderBy['column'];
4343 foreach ($this->_columns
as $tableName => $table) {
4344 if (array_key_exists('fields', $table)) {
4345 foreach ($table['fields'] as $fieldName => $field) {
4346 if (!empty($field['required']) ||
4347 !empty($this->_params
['fields'][$fieldName])
4349 $this->_selectedTables
[] = $tableName;
4354 if (array_key_exists('order_bys', $table)) {
4355 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4356 if (in_array($orderByName, $orderByColumns)) {
4357 $this->_selectedTables
[] = $tableName;
4362 if (array_key_exists('filters', $table)) {
4363 foreach ($table['filters'] as $filterName => $filter) {
4364 $filterOp = $this->_params
["{$filterName}_op"] ??
'';
4365 if ((isset($this->_params
["{$filterName}_value"])
4366 && !CRM_Utils_System
::isNull($this->_params
["{$filterName}_value"]))
4367 ||
!empty($this->_params
["{$filterName}_relative"])
4368 ||
$filterOp === 'nll'
4369 ||
$filterOp === 'nnll'
4371 $this->_selectedTables
[] = $tableName;
4372 $this->filteredTables
[] = $tableName;
4379 return $this->_selectedTables
;
4383 * Add campaign fields.
4384 * @param string $entityTable
4385 * @param bool $groupBy
4386 * Add GroupBy? Not appropriate for detail report.
4387 * @param bool $orderBy
4388 * Add OrderBy? Not appropriate for detail report.
4389 * @param bool $filters
4392 public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) {
4393 // Check if CiviCampaign is a) enabled and b) has active campaigns
4394 $config = CRM_Core_Config
::singleton();
4395 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents
);
4396 if ($campaignEnabled) {
4397 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE);
4398 // If we have a campaign, build out the relevant elements
4399 if (!empty($getCampaigns['campaigns'])) {
4400 $this->campaigns
= $getCampaigns['campaigns'];
4401 asort($this->campaigns
);
4402 $this->_columns
[$entityTable]['fields']['campaign_id'] = ['title' => ts('Campaign'), 'default' => 'false'];
4404 $this->_columns
[$entityTable]['filters']['campaign_id'] = [
4405 'title' => ts('Campaign'),
4406 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4407 'options' => $this->campaigns
,
4408 'type' => CRM_Utils_Type
::T_INT
,
4413 $this->_columns
[$entityTable]['group_bys']['campaign_id'] = ['title' => ts('Campaign')];
4417 $this->_columns
[$entityTable]['order_bys']['campaign_id'] = ['title' => ts('Campaign')];
4424 * Add address fields.
4426 * @deprecated - use getAddressColumns which is a more accurate description
4427 * and also accepts an array of options rather than a long list
4429 * adding address fields to construct function in reports
4431 * @param bool $groupBy
4432 * Add GroupBy? Not appropriate for detail report.
4433 * @param bool $orderBy
4434 * Add GroupBy? Not appropriate for detail report.
4435 * @param bool $filters
4436 * @param array $defaults
4439 * address fields for construct clause
4441 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = ['country_id' => TRUE]) {
4442 $defaultAddressFields = [
4443 'street_address' => ts('Street Address'),
4444 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4445 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4446 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4447 'street_number' => ts('Street Number'),
4448 'street_name' => ts('Street Name'),
4449 'street_unit' => ts('Street Unit'),
4450 'city' => ts('City'),
4451 'postal_code' => ts('Postal Code'),
4452 'postal_code_suffix' => ts('Postal Code Suffix'),
4453 'country_id' => ts('Country'),
4454 'state_province_id' => ts('State/Province'),
4455 'county_id' => ts('County'),
4458 'civicrm_address' => [
4459 'dao' => 'CRM_Core_DAO_Address',
4462 'title' => ts('Address Name'),
4463 'default' => $defaults['name'] ??
FALSE,
4467 'grouping' => 'location-fields',
4470 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4471 $addressFields['civicrm_address']['fields'][$fieldName] = [
4472 'title' => $fieldLabel,
4473 'default' => $defaults[$fieldName] ??
FALSE,
4477 $street_address_filters = $general_address_filters = [];
4479 // Address filter depends on whether street address parsing is enabled.
4481 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4484 if ($addressOptions['street_address_parsing']) {
4485 $street_address_filters = [
4486 'street_number' => [
4487 'title' => ts('Street Number'),
4488 'type' => CRM_Utils_Type
::T_INT
,
4489 'name' => 'street_number',
4492 'title' => ts('Street Name'),
4493 'name' => 'street_name',
4494 'type' => CRM_Utils_Type
::T_STRING
,
4499 $street_address_filters = [
4500 'street_address' => [
4501 'title' => ts('Street Address'),
4502 'type' => CRM_Utils_Type
::T_STRING
,
4503 'name' => 'street_address',
4507 $general_address_filters = [
4509 'title' => ts('Postal Code'),
4510 'type' => CRM_Utils_Type
::T_STRING
,
4511 'name' => 'postal_code',
4514 'title' => ts('City'),
4515 'type' => CRM_Utils_Type
::T_STRING
,
4519 'name' => 'country_id',
4520 'title' => ts('Country'),
4521 'type' => CRM_Utils_Type
::T_INT
,
4522 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4523 'options' => CRM_Core_PseudoConstant
::country(),
4525 'state_province_id' => [
4526 'name' => 'state_province_id',
4527 'title' => ts('State/Province'),
4528 'type' => CRM_Utils_Type
::T_INT
,
4529 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4533 'name' => 'county_id',
4534 'title' => ts('County'),
4535 'type' => CRM_Utils_Type
::T_INT
,
4536 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4541 $addressFields['civicrm_address']['filters'] = array_merge(
4542 $street_address_filters,
4543 $general_address_filters);
4546 $addressFields['civicrm_address']['order_bys'] = [
4547 'street_name' => ['title' => ts('Street Name')],
4548 'street_number' => ['title' => ts('Odd / Even Street Number')],
4549 'street_address' => NULL,
4551 'postal_code' => NULL,
4556 $addressFields['civicrm_address']['group_bys'] = [
4557 'street_address' => NULL,
4559 'postal_code' => NULL,
4560 'state_province_id' => [
4561 'title' => ts('State/Province'),
4564 'title' => ts('Country'),
4567 'title' => ts('County'),
4571 return $addressFields;
4575 * Do AlterDisplay processing on Address Fields.
4576 * If there are multiple address field values then
4577 * on basis of provided separator the code values are translated into respective labels
4580 * @param array $rows
4581 * @param int $rowNum
4582 * @param string $baseUrl
4583 * @param string $linkText
4584 * @param string $separator
4588 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4589 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4590 $entryFound = FALSE;
4592 'civicrm_address_country_id' => 'country',
4593 'civicrm_address_county_id' => 'county',
4594 'civicrm_address_state_province_id' => 'stateProvince',
4596 foreach ($columnMap as $fieldName => $fnName) {
4597 if (array_key_exists($fieldName, $row)) {
4598 if ($values = $row[$fieldName]) {
4599 $values = (array) explode($separator, $values);
4600 $rows[$rowNum][$fieldName] = [];
4601 $addressField = $fnName == 'stateProvince' ?
'state' : $fnName;
4602 foreach ($values as $value) {
4603 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant
::$fnName($value);
4605 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4607 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4608 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4609 $criteriaQueryParams,
4610 str_replace('civicrm_address_', '', $fieldName),
4611 str_replace('civicrm_address_', '', $fieldName),
4612 implode(',', $values)
4613 ), $this->_absoluteUrl
, $this->_id
4615 $rows[$rowNum]["{$fieldName}_link"] = $url;
4616 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", [1 => $linkText, 2 => $addressField]);
4627 * Do AlterDisplay processing on Address Fields.
4630 * @param array $rows
4631 * @param int $rowNum
4632 * @param string $baseUrl
4633 * @param string $linkText
4637 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4638 $entryFound = FALSE;
4639 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4640 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4641 $addLinks = ['gender_id' => 'Gender'];
4642 foreach (['prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language'] as $fieldName) {
4643 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4644 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4645 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4647 foreach ($rowValues as $rowValue) {
4649 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4652 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4653 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4654 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4661 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'do_not_trade', 'is_opt_out',
4663 foreach ($yesNoFields as $fieldName) {
4664 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4665 // Since these are essentially 'negative fields' it feels like it
4666 // makes sense to only highlight the exceptions hence no 'No'.
4667 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4672 // Handle employer id
4673 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4674 $employerId = $row['civicrm_contact_employer_id'];
4676 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact
::displayName($employerId);
4677 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
4678 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4687 * Adjusts dates passed in to YEAR() for fiscal year.
4689 * @param string $fieldName
4693 public function fiscalYearOffset($fieldName) {
4694 $config = CRM_Core_Config
::singleton();
4695 $fy = $config->fiscalYearStart
;
4696 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4697 ($fy['d'] == 1 && $fy['M'] == 1)
4699 return "YEAR( $fieldName )";
4701 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4702 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4706 * Add Address into From Table if required.
4708 * Prefix will be added to both tables as
4709 * it is assumed you are using it to get address of a secondary contact.
4711 * @param string $prefix
4712 * @param array $extra Additional options.
4713 * Not currently used in core but may be used in override extensions.
4715 protected function joinAddressFromContact($prefix = '', $extra = []) {
4716 $defaults = ['primary_only' => TRUE];
4717 $params = array_merge($defaults, $extra);
4718 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4719 $isJoinRequired = $this->_addressField
;
4720 foreach ($addressTables as $addressTable) {
4721 if ($this->isTableSelected($prefix . $addressTable)) {
4722 $isJoinRequired = TRUE;
4725 if ($isJoinRequired) {
4727 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4728 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4729 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id)";
4730 if ($params['primary_only']) {
4732 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4734 $this->_from
.= $fromJoin;
4739 * Add Country into From Table if required.
4741 * Prefix will be added to both tables as
4742 * it is assumed you are using it to get address of a secondary contact.
4744 * @param string $prefix
4745 * @param array $extra Additional options.
4746 * Not currently used in core but may be used in override extensions.
4748 protected function joinCountryFromAddress($prefix = '', $extra = []) {
4749 $defaults = ['primary_only' => TRUE];
4750 $params = array_merge($defaults, $extra);
4751 // include country field if country column is to be included
4752 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4753 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4754 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4757 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4758 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id";
4759 if ($params['primary_only']) {
4761 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4763 $this->_from
.= $fromJoin;
4768 * Add Phone into From Table if required.
4770 * Prefix will be added to both tables as
4771 * it is assumed you are using it to get address of a secondary contact.
4773 * @param string $prefix
4774 * @param array $extra Additional options.
4775 * Not currently used in core but may be used in override extensions.
4777 protected function joinPhoneFromContact($prefix = '', $extra = []) {
4778 $defaults = ['primary_only' => TRUE];
4779 $params = array_merge($defaults, $extra);
4780 // include phone field if phone column is to be included
4781 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4783 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4784 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id";
4785 if ($params['primary_only']) {
4787 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4789 $this->_from
.= $fromJoin;
4794 * Add Email into From Table if required.
4796 * Prefix will be added to both tables as
4797 * it is assumed you are using it to get address of a secondary contact.
4799 * @param string $prefix
4800 * @param array $extra Additional options.
4801 * Not currently used in core but may be used in override extensions.
4803 protected function joinEmailFromContact($prefix = '', $extra = []) {
4804 $defaults = ['primary_only' => TRUE];
4805 $params = array_merge($defaults, $extra);
4806 // include email field if email column is to be included
4807 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4809 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4810 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id";
4811 if ($params['primary_only']) {
4813 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1 ";
4815 $this->_from
.= $fromJoin;
4820 * Add Financial Transaction into From Table if required.
4822 public function addFinancialTrxnFromClause() {
4823 if ($this->isTableSelected('civicrm_financial_trxn')) {
4825 LEFT JOIN civicrm_entity_financial_trxn eftcc
4826 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4827 eftcc.entity_table = 'civicrm_contribution')
4828 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4829 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4834 * Get phone columns to add to array.
4836 * @param array $options
4837 * - prefix Prefix to add to table (in case of more than one instance of the table)
4838 * - prefix_label Label to give columns from this phone table instance
4841 * phone columns definition
4843 public function getPhoneColumns($options = []) {
4846 'prefix_label' => '',
4849 $options = array_merge($defaultOptions, $options);
4852 $options['prefix'] . 'civicrm_phone' => [
4853 'dao' => 'CRM_Core_DAO_Phone',
4855 $options['prefix'] . 'phone' => [
4856 'title' => $options['prefix_label'] . ts('Phone'),
4866 * Get a standard set of contact fields.
4867 * @deprecated - use getColumns('Contact') instead
4870 public function getBasicContactFields() {
4873 'title' => ts('Contact Name'),
4878 'no_display' => TRUE,
4882 'title' => ts('Contact Prefix'),
4885 'title' => ts('First Name'),
4888 'title' => ts('Nick Name'),
4891 'title' => ts('Middle Name'),
4894 'title' => ts('Last Name'),
4897 'title' => ts('Contact Suffix'),
4899 'source' => ['title' => ts('Contact Source')],
4900 'postal_greeting_display' => ['title' => ts('Postal Greeting')],
4901 'email_greeting_display' => ['title' => ts('Email Greeting')],
4902 'addressee_display' => ['title' => ts('Addressee')],
4904 'title' => ts('Contact Type'),
4906 'contact_sub_type' => [
4907 'title' => ts('Contact Subtype'),
4910 'title' => ts('Gender'),
4913 'title' => ts('Birth Date'),
4916 'title' => ts('Age'),
4917 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4920 'title' => ts('Contact Job title'),
4922 'organization_name' => [
4923 'title' => ts('Organization Name'),
4925 'external_identifier' => [
4926 'title' => ts('Contact identifier from external system'),
4928 'do_not_email' => [],
4929 'do_not_phone' => [],
4930 'do_not_mail' => [],
4932 'do_not_trade' => [],
4934 'is_deceased' => [],
4935 'preferred_language' => [],
4937 'title' => ts('Current Employer'),
4943 * Get a standard set of contact filters.
4945 * @param array $defaults
4949 public function getBasicContactFilters($defaults = []) {
4952 'title' => ts('Contact Name'),
4955 'title' => ts('Contact Source'),
4956 'type' => CRM_Utils_Type
::T_STRING
,
4959 'title' => ts('Contact ID'),
4960 'no_display' => TRUE,
4963 'title' => ts('Gender'),
4964 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4965 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4968 'title' => ts('Birth Date'),
4969 'operatorType' => CRM_Report_Form
::OP_DATE
,
4972 'title' => ts('Contact Type'),
4974 'contact_sub_type' => [
4975 'title' => ts('Contact Subtype'),
4977 'modified_date' => [
4978 'title' => ts('Contact Modified'),
4979 'operatorType' => CRM_Report_Form
::OP_DATE
,
4980 'type' => CRM_Utils_Type
::T_DATE
,
4983 'title' => ts('Deceased'),
4984 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4985 'default' => CRM_Utils_Array
::value('deceased', $defaults, 0),
4988 'title' => ts('Do not email'),
4989 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4992 'title' => ts('Do not phone'),
4993 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4996 'title' => ts('Do not mail'),
4997 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5000 'title' => ts('Do not SMS'),
5001 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5004 'title' => ts('Do not Trade'),
5005 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5008 'title' => ts('Do not bulk email'),
5009 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5011 'preferred_language' => [
5012 'title' => ts('Preferred Language'),
5015 'no_display' => TRUE,
5017 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5023 * Add contact to group.
5025 * @param int $groupID
5027 public function add2group($groupID) {
5028 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
5029 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
5030 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
5031 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
5032 $sql = str_replace('WITH ROLLUP', '', $sql);
5033 if (!$this->optimisedForOnlyFullGroupBy
) {
5034 CRM_Core_DAO
::disableFullGroupByMode();
5036 $dao = CRM_Core_DAO
::executeQuery($sql);
5037 CRM_Core_DAO
::reenableFullGroupByMode();
5040 // Add resulting contacts to group
5041 while ($dao->fetch()) {
5042 if ($dao->addtogroup_contact_id
) {
5043 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
5047 if (!empty($contact_ids)) {
5048 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
5049 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
5052 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
5058 * Apply common settings to entityRef fields.
5060 * @param array $field
5061 * @param string $table
5063 public function setEntityRefDefaults(&$field, $table) {
5064 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : [];
5065 $field['attributes'] +
= [
5066 'entity' => CRM_Core_DAO_AllCoreTables
::getEntityNameForTable($table),
5068 'placeholder' => ts('- select -'),
5073 * Add link fields to the row.
5075 * Function adds the _link & _hover fields to the row.
5078 * @param string $baseUrl
5079 * @param string $linkText
5080 * @param string $value
5081 * @param string $fieldName
5082 * @param string $tablePrefix
5083 * @param string $fieldLabel
5087 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
5088 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
5089 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
5090 "reset=1&force=1&{$criteriaQueryParams}&" .
5091 $fieldName . "_op=in&{$fieldName}_value={$value}",
5092 $this->_absoluteUrl
, $this->_id
5094 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
5095 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
5096 [1 => $linkText, 2 => $fieldLabel]
5101 * Get label for show results buttons.
5105 public function getResultsLabel() {
5106 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
5107 return $showResultsLabel;
5111 * Determine the output mode from the url or input.
5114 * - pdf : Render as pdf
5115 * - csv : Render as csv
5116 * - print : Render in print format
5117 * - save : save the report and display the new report
5118 * - copy : save the report as a new instance and display that.
5119 * - group : go to the add to group screen.
5121 * Potentially chart variations could also be included but the complexity
5122 * is that we might print a bar chart as a pdf.
5124 protected function setOutputMode() {
5125 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
5128 CRM_Core_DAO
::$_nullObject,
5130 CRM_Utils_Array
::value('task', $this->_params
)
5132 // if contacts are added to group
5133 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
5134 $this->_outputMode
= 'group';
5136 if (isset($this->_params
['task'])) {
5137 unset($this->_params
['task']);
5142 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5145 * @param $columnName
5147 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5148 // add new column with date value for the datetime field
5149 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5150 CRM_Core_DAO
::executeQuery($tempQuery);
5151 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5152 CRM_Core_DAO
::executeQuery($updateQuery);
5153 $this->_selectClauses
[] = "{$columnName}_date";
5154 $this->_select
.= ", {$columnName}_date";
5155 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5156 unset($this->_sections
["{$columnName}"]);
5157 $this->assign('sections', $this->_sections
);
5161 * Get an array of the columns that have been selected for display.
5165 public function getSelectColumns() {
5166 $selectColumns = [];
5167 foreach ($this->_columns
as $tableName => $table) {
5168 if (array_key_exists('fields', $table)) {
5169 foreach ($table['fields'] as $fieldName => $field) {
5170 if (!empty($field['required']) ||
5171 !empty($this->_params
['fields'][$fieldName])
5174 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5179 return $selectColumns;
5183 * Add location tables to the query if they are used for filtering.
5185 * This is for when we are running the query separately for filtering and retrieving display fields.
5187 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5188 if ($this->isTableFiltered('civicrm_email')) {
5190 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5191 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5192 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5194 if ($this->isTableFiltered('civicrm_phone')) {
5196 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5197 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5198 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5200 if ($this->isTableFiltered('civicrm_address')) {
5202 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5203 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5204 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5209 * Set the base table for the FROM clause.
5211 * Sets up the from clause, allowing for the possibility it might be a
5212 * temp table pre-filtered by groups if a group filter is in use.
5214 * @param string $baseTable
5215 * @param string $field
5216 * @param null $tableAlias
5218 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5220 $tableAlias = $this->_aliases
[$baseTable];
5222 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5223 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5224 $this->_from
.= " {$this->_aclFrom} ";
5228 * Join the temp table contacting contacts who are members of the filtered groups.
5230 * If we are using an IN filter we use an inner join, otherwise a left join.
5232 * @param string $baseTable
5233 * @param string $field
5234 * @param string $tableAlias
5236 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5237 if ($this->groupTempTable
) {
5238 if ($this->_params
['gid_op'] == 'in') {
5239 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5240 ON group_temp_table.contact_id = $tableAlias.{$field} ";
5244 LEFT JOIN $this->groupTempTable group_temp_table
5245 ON $tableAlias.{$field} = group_temp_table.contact_id ";
5251 * Get all labels for fields that are used in a group concat.
5253 * @param string $options
5254 * comma separated option values.
5255 * @param string $baoName
5256 * The BAO name for the field.
5257 * @param string $fieldName
5258 * The name of the field for which labels should be retrieved.
5262 public function getLabels($options, $baoName, $fieldName) {
5263 $types = explode(',', $options);
5265 foreach ($types as $value) {
5266 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5268 return implode(', ', array_filter($labels));
5272 * Add statistics columns.
5274 * If a group by is in play then add columns for the statistics fields.
5276 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5277 * column header field.
5279 * @param array $field
5280 * @param string $tableName
5281 * @param string $fieldName
5282 * @param array $select
5286 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5287 foreach ($field['statistics'] as $stat => $label) {
5288 $alias = "{$tableName}_{$fieldName}_{$stat}";
5289 switch (strtolower($stat)) {
5292 $select[] = "$stat({$field['dbAlias']}) as $alias";
5293 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5294 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5295 $this->_statFields
[$label] = $alias;
5296 $this->_selectAliases
[] = $alias;
5300 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5301 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5302 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5303 $this->_statFields
[$label] = $alias;
5304 $this->_selectAliases
[] = $alias;
5307 case 'count_distinct':
5308 $select[] = "COUNT(DISTINCT {$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;
5316 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5317 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5318 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5319 $this->_statFields
[$label] = $alias;
5320 $this->_selectAliases
[] = $alias;
5328 * Add a basic field to the select clause.
5330 * @param string $tableName
5331 * @param string $fieldName
5332 * @param array $field
5333 * @param string $select
5336 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5337 $alias = "{$tableName}_{$fieldName}";
5338 $select[] = "{$field['dbAlias']} as $alias";
5339 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'] ??
NULL;
5340 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = $field['type'] ??
NULL;
5341 $this->_selectAliases
[] = $alias;
5348 * @param array $table
5349 * @param string $tableName
5354 protected function setTableAlias($table, $tableName) {
5355 if (!isset($table['alias'])) {
5356 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5360 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5363 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5364 return $this->_aliases
[$tableName];
5368 * Function to add columns to reports.
5370 * This is ported from extended reports, which also adds join filters to the options.
5372 * @param string $type
5373 * @param array $options
5374 * - prefix - A string to prepend to the table name
5375 * - prefix_label A string to prepend to the fields
5376 * - fields (bool) - should the fields for this table be made available
5377 * - group_by (bool) - should the group bys for this table be made available.
5378 * - order_by (bool) - should the group bys for this table be made available.
5379 * - filters (bool) - should the filters for this table by made available.
5380 * - fields_defaults (array) array of fields that should be displayed by default.
5381 * - filters_defaults (array) array of fields that should be filtered by default.
5382 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5383 * - join_fields (array) fields available from join (requires additional custom code).
5384 * - group_by_defaults (array) array of group bys that should be applied by default.
5385 * - order_by_defaults (array) array of order bys that should be applied by default.
5386 * - custom_fields (array) array of entity types for custom fields (not usually required).
5387 * - contact_type (string) optional restriction on contact type for some tables.
5388 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5392 protected function getColumns($type, $options = []) {
5395 'prefix_label' => '',
5397 'group_bys' => FALSE,
5398 'order_bys' => TRUE,
5400 'join_filters' => FALSE,
5401 'fields_defaults' => [],
5402 'filters_defaults' => [],
5403 'group_bys_defaults' => [],
5404 'order_bys_defaults' => [],
5406 $options = array_merge($defaultOptions, $options);
5408 $fn = 'get' . $type . 'Columns';
5409 return $this->$fn($options);
5413 * Get columns for contact table.
5415 * @param array $options
5419 protected function getContactColumns($options = []) {
5421 'custom_fields' => ['Individual', 'Contact', 'Organization'],
5422 'fields_defaults' => ['display_name', 'id'],
5423 'order_bys_defaults' => ['sort_name ASC'],
5424 'contact_type' => NULL,
5427 $options = array_merge($defaultOptions, $options);
5429 $tableAlias = $options['prefix'] . 'contact';
5432 $options['prefix'] . 'display_name' => [
5433 'name' => 'display_name',
5434 'title' => $options['prefix_label'] . ts('Contact Name'),
5435 'is_fields' => TRUE,
5437 $options['prefix'] . 'sort_name' => [
5438 'name' => 'sort_name',
5439 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5440 'is_fields' => TRUE,
5441 'is_filters' => TRUE,
5442 'is_order_bys' => TRUE,
5444 $options['prefix'] . 'id' => [
5446 'title' => $options['prefix_label'] . ts('Contact ID'),
5447 'alter_display' => 'alterContactID',
5448 'type' => CRM_Utils_Type
::T_INT
,
5449 'is_order_bys' => TRUE,
5450 'is_group_bys' => TRUE,
5451 'is_fields' => TRUE,
5452 'is_filters' => TRUE,
5454 $options['prefix'] . 'external_identifier' => [
5455 'name' => 'external_identifier',
5456 'title' => $options['prefix_label'] . ts('External ID'),
5457 'type' => CRM_Utils_Type
::T_INT
,
5458 'is_fields' => TRUE,
5460 $options['prefix'] . 'contact_type' => [
5461 'title' => $options['prefix_label'] . ts('Contact Type'),
5462 'name' => 'contact_type',
5463 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5464 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5465 'is_fields' => TRUE,
5466 'is_filters' => TRUE,
5467 'is_group_bys' => TRUE,
5469 $options['prefix'] . 'contact_sub_type' => [
5470 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5471 'name' => 'contact_sub_type',
5472 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5473 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5474 'is_fields' => TRUE,
5475 'is_filters' => TRUE,
5476 'is_group_bys' => TRUE,
5478 $options['prefix'] . 'is_deleted' => [
5479 'title' => $options['prefix_label'] . ts('Is deleted'),
5480 'name' => 'is_deleted',
5481 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5482 'is_fields' => FALSE,
5483 'is_filters' => TRUE,
5484 'is_group_bys' => FALSE,
5486 $options['prefix'] . 'external_identifier' => [
5487 'title' => $options['prefix_label'] . ts('Contact identifier from external system'),
5488 'name' => 'external_identifier',
5489 'is_fields' => TRUE,
5490 'is_filters' => FALSE,
5491 'is_group_bys' => FALSE,
5492 'is_order_bys' => TRUE,
5494 $options['prefix'] . 'preferred_language' => [
5495 'title' => $options['prefix_label'] . ts('Preferred Language'),
5496 'name' => 'preferred_language',
5497 'is_fields' => TRUE,
5498 'is_filters' => TRUE,
5499 'is_group_bys' => TRUE,
5500 'is_order_bys' => TRUE,
5502 $options['prefix'] . 'preferred_communication_method' => [
5503 'title' => $options['prefix_label'] . ts('Preferred Communication Method'),
5504 'alter_display' => 'alterCommunicationtMethod',
5505 'name' => 'preferred_communication_method',
5506 'is_fields' => TRUE,
5507 'is_filters' => FALSE,
5508 'is_group_bys' => FALSE,
5509 'is_order_bys' => FALSE,
5513 'postal_greeting_display' => 'Postal Greeting',
5514 'email_greeting_display' => 'Email Greeting',
5515 'addressee_display' => 'Addressee',
5516 ] as $field => $title) {
5517 $spec[$options['prefix'] . $field] = [
5518 'title' => $options['prefix_label'] . ts($title),
5520 'is_fields' => TRUE,
5521 'is_filters' => FALSE,
5522 'is_group_bys' => FALSE,
5525 foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'do_not_trade', 'is_opt_out'] as $field) {
5526 $spec[$options['prefix'] . $field] = [
5528 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5529 'is_fields' => TRUE,
5530 'is_filters' => TRUE,
5531 'is_group_bys' => FALSE,
5534 $individualFields = [
5535 $options['prefix'] . 'first_name' => [
5536 'name' => 'first_name',
5537 'title' => $options['prefix_label'] . ts('First Name'),
5538 'is_fields' => TRUE,
5539 'is_filters' => TRUE,
5540 'is_order_bys' => TRUE,
5542 $options['prefix'] . 'middle_name' => [
5543 'name' => 'middle_name',
5544 'title' => $options['prefix_label'] . ts('Middle Name'),
5545 'is_fields' => TRUE,
5547 $options['prefix'] . 'last_name' => [
5548 'name' => 'last_name',
5549 'title' => $options['prefix_label'] . ts('Last Name'),
5550 'default_order' => 'ASC',
5551 'is_fields' => TRUE,
5553 $options['prefix'] . 'nick_name' => [
5554 'name' => 'nick_name',
5555 'title' => $options['prefix_label'] . ts('Nick Name'),
5556 'is_fields' => TRUE,
5558 $options['prefix'] . 'prefix_id' => [
5559 'name' => 'prefix_id',
5560 'title' => $options['prefix_label'] . ts('Prefix'),
5561 'options' => CRM_Contact_BAO_Contact
::buildOptions('prefix_id'),
5562 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5563 'is_fields' => TRUE,
5564 'is_filters' => TRUE,
5566 $options['prefix'] . 'suffix_id' => [
5567 'name' => 'suffix_id',
5568 'title' => $options['prefix_label'] . ts('Suffix'),
5569 'options' => CRM_Contact_BAO_Contact
::buildOptions('suffix_id'),
5570 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5571 'is_fields' => TRUE,
5572 'is_filters' => TRUE,
5574 $options['prefix'] . 'gender_id' => [
5575 'name' => 'gender_id',
5576 'title' => $options['prefix_label'] . ts('Gender'),
5577 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5578 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5579 'is_fields' => TRUE,
5580 'is_filters' => TRUE,
5583 'title' => $options['prefix_label'] . ts('Birth Date'),
5584 'operatorType' => CRM_Report_Form
::OP_DATE
,
5585 'type' => CRM_Utils_Type
::T_DATE
,
5586 'is_fields' => TRUE,
5587 'is_filters' => TRUE,
5590 'title' => $options['prefix_label'] . ts('Age'),
5591 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5592 'type' => CRM_Utils_Type
::T_INT
,
5593 'is_fields' => TRUE,
5595 $options['prefix'] . 'is_deceased' => [
5596 'title' => $options['prefix_label'] . ts('Is deceased'),
5597 'name' => 'is_deceased',
5598 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5599 'is_fields' => FALSE,
5600 'is_filters' => TRUE,
5601 'is_group_bys' => FALSE,
5603 $options['prefix'] . 'job_title' => [
5604 'name' => 'job_title',
5605 'is_fields' => TRUE,
5606 'is_filters' => FALSE,
5607 'is_group_bys' => FALSE,
5609 $options['prefix'] . 'employer_id' => [
5610 'title' => $options['prefix_label'] . ts('Current Employer'),
5611 'type' => CRM_Utils_Type
::T_INT
,
5612 'name' => 'employer_id',
5613 'is_fields' => TRUE,
5614 'is_filters' => FALSE,
5615 'is_group_bys' => TRUE,
5618 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5619 $spec = array_merge($spec, $individualFields);
5622 if (!empty($options['custom_fields'])) {
5623 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = [
5624 'extends' => $options['custom_fields'],
5625 'title' => $options['prefix_label'],
5626 'filters' => $options['filters'],
5627 'prefix' => $options['prefix'],
5628 'prefix_label' => $options['prefix_label'],
5632 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5636 * Get address columns to add to array.
5638 * @param array $options
5639 * - prefix Prefix to add to table (in case of more than one instance of the table)
5640 * - prefix_label Label to give columns from this address table instance
5641 * - group_bys enable these fields for group by - default false
5642 * - order_bys enable these fields for order by
5643 * - filters enable these fields for filtering
5645 * @return array address columns definition
5647 protected function getAddressColumns($options = []) {
5650 'prefix_label' => '',
5652 'group_bys' => FALSE,
5653 'order_bys' => TRUE,
5655 'join_filters' => FALSE,
5656 'fields_defaults' => [],
5657 'filters_defaults' => [],
5658 'group_bys_defaults' => [],
5659 'order_bys_defaults' => [],
5662 $options = array_merge($defaultOptions, $options);
5663 $defaults = $this->getDefaultsFromOptions($options);
5664 $tableAlias = $options['prefix'] . 'address';
5667 $options['prefix'] . 'name' => [
5668 'title' => $options['prefix_label'] . ts('Address Name'),
5670 'is_fields' => TRUE,
5672 $options['prefix'] . 'street_number' => [
5673 'name' => 'street_number',
5674 'title' => $options['prefix_label'] . ts('Street Number'),
5676 'is_fields' => TRUE,
5678 $options['prefix'] . 'odd_street_number' => [
5679 'title' => ts('Odd / Even Street Number'),
5680 'name' => 'odd_street_number',
5681 'type' => CRM_Utils_Type
::T_INT
,
5682 'no_display' => TRUE,
5684 'dbAlias' => "({$tableAlias}_civireport.street_number % 2)",
5685 'is_fields' => TRUE,
5686 'is_order_bys' => TRUE,
5688 $options['prefix'] . 'street_name' => [
5689 'name' => 'street_name',
5690 'title' => $options['prefix_label'] . ts('Street Name'),
5692 'is_fields' => TRUE,
5693 'is_filters' => TRUE,
5694 'operator' => 'like',
5695 'is_order_bys' => TRUE,
5697 $options['prefix'] . 'street_address' => [
5698 'title' => $options['prefix_label'] . ts('Street Address'),
5699 'name' => 'street_address',
5700 'is_fields' => TRUE,
5701 'is_filters' => TRUE,
5702 'is_group_bys' => TRUE,
5704 $options['prefix'] . 'supplemental_address_1' => [
5705 'title' => $options['prefix_label'] . ts('Supplementary Address Field 1'),
5706 'name' => 'supplemental_address_1',
5707 'is_fields' => TRUE,
5709 $options['prefix'] . 'supplemental_address_2' => [
5710 'title' => $options['prefix_label'] . ts('Supplementary Address Field 2'),
5711 'name' => 'supplemental_address_2',
5712 'is_fields' => TRUE,
5714 $options['prefix'] . 'supplemental_address_3' => [
5715 'title' => $options['prefix_label'] . ts('Supplementary Address Field 3'),
5716 'name' => 'supplemental_address_3',
5717 'is_fields' => TRUE,
5719 $options['prefix'] . 'street_number' => [
5720 'name' => 'street_number',
5721 'title' => $options['prefix_label'] . ts('Street Number'),
5723 'is_order_bys' => TRUE,
5724 'is_filters' => TRUE,
5725 'is_fields' => TRUE,
5727 $options['prefix'] . 'street_unit' => [
5728 'name' => 'street_unit',
5729 'title' => $options['prefix_label'] . ts('Street Unit'),
5731 'is_fields' => TRUE,
5733 $options['prefix'] . 'city' => [
5734 'title' => $options['prefix_label'] . ts('City'),
5736 'operator' => 'like',
5737 'is_fields' => TRUE,
5738 'is_filters' => TRUE,
5739 'is_group_bys' => TRUE,
5740 'is_order_bys' => TRUE,
5742 $options['prefix'] . 'postal_code' => [
5743 'title' => $options['prefix_label'] . ts('Postal Code'),
5744 'name' => 'postal_code',
5746 'is_fields' => TRUE,
5747 'is_filters' => TRUE,
5748 'is_group_bys' => TRUE,
5749 'is_order_bys' => TRUE,
5751 $options['prefix'] . 'postal_code_suffix' => [
5752 'title' => $options['prefix_label'] . ts('Postal Code Suffix'),
5753 'name' => 'postal_code_suffix',
5755 'is_fields' => TRUE,
5756 'is_filters' => TRUE,
5757 'is_group_bys' => TRUE,
5758 'is_order_bys' => TRUE,
5760 $options['prefix'] . 'county_id' => [
5761 'title' => $options['prefix_label'] . ts('County'),
5762 'alter_display' => 'alterCountyID',
5763 'name' => 'county_id',
5764 'type' => CRM_Utils_Type
::T_INT
,
5765 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5766 'options' => CRM_Core_PseudoConstant
::county(),
5767 'is_fields' => TRUE,
5768 'is_filters' => TRUE,
5769 'is_group_bys' => TRUE,
5771 $options['prefix'] . 'state_province_id' => [
5772 'title' => $options['prefix_label'] . ts('State/Province'),
5773 'alter_display' => 'alterStateProvinceID',
5774 'name' => 'state_province_id',
5775 'type' => CRM_Utils_Type
::T_INT
,
5776 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5777 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5778 'is_fields' => TRUE,
5779 'is_filters' => TRUE,
5780 'is_group_bys' => TRUE,
5782 $options['prefix'] . 'country_id' => [
5783 'title' => $options['prefix_label'] . ts('Country'),
5784 'alter_display' => 'alterCountryID',
5785 'name' => 'country_id',
5786 'is_fields' => TRUE,
5787 'is_filters' => TRUE,
5788 'is_group_bys' => TRUE,
5789 'type' => CRM_Utils_Type
::T_INT
,
5790 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5791 'options' => CRM_Core_PseudoConstant
::country(),
5793 $options['prefix'] . 'location_type_id' => [
5794 'name' => 'location_type_id',
5795 'title' => $options['prefix_label'] . ts('Location Type'),
5796 'type' => CRM_Utils_Type
::T_INT
,
5797 'is_fields' => TRUE,
5798 'alter_display' => 'alterLocationTypeID',
5800 $options['prefix'] . 'id' => [
5801 'title' => $options['prefix_label'] . ts('ID'),
5803 'is_fields' => TRUE,
5805 $options['prefix'] . 'is_primary' => [
5806 'name' => 'is_primary',
5807 'title' => $options['prefix_label'] . ts('Primary Address?'),
5808 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5809 'is_fields' => TRUE,
5812 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5816 * Build the columns.
5818 * The normal report class needs you to remember to do a few things that are often erratic
5820 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5821 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5822 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5823 * means any saved filters / fields on saved report instances. This will mean that matching names from
5824 * different tables may be ambigious, but it will smooth any code transition.
5825 * - note that it assumes the value being passed in is the actual table field name
5827 * 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
5828 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5830 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5831 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5832 * the core classes can start to move towards that.
5834 * @param array $specs
5835 * @param string $tableName
5836 * @param string $daoName
5837 * @param string $tableAlias
5838 * @param array $defaults
5839 * @param array $options
5843 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = [], $options = []) {
5845 $tableAlias = str_replace('civicrm_', '', $tableName);
5847 $types = ['filters', 'group_bys', 'order_bys', 'join_filters'];
5848 $columns = [$tableName => array_fill_keys($types, [])];
5849 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5850 $columns[$tableName]['dao'] = $daoName;
5851 $columns[$tableName]['alias'] = $tableAlias;
5853 foreach ($specs as $specName => $spec) {
5854 if (empty($spec['name'])) {
5855 $spec['name'] = $specName;
5858 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5859 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5860 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5861 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5862 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5865 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5866 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5869 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5870 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5873 foreach ($types as $type) {
5874 if ($options[$type] && !empty($spec['is_' . $type])) {
5875 $columns[$tableName][$type][$fieldAlias] = $spec;
5876 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5877 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5882 if (isset($options['grouping'])) {
5883 $columns[$tableName]['grouping'] = $options['grouping'];
5884 $columns[$tableName]['group_title'] = $options['group_title'] ??
'';
5890 * Store group bys into array - so we can check elsewhere what is grouped.
5892 protected function storeGroupByArray() {
5894 if (empty($this->_params
['group_bys'])
5895 ||
!is_array($this->_params
['group_bys'])) {
5896 $this->_params
['group_bys'] = [];
5899 foreach ($this->_columns
as $tableName => $table) {
5900 $table = $this->_columns
[$tableName];
5901 if (array_key_exists('group_bys', $table)) {
5902 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5903 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5904 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5905 if (!empty($field['chart'])) {
5906 $this->assign('chartSupported', TRUE);
5909 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5910 !empty($this->_params
['group_bys_freq'][$fieldName])
5913 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5915 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5919 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " YEAR({$field['dbAlias']})";
5923 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "YEAR({$field['dbAlias']}), QUARTER({$field['dbAlias']})";
5927 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "YEARWEEK({$field['dbAlias']})";
5931 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_MONTH FROM {$field['dbAlias']})";
5935 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "DATE({$field['dbAlias']})";
5940 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5941 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5956 protected function getDefaultsFromOptions($options) {
5958 'fields_defaults' => $options['fields_defaults'],
5959 'filters_defaults' => $options['filters_defaults'],
5960 'group_bys_defaults' => $options['group_bys_defaults'],
5961 'order_bys_defaults' => $options['order_bys_defaults'],
5967 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5969 * Full group by mode dictates that a field must either be in the group by function or
5970 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5973 * @param string $tableName
5974 * @param string $fieldName
5975 * @param string $field
5978 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5979 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5980 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5981 $label = $field['title'] ??
NULL;
5982 $alias = $field['tplField'] ??
"{$tableName}_{$fieldName}";
5983 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5984 $this->_selectAliases
[] = $alias;
5985 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5986 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5988 return "({$field['dbAlias']}) as $alias";
5994 * Generate clause for the selected filter.
5996 * @param array $field
5997 * Field specification
5998 * @param string $fieldName
6002 * Relevant where clause.
6004 protected function generateFilterClause($field, $fieldName) {
6005 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
6006 if (CRM_Utils_Array
::value('operatorType', $field) ==
6007 CRM_Report_Form
::OP_MONTH
6009 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
6010 $value = $this->_params
["{$fieldName}_value"] ??
NULL;
6011 if (is_array($value) && !empty($value)) {
6012 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
6017 $relative = $this->_params
["{$fieldName}_relative"] ??
NULL;
6018 $from = $this->_params
["{$fieldName}_from"] ??
NULL;
6019 $to = $this->_params
["{$fieldName}_to"] ??
NULL;
6020 $fromTime = $this->_params
["{$fieldName}_from_time"] ??
NULL;
6021 $toTime = $this->_params
["{$fieldName}_to_time"] ??
NULL;
6022 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
6026 $op = $this->_params
["{$fieldName}_op"] ??
NULL;
6028 return $this->whereClause($field,
6030 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
6031 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
6032 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
6040 * Retrieve a suitable object from the factory depending on the report
6041 * parameters, which typically might just be dependent on outputMode.
6043 * If there is no suitable output handler, e.g. if outputMode is "copy",
6044 * then this sets it to NULL.
6046 public function setOutputHandler() {
6047 $this->outputHandler
= \Civi\Report\OutputHandlerFactory
::singleton()->create($this);
6051 * Send report by email
6053 public function sendEmail() {
6054 if (empty($this->outputHandler
)) {
6055 // It's possible to end up here with outputMode unset, so we use
6056 // the "print" handler which was the default before, i.e. include
6057 // it as html in the body.
6058 $oldOutputMode = $this->_outputMode ??
NULL;
6059 $this->_outputMode
= 'print';
6060 $this->setOutputHandler();
6061 $this->_outputMode
= $oldOutputMode;
6064 $mailBody = $this->outputHandler
->getMailBody();
6067 $attachmentFileName = $this->outputHandler
->getFileName();
6068 // It's not always in the form of an attachment, e.g. for 'print' the
6069 // output ends up in $mailBody above.
6070 if ($attachmentFileName) {
6071 $fullFilename = CRM_Core_Config
::singleton()->templateCompileDir
. CRM_Utils_File
::makeFileName($attachmentFileName);
6072 file_put_contents($fullFilename, $this->outputHandler
->getOutputString());
6074 'fullPath' => $fullFilename,
6075 'mime_type' => $this->outputHandler
->getMimeType(),
6076 'cleanName' => $attachmentFileName,
6077 'charset' => $this->outputHandler
->getCharset(),
6082 // @todo outputMode doesn't seem to get used by mailReport, which is good
6083 // since it shouldn't have any outputMode-related `if` statements in it.
6084 // Someday could remove the param from the function call.
6085 if (CRM_Report_Utils_Report
::mailReport($mailBody, $this->_id
, $this->_outputMode
, $attachments)) {
6086 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
6089 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');