3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = [];
80 * The set of filters in the report
84 protected $_filters = [];
87 * The set of optional columns in the report
91 public $_options = [];
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
98 protected $_exposeContactID = TRUE;
101 * Set of statistic fields
105 protected $_statFields = [];
108 * Set of statistics data
112 protected $_statistics = [];
115 * List of fields not to be repeated during display
119 protected $_noRepeats = [];
122 * List of fields not to be displayed
126 protected $_noDisplay = [];
129 * Object type that a custom group extends
133 protected $_customGroupExtends = NULL;
134 protected $_customGroupExtendsJoin = [];
135 protected $_customGroupFilters = TRUE;
136 protected $_customGroupGroupBy = FALSE;
137 protected $_customGroupJoin = 'LEFT JOIN';
143 protected $_tagFilter = FALSE;
146 * specify entity table for tags filter
149 protected $_tagFilterTable = 'civicrm_contact';
152 * Build groups filter.
156 protected $_groupFilter = FALSE;
159 * Has the report been optimised for group filtering.
161 * The functionality for group filtering has been improved but not
162 * all reports have been adjusted to take care of it.
164 * This property exists to highlight the reports which are still using the
165 * slow method & allow group filtering to still work for them until they
168 * In order to protect extensions we have to default to TRUE - but I have
169 * separately marked every class with a groupFilter in the hope that will trigger
170 * people to fix them as they touch them.
176 protected $groupFilterNotOptimised = TRUE;
183 public $_navigation = [];
185 public $_drilldownReport = [];
188 * Array of tabs to display on report.
190 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
192 * $this->tabs['OrderBy'] = array(
193 * 'title' => ts('Sorting'),
194 * 'tpl' => 'OrderBy',
195 * 'div_label' => 'order-by',
200 protected $tabs = [];
203 * Should we add paging.
207 protected $addPaging = TRUE;
209 protected $isForceGroupBy = FALSE;
211 protected $groupConcatTested = FALSE;
214 * An attribute for checkbox/radio form field layout
218 protected $_fourColumnAttribute = [
219 '</td><td width="25%">',
220 '</td><td width="25%">',
221 '</td><td width="25%">',
225 protected $_force = 1;
227 protected $_params = NULL;
228 protected $_formValues = NULL;
229 protected $_instanceValues = NULL;
231 protected $_instanceForm = FALSE;
232 protected $_criteriaForm = FALSE;
234 protected $_instanceButtonName = NULL;
235 protected $_createNewButtonName = NULL;
236 protected $_printButtonName = NULL;
237 protected $_pdfButtonName = NULL;
238 protected $_csvButtonName = NULL;
239 protected $_groupButtonName = NULL;
240 protected $_chartButtonName = NULL;
241 protected $_csvSupported = TRUE;
242 protected $_add2groupSupported = TRUE;
243 protected $_groups = NULL;
244 protected $_grandFlag = FALSE;
245 protected $_rowsFound = NULL;
246 protected $_selectAliases = [];
247 protected $_rollup = NULL;
250 * Table containing list of contact IDs within the group filter.
254 protected $groupTempTable = '';
259 protected $_aliases = [];
275 protected $_limit = NULL;
278 * This can be set to specify a limit to the number of rows
279 * Since it is currently envisaged as part of the api usage it is only being applied
280 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
281 * of the code (see limit() fn.
285 protected $_limitValue = NULL;
288 * This can be set to specify row offset
289 * See notes on _limitValue
293 protected $_offsetValue = NULL;
297 protected $_sections = NULL;
298 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
299 protected $_absoluteUrl = FALSE;
302 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
306 protected $_storeResultSet = FALSE;
309 * When _storeResultSet Flag is set use this var to store result set in form of array
313 protected $_resultSet = [];
316 * To what frequency group-by a date column
320 protected $_groupByDateFreq = [
322 'YEARWEEK' => 'Week',
323 'QUARTER' => 'Quarter',
328 * Variables to hold the acl inner join and where clause
331 protected $_aclFrom = NULL;
332 protected $_aclWhere = NULL;
335 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
337 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
341 protected $_selectedTables = [];
344 * Array of DAO tables having columns included in WHERE or HAVING clause
348 protected $filteredTables;
351 * Output mode e.g 'print', 'csv', 'pdf'.
355 protected $_outputMode;
358 * Format of any chart in use.
360 * (it's unclear if this could be merged with outputMode at this stage)
366 public $_having = NULL;
367 public $_select = NULL;
368 public $_selectClauses = [];
369 public $_columnHeaders = [];
370 public $_orderBy = NULL;
371 public $_orderByFields = [];
372 public $_orderByArray = [];
374 * Array of clauses to group by.
378 protected $_groupByArray = [];
379 public $_groupBy = NULL;
380 public $_whereClauses = [];
381 public $_havingClauses = [];
384 * DashBoardRowCount Dashboard row count.
388 public $_dashBoardRowCount;
391 * Is this being called without a form controller (ie. the report is being render outside the normal form
392 * - e.g the api is retrieving the rows.
396 public $noController = FALSE;
399 * Variable to hold the currency alias.
403 protected $_currencyColumn = NULL;
408 protected $_interval;
413 protected $_sendmail;
426 * Report description.
430 public $_description;
433 * Is an address field selected.
436 * This was intended to determine if the address table should be joined in
437 * The isTableSelected function is now preferred for this purpose
439 protected $_addressField;
442 * Is an email field selected.
445 * This was intended to determine if the email table should be joined in
446 * The isTableSelected function is now preferred for this purpose
448 protected $_emailField;
451 * Is a phone field selected.
454 * This was intended to determine if the phone table should be joined in
455 * The isTableSelected function is now preferred for this purpose
457 protected $_phoneField;
460 * Create new report instance? (or update existing) on save.
464 protected $_createNew;
467 * When a grand total row has calculated the status we pop it off to here.
469 * This allows us to access it from the stats function and avoid recalculating.
473 protected $rollupRow = [];
476 * Database attributes - character set and collation.
480 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
483 * SQL being run in this report.
485 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
493 * An instruction not to add a Group By.
495 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
497 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
498 * such as in pivot charts when no row header is set
502 protected $noGroupBy = FALSE;
505 * SQL being run in this report as an array.
507 * The sql in the report is stored in this variable in order to be returned to api & test calls.
515 * Tables created for the report that need removal afterwards.
517 * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x']
520 protected $temporaryTables = [];
523 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
526 public $optimisedForOnlyFullGroupBy = TRUE;
531 public function __construct() {
532 parent
::__construct();
534 $this->addClass('crm-report-form');
536 if ($this->_tagFilter
) {
537 $this->buildTagFilter();
539 if ($this->_exposeContactID
) {
540 if (array_key_exists('civicrm_contact', $this->_columns
)) {
541 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = [
543 'title' => ts('Contact ID'),
549 if ($this->_groupFilter
) {
550 $this->buildGroupFilter();
553 // Get all custom groups
554 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
556 // Get the custom groupIds for which the user has VIEW permission
557 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
558 // and addCustomDataToColumns() will allow access to all custom groups.
559 $permCustomGroupIds = [];
560 if (!CRM_Core_Permission
::check('access all custom data')) {
561 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
562 // do not allow custom data for reports if user doesn't have
563 // permission to access custom data.
564 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
565 $this->_customGroupExtends
= [];
569 // merge custom data columns to _columns list, if any
570 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
572 // add / modify display columns, filters ..etc
573 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
575 //assign currencyColumn variable to tpl
576 $this->assign('currencyColumn', $this->_currencyColumn
);
580 * Shared pre-process function.
582 * If overriding preProcess function this should still be called.
586 public function preProcessCommon() {
587 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
589 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
591 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
593 $this->assign('section', $this->_section
);
594 CRM_Core_Region
::instance('page-header')->add([
595 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
597 if (!$this->noController
) {
598 $this->setID($this->get('instanceId'));
601 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
603 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
607 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
608 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
609 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
613 $this->assign('instanceId', $this->_id
);
614 $params = ['id' => $this->_id
];
615 $this->_instanceValues
= [];
616 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
618 $this->_instanceValues
620 if (empty($this->_instanceValues
)) {
621 CRM_Core_Error
::fatal("Report could not be loaded.");
623 $this->_title
= $this->_instanceValues
['title'];
624 if (!empty($this->_instanceValues
['permission']) &&
625 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
626 CRM_Core_Permission
::check('administer Reports')
629 CRM_Utils_System
::permissionDenied();
630 CRM_Utils_System
::civiExit();
633 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
635 $this->_formValues
= unserialize($formValues);
638 $this->_formValues
= NULL;
641 $this->setOutputMode();
643 if ($this->_outputMode
== 'copy') {
644 $this->_createNew
= TRUE;
645 $this->_params
= $this->_formValues
;
646 $this->_params
['view_mode'] = 'criteria';
647 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', [
648 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
649 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
651 // Do not pass go. Do not collect another chance to re-run the same query.
652 CRM_Report_Form_Instance
::postProcess($this);
655 // lets always do a force if reset is found in the url.
656 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
657 // in the comment line above these 2.
658 if (!empty($_REQUEST['reset'])
659 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), ['save', 'criteria'])) {
664 $this->assign('mode', 'instance');
666 elseif (!$this->noController
) {
667 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
668 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
669 if (($instanceCount > 0) && $optionValueID) {
670 $this->assign('instanceUrl',
671 CRM_Utils_System
::url('civicrm/report/list',
672 "reset=1&ovid=$optionValueID"
676 if ($optionValueID) {
677 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
681 $this->assign('mode', 'template');
684 // lets display the Report Settings section
685 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
687 // Do not display Report Settings section if administer Reports permission is absent OR
688 // if report instance is reserved and administer reserved reports absent
689 if (!CRM_Core_Permission
::check('administer Reports') ||
690 ($this->_instanceValues
['is_reserved'] &&
691 !CRM_Core_Permission
::check('administer reserved reports'))
693 $this->_instanceForm
= FALSE;
696 $this->assign('criteriaForm', FALSE);
697 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
698 if (CRM_Core_Permission
::check('administer Reports') ||
699 CRM_Core_Permission
::check('access Report Criteria')
701 if (!$this->_instanceValues
['is_reserved'] ||
702 CRM_Core_Permission
::check('administer reserved reports')
704 $this->assign('criteriaForm', TRUE);
705 $this->_criteriaForm
= TRUE;
709 // Special permissions check for private instance if it's not the current contact instance
711 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
712 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
713 if (!CRM_Core_Permission
::check('access all private reports')) {
714 $this->_instanceForm
= FALSE;
715 $this->assign('criteriaForm', FALSE);
719 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
720 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
721 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
722 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
728 public function addBreadCrumb() {
732 'title' => ts('Report Templates'),
733 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
737 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
741 * Pre process function.
743 * Called prior to build form.
745 public function preProcess() {
746 $this->preProcessCommon();
749 $this->addBreadCrumb();
752 foreach ($this->_columns
as $tableName => $table) {
753 $this->setTableAlias($table, $tableName);
756 // higher preference to bao object
757 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
760 if (method_exists($daoOrBaoName, 'exportableFields')) {
761 $expFields = $daoOrBaoName::exportableFields();
764 $expFields = $daoOrBaoName::export();
768 $doNotCopy = ['required', 'default'];
770 $fieldGroups = ['fields', 'filters', 'group_bys', 'order_bys'];
771 foreach ($fieldGroups as $fieldGrp) {
772 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
773 foreach ($table[$fieldGrp] as $fieldName => $field) {
774 // $name is the field name used to reference the BAO/DAO export fields array
775 $name = isset($field['name']) ?
$field['name'] : $fieldName;
777 // Sometimes the field name key in the BAO/DAO export fields array is
778 // different from the actual database field name.
779 // Unset $field['name'] so that actual database field name can be obtained
780 // from the BAO/DAO export fields array.
781 unset($field['name']);
783 if (array_key_exists($name, $expFields)) {
784 foreach ($doNotCopy as $dnc) {
785 // unset the values we don't want to be copied.
786 unset($expFields[$name][$dnc]);
789 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
792 foreach ($expFields[$name] as $property => $val) {
793 if (!array_key_exists($property, $field)) {
794 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
801 if (!empty($field['no_repeat'])) {
802 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
804 if (!empty($field['no_display'])) {
805 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
808 // set alias = table-name, unless already set
809 $alias = isset($field['alias']) ?
$field['alias'] : (
810 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
812 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
814 // set name = fieldName, unless already set
815 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
816 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
819 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
820 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
823 // set dbAlias = alias.name, unless already set
824 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
825 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
827 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
830 // a few auto fills for filters
831 if ($fieldGrp == 'filters') {
832 // fill operator types
833 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
834 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
835 case CRM_Utils_Type
::T_MONEY
:
836 case CRM_Utils_Type
::T_FLOAT
:
837 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
840 case CRM_Utils_Type
::T_INT
:
841 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
844 case CRM_Utils_Type
::T_DATE
:
845 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
848 case CRM_Utils_Type
::T_BOOLEAN
:
849 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
850 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
851 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
862 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
864 // with multiple options operator-type is generally multi-select
865 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
866 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
868 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
875 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
876 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
879 $this->_columns
[$tableName]['metadata'][$fieldName] = array_merge($this->_columns
[$tableName][$fieldGrp][$fieldName], $this->_columns
[$tableName]['metadata'][$fieldName]);
885 // copy filters to a separate handy variable
886 if (array_key_exists('filters', $table)) {
887 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
890 if (array_key_exists('group_bys', $table)) {
891 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
894 if (array_key_exists('fields', $table)) {
895 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
900 $this->setDefaultValues(FALSE);
903 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
904 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
905 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
906 CRM_Report_Utils_Get
::processChart($this->_defaults
);
909 $this->_formValues
= $this->_defaults
;
910 $this->postProcess();
915 * Set default values.
917 * @param bool $freeze
921 public function setDefaultValues($freeze = TRUE) {
924 // FIXME: generalizing form field naming conventions would reduce
925 // Lots of lines below.
926 foreach ($this->_columns
as $tableName => $table) {
927 if (array_key_exists('fields', $table)) {
928 foreach ($table['fields'] as $fieldName => $field) {
929 if (empty($field['no_display'])) {
930 if (!empty($field['required'])) {
932 $this->_defaults
['fields'][$fieldName] = 1;
935 // find element object, so that we could use quickform's freeze method
936 // for required elements
937 $obj = $this->getElementFromGroup("fields", $fieldName);
939 $freezeGroup[] = $obj;
943 elseif (isset($field['default'])) {
944 $this->_defaults
['fields'][$fieldName] = $field['default'];
950 if (array_key_exists('group_bys', $table)) {
951 foreach ($table['group_bys'] as $fieldName => $field) {
952 if (isset($field['default'])) {
953 if (!empty($field['frequency'])) {
954 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
956 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
960 if (array_key_exists('filters', $table)) {
961 foreach ($table['filters'] as $fieldName => $field) {
962 if (isset($field['default'])) {
963 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
965 if (is_array($field['default'])) {
966 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
967 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
968 $this->_defaults
["{$fieldName}_relative"] = 0;
971 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
975 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
976 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
977 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
979 $this->_defaults
["{$fieldName}_value"] = $field['default'];
982 //assign default value as "in" for multiselect
983 //operator, To freeze the select element
984 if (CRM_Utils_Array
::value('operatorType', $field) ==
985 CRM_Report_Form
::OP_MULTISELECT
987 $this->_defaults
["{$fieldName}_op"] = 'in';
989 if (CRM_Utils_Array
::value('operatorType', $field) ==
990 CRM_Report_Form
::OP_ENTITYREF
992 $this->_defaults
["{$fieldName}_op"] = 'in';
994 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
995 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
997 $this->_defaults
["{$fieldName}_op"] = 'mhas';
999 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
1000 $this->_defaults
["{$fieldName}_op"] = $op;
1006 empty($this->_formValues
['order_bys']) &&
1007 (array_key_exists('order_bys', $table) &&
1008 is_array($table['order_bys']))
1010 if (!array_key_exists('order_bys', $this->_defaults
)) {
1011 $this->_defaults
['order_bys'] = [];
1013 foreach ($table['order_bys'] as $fieldName => $field) {
1014 if (!empty($field['default']) ||
!empty($field['default_order']) ||
1015 CRM_Utils_Array
::value('default_is_section', $field) ||
1016 !empty($field['default_weight'])
1019 'column' => $fieldName,
1020 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
1021 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
1024 if (!empty($field['default_weight'])) {
1025 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
1028 array_unshift($this->_defaults
['order_bys'], $order_by);
1034 foreach ($this->_options
as $fieldName => $field) {
1035 if (isset($field['default'])) {
1036 $this->_defaults
['options'][$fieldName] = $field['default'];
1041 if (!empty($this->_submitValues
)) {
1042 $this->preProcessOrderBy($this->_submitValues
);
1045 $this->preProcessOrderBy($this->_defaults
);
1048 // lets finish freezing task here itself
1049 if (!empty($freezeGroup)) {
1050 foreach ($freezeGroup as $elem) {
1055 if ($this->_formValues
) {
1056 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1059 if ($this->_instanceValues
) {
1060 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1063 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1065 return $this->_defaults
;
1069 * Get element from group.
1071 * @param string $group
1072 * @param string $grpFieldName
1076 public function getElementFromGroup($group, $grpFieldName) {
1077 $eleObj = $this->getElement($group);
1078 foreach ($eleObj->_elements
as $index => $obj) {
1079 if ($grpFieldName == $obj->_attributes
['name']) {
1087 * Setter for $_params.
1089 * @param array $params
1091 public function setParams($params) {
1092 $this->_params
= $params;
1096 * Getter for $_params.
1098 * @return void|array $params
1100 public function getParams() {
1101 return $this->_params
;
1107 * @param int $instanceID
1109 public function setID($instanceID) {
1110 $this->_id
= $instanceID;
1114 * Setter for $_force.
1116 * @param bool $isForce
1118 public function setForce($isForce) {
1119 $this->_force
= $isForce;
1123 * Setter for $_limitValue.
1125 * @param int $_limitValue
1127 public function setLimitValue($_limitValue) {
1128 $this->_limitValue
= $_limitValue;
1132 * Setter for $_offsetValue.
1134 * @param int $_offsetValue
1136 public function setOffsetValue($_offsetValue) {
1137 $this->_offsetValue
= $_offsetValue;
1141 * Setter for $addPaging.
1143 * @param bool $value
1145 public function setAddPaging($value) {
1146 $this->addPaging
= $value;
1150 * Getter for $_defaultValues.
1154 public function getDefaultValues() {
1155 return $this->_defaults
;
1159 * Remove any temporary tables.
1161 public function cleanUpTemporaryTables() {
1162 foreach ($this->temporaryTables
as $temporaryTable) {
1163 CRM_Core_DAO
::executeQuery('DROP ' . ($temporaryTable['temporary'] ?
'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']);
1168 * Create a temporary table.
1170 * This function creates a table AND adds the details to the developer tab & $this->>temporary tables.
1172 * @param string $identifier
1173 * This is the key that will be used for the table in the temporaryTables property.
1174 * @param string $sql
1175 * Sql select statement or column description (the latter requires the columns flag)
1176 * @param bool $isColumns
1177 * Is the sql describing columns to create (rather than using a select query).
1178 * @param bool $isMemory
1179 * Create a memory table rather than a normal INNODB table.
1183 public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) {
1184 $tempTable = CRM_Utils_SQL_TempTable
::build();
1186 $tempTable->setMemory();
1189 $tempTable->createWithColumns($sql);
1192 $tempTable->createWithQuery($sql);
1194 $name = $tempTable->getName();
1195 // Developers may force tables to be durable to assist in debugging so lets check.
1196 $isNotTrueTemporary = $tempTable->isDurable();
1197 $this->addToDeveloperTab($tempTable->getCreateSql());
1198 $this->temporaryTables
[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name];
1203 * Add columns to report.
1205 public function addColumns() {
1208 foreach ($this->_columns
as $tableName => $table) {
1209 if (array_key_exists('fields', $table)) {
1210 foreach ($table['fields'] as $fieldName => $field) {
1212 if (empty($field['no_display'])) {
1213 foreach (['table', 'field'] as $var) {
1214 if (!empty($
{$var}['grouping'])) {
1215 if (!is_array($
{$var}['grouping'])) {
1216 $tableName = $
{$var}['grouping'];
1219 $tableName = array_keys($
{$var}['grouping']);
1220 $tableName = $tableName[0];
1221 $groupTitle = array_values($
{$var}['grouping']);
1222 $groupTitle = $groupTitle[0];
1227 if (!$groupTitle && isset($table['group_title'])) {
1228 $groupTitle = $table['group_title'];
1229 // Having a group_title is secret code for being a custom group
1230 // which cryptically translates to needing an accordion.
1231 // here we make that explicit.
1232 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1235 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1236 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1237 $colGroups[$tableName]['group_title'] = $groupTitle;
1239 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1245 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1246 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1248 if (!empty($colGroups)) {
1249 $this->tabs
['FieldSelection'] = [
1250 'title' => ts('Columns'),
1251 'tpl' => 'FieldSelection',
1252 'div_label' => 'col-groups',
1255 // Note this assignment is only really required in buildForm. It is being 'over-called'
1256 // to reduce risk of being missed due to overridden functions.
1257 $this->assign('tabs', $this->tabs
);
1260 $this->assign('colGroups', $colGroups);
1264 * Add filters to report.
1266 public function addFilters() {
1267 $filters = $filterGroups = [];
1270 foreach ($this->_filters
as $table => $attributes) {
1271 if (isset($this->_columns
[$table]['group_title'])) {
1272 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1273 // which magically means to 'display in an accordian'
1274 // here we make this explicit.
1275 $filterGroups[$table] = [
1276 'group_title' => $this->_columns
[$table]['group_title'],
1277 'use_accordian_for_field_selection' => TRUE,
1281 foreach ($attributes as $fieldName => $field) {
1282 // get ready with option value pair
1283 // @ 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
1285 $operations = $this->getOperationPair(
1286 CRM_Utils_Array
::value('operatorType', $field),
1289 $filters[$table][$fieldName] = $field;
1291 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1292 case CRM_Report_Form
::OP_MONTH
:
1293 if (!array_key_exists('options', $field) ||
1294 !is_array($field['options']) ||
empty($field['options'])
1296 // If there's no option list for this filter, define one.
1297 $field['options'] = [
1299 2 => ts('February'),
1306 9 => ts('September'),
1307 10 => ts('October'),
1308 11 => ts('November'),
1309 12 => ts('December'),
1311 // Add this option list to this column _columns. This is
1312 // required so that filter statistics show properly.
1313 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1315 case CRM_Report_Form
::OP_MULTISELECT
:
1316 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1317 // assume a multi-select field
1318 if (!empty($field['options']) ||
1319 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1321 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1322 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1325 if (count($operations) <= 1) {
1328 if ($fieldName == 'state_province_id' ||
1329 $fieldName == 'county_id'
1331 $this->addChainSelect($fieldName . '_value', [
1338 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], [
1339 'style' => 'min-width:250px',
1340 'class' => 'crm-select2 huge',
1342 'placeholder' => ts('- select -'),
1348 case CRM_Report_Form
::OP_SELECT
:
1349 // assume a select field
1350 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1351 if (!empty($field['options'])) {
1352 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1356 case CRM_Report_Form
::OP_ENTITYREF
:
1357 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1358 $this->setEntityRefDefaults($field, $table);
1359 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1362 case CRM_Report_Form
::OP_DATE
:
1363 // build datetime fields
1364 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1368 case CRM_Report_Form
::OP_DATETIME
:
1369 // build datetime fields
1370 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1374 case CRM_Report_Form
::OP_INT
:
1375 case CRM_Report_Form
::OP_FLOAT
:
1376 // and a min value input box
1377 $this->add('text', "{$fieldName}_min", ts('Min'));
1378 // and a max value input box
1379 $this->add('text', "{$fieldName}_max", ts('Max'));
1381 // default type is string
1382 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1383 ['onchange' => "return showHideMaxMinVal( '$fieldName', this.value );"]
1385 // we need text box for value input
1386 $this->add('text', "{$fieldName}_value", NULL, ['class' => 'huge']);
1391 if (!empty($filters)) {
1392 $this->tabs
['Filters'] = [
1393 'title' => ts('Filters'),
1395 'div_label' => 'set-filters',
1398 $this->assign('filters', $filters);
1399 $this->assign('filterGroups', $filterGroups);
1403 * Function to assign the tabs to the template in the correct order.
1405 * We want the tabs to wind up in this order (if not overridden).
1413 protected function assignTabs() {
1421 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1422 $order = array_merge($order, $this->tabs
);
1423 $this->assign('tabs', $order);
1427 * The intent is to add a tab for developers to view the sql.
1429 * Currently using dpm.
1431 * @param string $sql
1433 public function addToDeveloperTab($sql) {
1434 if (!CRM_Core_Permission
::check('view report sql')) {
1437 $ignored_output_modes = ['pdf', 'csv', 'print'];
1438 if (in_array($this->_outputMode
, $ignored_output_modes)) {
1441 $this->tabs
['Developer'] = [
1442 'title' => ts('Developer'),
1443 'tpl' => 'Developer',
1444 'div_label' => 'set-developer',
1447 $this->assignTabs();
1448 $this->sqlArray
[] = $sql;
1449 foreach ($this->sqlArray
as $sql) {
1450 foreach (['LEFT JOIN'] as $term) {
1451 $sql = str_replace($term, '<br> ' . $term, $sql);
1453 foreach (['FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';'] as $term) {
1454 $sql = str_replace($term, '<br><br>' . $term, $sql);
1456 $this->sqlFormattedArray
[] = $sql;
1457 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1459 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL
::getSqlModes());
1464 * Add options defined in $this->_options to the report.
1466 public function addOptions() {
1467 if (!empty($this->_options
)) {
1468 // FIXME: For now lets build all elements as checkboxes.
1469 // Once we clear with the format we can build elements based on type
1471 foreach ($this->_options
as $fieldName => $field) {
1474 if ($field['type'] == 'select') {
1475 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1477 elseif ($field['type'] == 'checkbox') {
1478 $options[$field['title']] = $fieldName;
1479 $this->addCheckBox($fieldName, NULL,
1481 NULL, NULL, NULL, $this->_fourColumnAttribute
1486 if (!empty($this->_options
) &&
1488 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1490 $this->tabs
['ReportOptions'] = [
1491 'title' => ts('Display Options'),
1492 'tpl' => 'ReportOptions',
1493 'div_label' => 'other-options',
1496 $this->assign('otherOptions', $this->_options
);
1500 * Add chart options to the report.
1502 public function addChartOptions() {
1503 if (!empty($this->_charts
)) {
1504 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1505 $this->assign('charts', $this->_charts
);
1506 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1511 * Add group by options to the report.
1513 public function addGroupBys() {
1514 $options = $freqElements = [];
1516 foreach ($this->_columns
as $tableName => $table) {
1517 if (array_key_exists('group_bys', $table)) {
1518 foreach ($table['group_bys'] as $fieldName => $field) {
1519 if (!empty($field) && empty($field['no_display'])) {
1520 $options[$field['title']] = $fieldName;
1521 if (!empty($field['frequency'])) {
1522 $freqElements[$field['title']] = $fieldName;
1528 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1529 NULL, NULL, NULL, $this->_fourColumnAttribute
1531 $this->assign('groupByElements', $options);
1532 if (!empty($options)) {
1533 $this->tabs
['GroupBy'] = [
1534 'title' => ts('Grouping'),
1536 'div_label' => 'group-by-elements',
1540 foreach ($freqElements as $name) {
1541 $this->addElement('select', "group_bys_freq[$name]",
1542 ts('Frequency'), $this->_groupByDateFreq
1548 * Add data for order by tab.
1550 public function addOrderBys() {
1552 foreach ($this->_columns
as $tableName => $table) {
1554 // Report developer may define any column to order by; include these as order-by options.
1555 if (array_key_exists('order_bys', $table)) {
1556 foreach ($table['order_bys'] as $fieldName => $field) {
1557 if (!empty($field)) {
1558 $options[$fieldName] = $field['title'];
1563 // Add searchable custom fields as order-by options, if so requested
1564 // (These are already indexed, so allowing to order on them is cheap.)
1566 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1567 array_key_exists('extends', $table) && !empty($table['extends'])
1569 foreach ($table['fields'] as $fieldName => $field) {
1570 if (empty($field['no_display'])) {
1571 $options[$fieldName] = $field['title'];
1579 $this->assign('orderByOptions', $options);
1580 if (!empty($options)) {
1581 $this->tabs
['OrderBy'] = [
1582 'title' => ts('Sorting'),
1584 'div_label' => 'order-by-elements',
1588 if (!empty($options)) {
1590 '-' => ' - none - ',
1592 for ($i = 1; $i <= 5; $i++
) {
1593 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1594 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
1595 'ASC' => ts('Ascending'),
1596 'DESC' => ts('Descending'),
1598 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, ['id' => "order_by_section_$i"]);
1599 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, ['id' => "order_by_pagebreak_$i"]);
1605 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1607 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1608 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1611 public function buildInstanceAndButtons() {
1612 CRM_Report_Form_Instance
::buildForm($this);
1613 $this->_actionButtonName
= $this->getButtonName('submit');
1614 $this->addTaskMenu($this->getActions($this->_id
));
1616 $this->assign('instanceForm', $this->_instanceForm
);
1618 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1619 $permission = CRM_Core_Permission
::getPermission();
1620 if ($this->_instanceForm
&& $permission == CRM_Core_Permission
::EDIT
&&
1621 $this->_add2groupSupported
1623 $this->addElement('select', 'groups', ts('Group'),
1624 ['' => ts('Add Contacts to Group')] +
1625 CRM_Core_PseudoConstant
::nestedGroup(),
1626 ['class' => 'crm-select2 crm-action-menu fa-plus huge']
1628 $this->assign('group', TRUE);
1631 $this->addElement('submit', $this->_groupButtonName
, '', ['style' => 'display: none;']);
1633 $this->addChartOptions();
1634 $showResultsLabel = $this->getResultsLabel();
1638 'name' => $showResultsLabel,
1639 'isDefault' => TRUE,
1645 * Has this form been submitted already?
1649 public function resultsDisplayed() {
1650 $buttonName = $this->controller
->getButtonName();
1651 return ($buttonName ||
$this->_outputMode
);
1655 * Get the actions for this report instance.
1657 * @param int $instanceId
1661 protected function getActions($instanceId) {
1662 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1663 if (empty($instanceId)) {
1664 $actions['report_instance.save'] = [
1665 'title' => ts('Create Report'),
1667 'is_confirm' => TRUE,
1668 'confirm_title' => ts('Create Report'),
1669 'confirm_refresh_fields' => json_encode([
1670 'title' => ['selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''],
1671 'description' => ['selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''],
1675 unset($actions['report_instance.delete']);
1678 if (!$this->_csvSupported
) {
1679 unset($actions['report_instance.csv']);
1686 * Main build form function.
1688 public function buildQuickForm() {
1689 $this->addColumns();
1691 $this->addFilters();
1693 $this->addOptions();
1695 $this->addGroupBys();
1697 $this->addOrderBys();
1699 $this->buildInstanceAndButtons();
1701 // Add form rule for report.
1706 $this->addFormRule([get_class($this), 'formRule'], $this);
1708 $this->assignTabs();
1712 * A form rule function for custom data.
1714 * The rule ensures that fields selected in group_by if any) should only be the ones
1715 * present in display/select fields criteria;
1716 * note: works if and only if any custom field selected in group_by.
1718 * @param array $fields
1719 * @param array $ignoreFields
1723 public function customDataFormRule($fields, $ignoreFields = []) {
1725 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1726 !empty($fields['group_bys'])
1728 foreach ($this->_columns
as $tableName => $table) {
1729 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1730 substr($tableName, 0, 12) == 'custom_value') &&
1731 !empty($this->_columns
[$tableName]['fields'])
1733 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1734 if (array_key_exists($fieldName, $fields['group_bys']) &&
1735 !array_key_exists($fieldName, $fields['fields'])
1737 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1739 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1740 foreach ($fields['fields'] as $fld => $val) {
1741 if (!array_key_exists($fld, $fields['group_bys']) &&
1742 !in_array($fld, $ignoreFields)
1744 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1756 * Get operators to display on form.
1758 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1760 * @param string $type
1761 * @param string $fieldName
1765 public function getOperationPair($type = "string", $fieldName = NULL) {
1766 // FIXME: At some point we should move these key-val pairs
1767 // to option_group and option_value table.
1769 case CRM_Report_Form
::OP_INT
:
1770 case CRM_Report_Form
::OP_FLOAT
:
1773 'lte' => ts('Is less than or equal to'),
1774 'gte' => ts('Is greater than or equal to'),
1775 'bw' => ts('Is between'),
1776 'eq' => ts('Is equal to'),
1777 'lt' => ts('Is less than'),
1778 'gt' => ts('Is greater than'),
1779 'neq' => ts('Is not equal to'),
1780 'nbw' => ts('Is not between'),
1781 'nll' => ts('Is empty (Null)'),
1782 'nnll' => ts('Is not empty (Null)'),
1786 case CRM_Report_Form
::OP_SELECT
:
1788 'eq' => ts('Is equal to'),
1792 case CRM_Report_Form
::OP_MONTH
:
1793 case CRM_Report_Form
::OP_MULTISELECT
:
1794 case CRM_Report_Form
::OP_ENTITYREF
:
1797 'in' => ts('Is one of'),
1798 'notin' => ts('Is not one of'),
1799 'nll' => ts('Is empty (Null)'),
1800 'nnll' => ts('Is not empty (Null)'),
1804 case CRM_Report_Form
::OP_DATE
:
1807 'nll' => ts('Is empty (Null)'),
1808 'nnll' => ts('Is not empty (Null)'),
1812 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1813 // use this operator for the values, concatenated with separator. For e.g if
1814 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1816 'mhas' => ts('Is one of'),
1817 'mnot' => ts('Is not one of'),
1824 'has' => ts('Contains'),
1825 'sw' => ts('Starts with'),
1826 'ew' => ts('Ends with'),
1827 'nhas' => ts('Does not contain'),
1828 'eq' => ts('Is equal to'),
1829 'neq' => ts('Is not equal to'),
1830 'nll' => ts('Is empty (Null)'),
1831 'nnll' => ts('Is not empty (Null)'),
1838 * Build the tag filter field to display on the filters tab.
1840 public function buildTagFilter() {
1841 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1842 if (!empty($contactTags)) {
1843 $this->_columns
['civicrm_tag'] = [
1844 'dao' => 'CRM_Core_DAO_Tag',
1848 'title' => ts('Tag'),
1849 'type' => CRM_Utils_Type
::T_INT
,
1851 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1852 'options' => $contactTags,
1860 * Adds group filters to _columns (called from _Construct).
1862 public function buildGroupFilter() {
1863 $this->_columns
['civicrm_group']['filters'] = [
1865 'name' => 'group_id',
1866 'title' => ts('Group'),
1867 'type' => CRM_Utils_Type
::T_INT
,
1868 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1870 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1873 if (empty($this->_columns
['civicrm_group']['dao'])) {
1874 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1876 if (empty($this->_columns
['civicrm_group']['alias'])) {
1877 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1882 * Get SQL operator from form text version.
1884 * @param string $operator
1888 public function getSQLOperator($operator = "like") {
1889 switch ($operator) {
1922 return 'IS NOT NULL';
1931 * Generate where clause.
1933 * This can be overridden in reports for special treatment of a field
1935 * @param array $field Field specifications
1936 * @param string $op Query operator (not an exact match to sql)
1937 * @param mixed $value
1941 * @return null|string
1943 public function whereClause(&$field, $op, $value, $min, $max) {
1945 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1947 // CRM-18010: Ensure type of each report filters
1949 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1956 if (($min !== NULL && strlen($min) > 0) ||
1957 ($max !== NULL && strlen($max) > 0)
1961 $min = CRM_Utils_Type
::escape($min, $type);
1963 $clauses[] = "( {$field['dbAlias']} >= $min )";
1966 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1970 $max = CRM_Utils_Type
::escape($max, $type);
1972 $clauses[] = "( {$field['dbAlias']} <= $max )";
1975 $clauses[] = "( {$field['dbAlias']} > $max )";
1979 if (!empty($clauses)) {
1981 $clause = implode(' AND ', $clauses);
1984 $clause = '(' . implode('OR', $clauses) . ')';
1992 if ($value !== NULL && strlen($value) > 0) {
1993 $value = CRM_Utils_Type
::escape($value, $type);
1994 if (strpos($value, '%') === FALSE) {
1995 $value = "'%{$value}%'";
1998 $value = "'{$value}'";
2000 $sqlOP = $this->getSQLOperator($op);
2001 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2007 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
2008 $value = explode(',', $value);
2010 if ($value !== NULL && is_array($value) && count($value) > 0) {
2011 $sqlOP = $this->getSQLOperator($op);
2012 if (CRM_Utils_Array
::value('type', $field) ==
2013 CRM_Utils_Type
::T_STRING
2015 //cycle through selections and escape values
2016 foreach ($value as $key => $selection) {
2017 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
2020 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
2024 // for numerical values
2025 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
2028 if ($op == 'notin') {
2029 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
2032 $clause = "( " . $clause . " )";
2039 // multiple has or multiple not
2040 if ($value !== NULL && count($value) > 0) {
2041 $value = CRM_Utils_Type
::escapeAll($value, $type);
2042 $operator = $op == 'mnot' ?
'NOT' : '';
2043 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2044 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2050 if ($value !== NULL && strlen($value) > 0) {
2051 $value = CRM_Utils_Type
::escape($value, $type);
2052 if (strpos($value, '%') === FALSE) {
2054 $value = "'{$value}%'";
2057 $value = "'%{$value}'";
2061 $value = "'{$value}'";
2063 $sqlOP = $this->getSQLOperator($op);
2064 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2070 $sqlOP = $this->getSQLOperator($op);
2071 $clause = "( {$field['dbAlias']} $sqlOP )";
2077 //CRM-18457: some custom field passes value in array format against binary operator
2078 if (is_array($value) && count($value)) {
2083 if ($value !== NULL && $value !== '') {
2084 if (isset($field['clause'])) {
2085 // FIXME: we not doing escape here. Better solution is to use two
2086 // different types - data-type and filter-type
2087 $clause = $field['clause'];
2089 elseif (!is_array($value)) {
2090 $value = CRM_Utils_Type
::escape($value, $type);
2091 $sqlOP = $this->getSQLOperator($op);
2092 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
2093 $value = "'{$value}'";
2095 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2101 //dev/core/544 Add report support for multiple contact subTypes
2102 if ($field['name'] == 'contact_sub_type' && $clause) {
2103 $clause = $this->whereSubtypeClause($field, $value, $op);
2105 if (!empty($field['group']) && $clause) {
2106 $clause = $this->whereGroupClause($field, $value, $op);
2108 elseif (!empty($field['tag']) && $clause) {
2109 // not using left join in query because if any contact
2110 // belongs to more than one tag, results duplicate
2112 $clause = $this->whereTagClause($field, $value, $op);
2114 elseif (!empty($field['membership_org']) && $clause) {
2115 $clause = $this->whereMembershipOrgClause($value, $op);
2117 elseif (!empty($field['membership_type']) && $clause) {
2118 $clause = $this->whereMembershipTypeClause($value, $op);
2124 * Get SQL where clause for contact subtypes
2125 * @param string $field
2126 * @param mixed $value
2127 * @param string $op SQL Operator
2131 public function whereSubtypeClause($field, $value, $op) {
2132 // Get the correct SQL operator.
2136 $clauseSeparator = 'AND';
2141 $clauseSeparator = 'OR';
2144 $sqlOp = $this->getSQLOperator($op);
2146 $subtypeFilters = count($value);
2147 if ($sqlOp == 'IS NULL' ||
$sqlOp == 'IS NOT NULL') {
2148 $clause .= "{$field['dbAlias']} $sqlOp";
2151 for ($i = 0; $i < $subtypeFilters; $i++
) {
2152 $clause .= "{$field['dbAlias']} $sqlOp '%$value[$i]%'";
2153 if ($i !== ($subtypeFilters - 1)) {
2154 $clause .= " $clauseSeparator ";
2163 * Get SQL where clause for a date field.
2165 * @param string $fieldName
2166 * @param string $relative
2167 * @param string $from
2169 * @param string $type
2170 * @param string $fromTime
2171 * @param string $toTime
2173 * @return null|string
2175 public function dateClause(
2177 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2180 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2181 $sqlOP = $this->getSQLOperator($relative);
2182 return "( {$fieldName} {$sqlOP} )";
2185 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2188 $clauses[] = "( {$fieldName} >= $from )";
2192 $clauses[] = "( {$fieldName} <= {$to} )";
2195 if (!empty($clauses)) {
2196 return implode(' AND ', $clauses);
2203 * Get values for from and to for date ranges.
2207 * @param bool $relative
2208 * @param string $from
2210 * @param string $fromTime
2211 * @param string $toTime
2215 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2216 if (empty($toTime)) {
2217 // odd legacy behaviour to treat NULL as 'end of the day'
2218 // recommend updating reports to call CRM_Utils_Date::getFromTo
2219 //directly (default on the function is the actual default there).
2222 return CRM_Utils_Date
::getFromTo($relative, $from, $to, $fromTime, $toTime);
2226 * Alter display of rows.
2228 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2229 * such as rendering contacts as links.
2231 * @param array $rows
2232 * Rows generated by SQL, with an array for each row.
2234 public function alterDisplay(&$rows) {
2238 * Alter the way in which custom data fields are displayed.
2240 * @param array $rows
2242 public function alterCustomDataDisplay(&$rows) {
2243 // custom code to alter rows having custom values
2244 if (empty($this->_customGroupExtends
)) {
2249 $customFieldIds = [];
2250 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2251 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2252 $customFieldIds[$fieldAlias] = $fieldId;
2255 if (empty($customFieldIds)) {
2259 // skip for type date and ContactReference since date format is already handled
2261 SELECT cg.table_name, cf.id
2262 FROM civicrm_custom_field cf
2263 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2264 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2265 cg.is_active = 1 AND
2266 cf.is_active = 1 AND
2267 cf.is_searchable = 1 AND
2268 cf.data_type NOT IN ('ContactReference', 'Date') AND
2269 cf.id IN (" . implode(",", $customFieldIds) . ")";
2271 $dao = CRM_Core_DAO
::executeQuery($query);
2272 while ($dao->fetch()) {
2273 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2276 $entryFound = FALSE;
2277 foreach ($rows as $rowNum => $row) {
2278 foreach ($row as $tableCol => $val) {
2279 if (array_key_exists($tableCol, $customFields)) {
2280 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2285 // skip looking further in rows, if first row itself doesn't
2286 // have the column we need
2294 * Remove duplicate rows.
2296 * @param array $rows
2298 public function removeDuplicates(&$rows) {
2299 if (empty($this->_noRepeats
)) {
2304 foreach ($rows as $key => $list) {
2305 foreach ($list as $colName => $colVal) {
2306 if (array_key_exists($colName, $checkList) &&
2307 $checkList[$colName] == $colVal
2309 $rows[$key][$colName] = "";
2311 if (in_array($colName, $this->_noRepeats
)) {
2312 $checkList[$colName] = $colVal;
2319 * Fix subtotal display.
2322 * @param array $fields
2323 * @param bool $subtotal
2325 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2326 foreach ($row as $colName => $colVal) {
2327 if (in_array($colName, $fields)) {
2329 elseif (isset($this->_columnHeaders
[$colName])) {
2331 $row[$colName] = 'Subtotal';
2335 unset($row[$colName]);
2342 * Calculate grant total.
2344 * @param array $rows
2348 public function grandTotal(&$rows) {
2349 if (!$this->_rollup ||
count($rows) == 1) {
2353 $this->moveSummaryColumnsToTheRightHandSide();
2355 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2359 $this->rollupRow
= array_pop($rows);
2361 foreach ($this->_columnHeaders
as $fld => $val) {
2362 if (!in_array($fld, $this->_statFields
)) {
2363 if (!$this->_grandFlag
) {
2364 $this->rollupRow
[$fld] = ts('Grand Total');
2365 $this->_grandFlag
= TRUE;
2368 $this->rollupRow
[$fld] = "";
2373 $this->assign('grandStat', $this->rollupRow
);
2378 * Format display output.
2380 * @param array $rows
2381 * @param bool $pager
2383 public function formatDisplay(&$rows, $pager = TRUE) {
2384 // set pager based on if any limit was applied in the query.
2389 // allow building charts if any
2390 if (!empty($this->_params
['charts']) && !empty($rows)) {
2391 $this->buildChart($rows);
2392 $this->assign('chartEnabled', TRUE);
2393 $this->_chartId
= "{$this->_params['charts']}_" .
2394 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2396 $this->assign('chartId', $this->_chartId
);
2399 // unset columns not to be displayed.
2400 foreach ($this->_columnHeaders
as $key => $value) {
2401 if (!empty($value['no_display'])) {
2402 unset($this->_columnHeaders
[$key]);
2406 // unset columns not to be displayed.
2407 if (!empty($rows)) {
2408 foreach ($this->_noDisplay
as $noDisplayField) {
2409 foreach ($rows as $rowNum => $row) {
2410 unset($this->_columnHeaders
[$noDisplayField]);
2415 // Find alter display functions.
2416 $firstRow = reset($rows);
2418 $selectedFields = array_keys($firstRow);
2419 $alterFunctions = $alterMap = $alterSpecs = [];
2420 foreach ($this->_columns
as $tableName => $table) {
2421 if (array_key_exists('metadata', $table)) {
2422 foreach ($table['metadata'] as $field => $specs) {
2423 if (in_array($tableName . '_' . $field, $selectedFields)) {
2424 if (array_key_exists('alter_display', $specs)) {
2425 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2426 $alterMap[$tableName . '_' . $field] = $field;
2427 $alterSpecs[$tableName . '_' . $field] = NULL;
2429 // Add any alters that can be intuited from the field specs.
2430 // So far only boolean but a lot more could be.
2431 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2432 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2433 $alterMap[$tableName . '_' . $field] = $field;
2434 $alterSpecs[$tableName . '_' . $field] = NULL;
2441 // Run the alter display functions
2442 foreach ($rows as $index => & $row) {
2443 foreach ($row as $selectedField => $value) {
2444 if (array_key_exists($selectedField, $alterFunctions)) {
2445 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2451 // use this method for formatting rows for display purpose.
2452 $this->alterDisplay($rows);
2453 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2455 // build array of section totals
2456 $this->sectionTotals();
2458 // process grand-total row
2459 $this->grandTotal($rows);
2461 // use this method for formatting custom rows for display purpose.
2462 $this->alterCustomDataDisplay($rows);
2468 * @param $selectedfield
2469 * @param $criteriaFieldName
2473 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2474 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2475 $row[$selectedfield . '_link'] = $url;
2476 $row[$selectedfield . '_hover'] = ts("%1 for this state.", [
2480 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2481 if (!is_array($states)) {
2489 * @param $selectedField
2490 * @param $criteriaFieldName
2494 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2495 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2496 $row[$selectedField . '_link'] = $url;
2497 $row[$selectedField . '_hover'] = ts("%1 for this country.", [
2500 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2501 if (!is_array($countries)) {
2509 * @param $selectedfield
2510 * @param $criteriaFieldName
2514 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2515 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2516 $row[$selectedfield . '_link'] = $url;
2517 $row[$selectedfield . '_hover'] = ts("%1 for this county.", [
2520 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2521 if (!is_array($counties)) {
2529 * @param $selectedfield
2530 * @param $criteriaFieldName
2534 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2535 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value);
2545 protected function alterContactID($value, &$row, $fieldname) {
2546 $nameField = substr($fieldname, 0, -2) . 'name';
2547 static $first = TRUE;
2548 static $viewContactList = FALSE;
2550 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2553 if (!$viewContactList) {
2556 if (array_key_exists($nameField, $row)) {
2557 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2560 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2570 protected function alterBoolean($value) {
2571 $options = [0 => '', 1 => ts('Yes')];
2572 if (isset($options[$value])) {
2573 return $options[$value];
2581 * @param array $rows
2583 public function buildChart(&$rows) {
2584 // override this method for building charts.
2587 // select() method below has been added recently (v3.3), and many of the report templates might
2588 // still be having their own select() method. We should fix them as and when encountered and move
2589 // towards generalizing the select() method below.
2592 * Generate the SELECT clause and set class variable $_select.
2594 public function select() {
2595 $select = $this->_selectAliases
= [];
2596 $this->storeGroupByArray();
2598 foreach ($this->_columns
as $tableName => $table) {
2599 if (array_key_exists('fields', $table)) {
2600 foreach ($table['fields'] as $fieldName => $field) {
2601 if ($tableName == 'civicrm_address') {
2602 // deprecated, use $this->isTableSelected.
2603 $this->_addressField
= TRUE;
2605 if ($tableName == 'civicrm_email') {
2606 $this->_emailField
= TRUE;
2608 if ($tableName == 'civicrm_phone') {
2609 $this->_phoneField
= TRUE;
2612 if (!empty($field['required']) ||
2613 !empty($this->_params
['fields'][$fieldName])
2616 // 1. In many cases we want select clause to be built in slightly different way
2617 // for a particular field of a particular type.
2618 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2620 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2621 if ($selectClause) {
2622 $select[] = $selectClause;
2626 // include statistics columns only if set
2627 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2628 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2632 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2633 if ($selectClause) {
2634 $select[] = $selectClause;
2637 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2644 // select for group bys
2645 if (array_key_exists('group_bys', $table)) {
2646 foreach ($table['group_bys'] as $fieldName => $field) {
2648 if ($tableName == 'civicrm_address') {
2649 $this->_addressField
= TRUE;
2651 if ($tableName == 'civicrm_email') {
2652 $this->_emailField
= TRUE;
2654 if ($tableName == 'civicrm_phone') {
2655 $this->_phoneField
= TRUE;
2657 // 1. In many cases we want select clause to be built in slightly different way
2658 // for a particular field of a particular type.
2659 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2661 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2662 if ($selectClause) {
2663 $select[] = $selectClause;
2667 if (!empty($this->_params
['group_bys']) &&
2668 !empty($this->_params
['group_bys'][$fieldName]) &&
2669 !empty($this->_params
['group_bys_freq'])
2671 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2673 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2674 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2675 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2676 $field['title'] = 'Week';
2680 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2681 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2682 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2683 $field['title'] = 'Year';
2687 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2688 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2689 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2690 $field['title'] = 'Month';
2694 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2695 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2696 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2697 $field['title'] = 'Quarter';
2700 // for graphs and charts -
2701 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2702 $this->_interval
= $field['title'];
2703 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2704 = $field['title'] . ' Beginning';
2705 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2706 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2708 // just to make sure these values are transferred to rows.
2709 // since we 'll need them for calculation purpose,
2710 // e.g making subtotals look nicer or graphs
2711 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
2712 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
2719 if (empty($select)) {
2720 // CRM-21412 Do not give fatal error on report when no fields selected
2724 $this->_selectClauses
= $select;
2725 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2729 * Build select clause for a single field.
2731 * @param string $tableName
2732 * @param string $tableKey
2733 * @param string $fieldName
2734 * @param string $field
2738 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2739 if (!empty($field['pseudofield'])) {
2740 $alias = "{$tableName}_{$fieldName}";
2741 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2742 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2743 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = CRM_Utils_Array
::value('dbAlias', $field);
2744 $this->_selectAliases
[] = $alias;
2745 return ' 1 as ' . $alias;
2751 * Build where clause.
2753 public function where() {
2754 $this->storeWhereHavingClauseArray();
2756 if (empty($this->_whereClauses
)) {
2757 $this->_where
= "WHERE ( 1 ) ";
2758 $this->_having
= "";
2761 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2764 if ($this->_aclWhere
) {
2765 $this->_where
.= " AND {$this->_aclWhere} ";
2768 if (!empty($this->_havingClauses
)) {
2769 // use this clause to construct group by clause.
2770 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2775 * Store Where clauses into an array.
2777 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2778 * temp table that may not be part of the final where clause or added
2779 * in other functions
2781 public function storeWhereHavingClauseArray() {
2782 foreach ($this->_columns
as $tableName => $table) {
2783 if (array_key_exists('filters', $table)) {
2784 foreach ($table['filters'] as $fieldName => $field) {
2785 // respect pseudofield to filter spec so fields can be marked as
2786 // not to be handled here
2787 if (!empty($field['pseudofield'])) {
2790 $clause = $this->generateFilterClause($field, $fieldName);
2792 if (!empty($clause)) {
2793 if (!empty($field['having'])) {
2794 $this->_havingClauses
[] = $clause;
2797 $this->_whereClauses
[] = $clause;
2809 public function processReportMode() {
2810 $this->setOutputMode();
2813 = CRM_Utils_Request
::retrieve(
2816 CRM_Core_DAO
::$_nullObject
2819 $this->_absoluteUrl
= FALSE;
2821 $this->assign('printOnly', FALSE);
2823 if ($this->_outputMode
== 'print' ||
2824 ($this->_sendmail
&& !$this->_outputMode
)
2826 $this->assign('printOnly', TRUE);
2828 $this->addPaging
= FALSE;
2829 $this->assign('outputMode', 'print');
2830 $this->_outputMode
= 'print';
2831 if ($this->_sendmail
) {
2832 $this->_absoluteUrl
= TRUE;
2835 elseif ($this->_outputMode
== 'pdf') {
2837 $this->addPaging
= FALSE;
2838 $this->_absoluteUrl
= TRUE;
2840 elseif ($this->_outputMode
== 'csv') {
2842 $this->_absoluteUrl
= TRUE;
2843 $this->addPaging
= FALSE;
2845 elseif ($this->_outputMode
== 'group') {
2846 $this->assign('outputMode', 'group');
2848 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2849 $this->assign('outputMode', 'create_report');
2851 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2852 $this->_createNew
= TRUE;
2855 $this->assign('outputMode', $this->_outputMode
);
2856 $this->assign('printOnly', $printOnly);
2857 // Get today's date to include in printed reports
2859 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2860 $this->assign('reportDate', $reportDate);
2865 * Post Processing function for Form.
2867 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2868 * This function is not accessed when the api calls the report.
2870 public function beginPostProcess() {
2871 $this->setParams($this->controller
->exportValues($this->_name
));
2872 if (empty($this->_params
) &&
2875 $this->setParams($this->_formValues
);
2878 // hack to fix params when submitted from dashboard, CRM-8532
2879 // fields array is missing because form building etc is skipped
2880 // in dashboard mode for report
2881 //@todo - this could be done in the dashboard no we have a setter
2882 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2883 $this->setParams($this->_formValues
);
2886 $this->processReportMode();
2888 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2889 $this->_createNew
= ($this->_outputMode
== 'copy');
2890 CRM_Report_Form_Instance
::postProcess($this);
2892 if ($this->_outputMode
== 'delete') {
2893 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2896 $this->_formValues
= $this->_params
;
2898 $this->beginPostProcessCommon();
2902 * BeginPostProcess function run in both report mode and non-report mode (api).
2904 public function beginPostProcessCommon() {
2908 * Build the report query.
2910 * @param bool $applyLimit
2914 public function buildQuery($applyLimit = TRUE) {
2915 $this->buildGroupTempTable();
2918 $this->customDataFrom();
2919 $this->buildPermissionClause();
2924 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
2925 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
2927 $clause = "{$field['dbAlias']} as {$alias}";
2929 $this->_select
.= ", $clause ";
2932 if ($applyLimit && empty($this->_params
['charts'])) {
2935 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2937 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2938 $this->addToDeveloperTab($sql);
2943 * Build group by clause.
2945 public function groupBy() {
2946 $this->storeGroupByArray();
2948 if (!empty($this->_groupByArray
)) {
2949 if ($this->optimisedForOnlyFullGroupBy
) {
2950 // We should probably deprecate this code path. What happens here is that
2951 // the group by is amended to reflect the select columns. This often breaks the
2952 // results. Retrofitting group strict group by onto existing report classes
2954 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2957 $this->_groupBy
= ' GROUP BY ' . implode($this->_groupByArray
);
2963 * Build order by clause.
2965 public function orderBy() {
2966 $this->_orderBy
= "";
2967 $this->_sections
= [];
2968 $this->storeOrderByArray();
2969 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2970 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2972 $this->assign('sections', $this->_sections
);
2976 * Extract order by fields and store as an array.
2978 * In some cases other functions want to know which fields are selected for ordering by
2979 * Separating this into a separate function allows it to be called separately from constructing
2980 * the order by clause
2982 public function storeOrderByArray() {
2985 if (!empty($this->_params
['order_bys']) &&
2986 is_array($this->_params
['order_bys']) &&
2987 !empty($this->_params
['order_bys'])
2990 // Process order_bys in user-specified order
2991 foreach ($this->_params
['order_bys'] as $orderBy) {
2993 foreach ($this->_columns
as $tableName => $table) {
2994 if (array_key_exists('order_bys', $table)) {
2995 // For DAO columns defined in $this->_columns
2996 $fields = $table['order_bys'];
2998 elseif (array_key_exists('extends', $table)) {
2999 // For custom fields referenced in $this->_customGroupExtends
3000 $fields = CRM_Utils_Array
::value('fields', $table, []);
3005 if (!empty($fields) && is_array($fields)) {
3006 foreach ($fields as $fieldName => $field) {
3007 if ($fieldName == $orderBy['column']) {
3008 $orderByField = array_merge($field, $orderBy);
3009 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
3016 if (!empty($orderByField)) {
3017 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
3018 if ($this->groupConcatTested
) {
3019 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
3022 // Not sure when this is preferable to using tplField (which has
3023 // definitely been tested to work in cases then this does not.
3024 // in caution not switching unless report has been tested for
3025 // group concat functionality.
3026 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
3029 // Record any section headers for assignment to the template
3030 if (!empty($orderBy['section'])) {
3031 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
3032 $this->_sections
[$orderByField['tplField']] = $orderByField;
3038 $this->_orderByArray
= $orderBys;
3040 $this->assign('sections', $this->_sections
);
3044 * Determine unselected columns.
3048 public function unselectedOrderByColumns() {
3049 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
3053 * Determine unselected columns.
3057 public function unselectedSectionColumns() {
3058 if (is_array($this->_sections
)) {
3059 return array_diff_key($this->_sections
, $this->getSelectColumns());
3067 * Build output rows.
3069 * @param string $sql
3070 * @param array $rows
3072 public function buildRows($sql, &$rows) {
3073 if (!$this->optimisedForOnlyFullGroupBy
) {
3074 CRM_Core_DAO
::disableFullGroupByMode();
3076 $dao = CRM_Core_DAO
::executeQuery($sql);
3077 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
3078 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
3080 CRM_Core_DAO
::reenableFullGroupByMode();
3081 if (!is_array($rows)) {
3085 // use this method to modify $this->_columnHeaders
3086 $this->modifyColumnHeaders();
3088 $unselectedSectionColumns = $this->unselectedSectionColumns();
3090 while ($dao->fetch()) {
3092 foreach ($this->_columnHeaders
as $key => $value) {
3093 if (property_exists($dao, $key)) {
3094 $row[$key] = $dao->$key;
3098 // section headers not selected for display need to be added to row
3099 foreach ($unselectedSectionColumns as $key => $values) {
3100 if (property_exists($dao, $key)) {
3101 $row[$key] = $dao->$key;
3110 * Calculate section totals.
3112 * When "order by" fields are marked as sections, this assigns to the template
3113 * an array of total counts for each section. This data is used by the Smarty
3114 * plugin {sectionTotal}.
3116 public function sectionTotals() {
3118 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3119 if (empty($this->_selectAliases
)) {
3123 if (!empty($this->_sections
)) {
3124 // build the query with no LIMIT clause
3125 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3126 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3128 // pull section aliases out of $this->_sections
3129 $sectionAliases = array_keys($this->_sections
);
3132 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3133 $ifnulls[] = "ifnull($alias, '') as $alias";
3135 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3136 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3138 // Group (un-limited) report by all aliases and get counts. This might
3139 // be done more efficiently when the contents of $sql are known, ie. by
3140 // overriding this method in the report class.
3142 $query = $this->_select
.
3143 ", count(*) as ct from ($sql) as subquery group by " .
3144 implode(", ", $sectionAliases);
3146 // initialize array of total counts
3148 $dao = CRM_Core_DAO
::executeQuery($query);
3149 while ($dao->fetch()) {
3151 // let $this->_alterDisplay translate any integer ids to human-readable values.
3152 $rows[0] = $dao->toArray();
3153 $this->alterDisplay($rows);
3156 // add totals for all permutations of section values
3159 $aliasCount = count($sectionAliases);
3160 foreach ($sectionAliases as $alias) {
3161 $values[] = $row[$alias];
3162 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3163 if ($i == $aliasCount) {
3164 // the last alias is the lowest-level section header; use count as-is
3165 $totals[$key] = $dao->ct
;
3168 // other aliases are higher level; roll count into their total
3169 $totals[$key] +
= $dao->ct
;
3173 $this->assign('sectionTotals', $totals);
3178 * Modify column headers.
3180 public function modifyColumnHeaders() {
3181 // use this method to modify $this->_columnHeaders
3185 * Move totals columns to the right edge of the table.
3187 * It seems like a more logical layout to have any totals columns on the far right regardless of
3188 * the location of the rest of their table.
3190 public function moveSummaryColumnsToTheRightHandSide() {
3191 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3192 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3196 * Assign rows to the template.
3198 * @param array $rows
3200 public function doTemplateAssignment(&$rows) {
3201 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
3202 $this->assign_by_ref('rows', $rows);
3203 $this->assign('statistics', $this->statistics($rows));
3207 * Build report statistics.
3209 * Override this method to build your own statistics.
3211 * @param array $rows
3215 public function statistics(&$rows) {
3218 $count = count($rows);
3219 // Why do we increment the count for rollup seems to artificially inflate the count.
3220 // It seems perhaps intentional to include the summary row in the count of results - although
3221 // this just seems odd.
3222 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3226 $this->countStat($statistics, $count);
3228 $this->groupByStat($statistics);
3230 $this->filterStat($statistics);
3236 * Add count statistics.
3238 * @param array $statistics
3241 public function countStat(&$statistics, $count) {
3242 $statistics['counts']['rowCount'] = [
3243 'title' => ts('Row(s) Listed'),
3247 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3248 $statistics['counts']['rowsFound'] = [
3249 'title' => ts('Total Row(s)'),
3250 'value' => $this->_rowsFound
,
3256 * Add group by statistics.
3258 * @param array $statistics
3260 public function groupByStat(&$statistics) {
3261 if (!empty($this->_params
['group_bys']) &&
3262 is_array($this->_params
['group_bys']) &&
3263 !empty($this->_params
['group_bys'])
3265 foreach ($this->_columns
as $tableName => $table) {
3266 if (array_key_exists('group_bys', $table)) {
3267 foreach ($table['group_bys'] as $fieldName => $field) {
3268 if (!empty($this->_params
['group_bys'][$fieldName])) {
3269 $combinations[] = $field['title'];
3274 $statistics['groups'][] = [
3275 'title' => ts('Grouping(s)'),
3276 'value' => implode(' & ', $combinations),
3282 * Filter statistics.
3284 * @param array $statistics
3286 public function filterStat(&$statistics) {
3287 foreach ($this->_columns
as $tableName => $table) {
3288 if (array_key_exists('filters', $table)) {
3289 foreach ($table['filters'] as $fieldName => $field) {
3290 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3291 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3292 CRM_Utils_Array
::value('operatorType', $field) !=
3293 CRM_Report_Form
::OP_MONTH
3297 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3298 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3299 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3300 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3301 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3303 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3304 $from = CRM_Utils_Date
::customFormat($from, NULL, [$from_time_format]);
3306 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3307 $to = CRM_Utils_Date
::customFormat($to, NULL, [$to_time_format]);
3310 $statistics['filters'][] = [
3311 'title' => $field['title'],
3312 'value' => ts("Between %1 and %2", [1 => $from, 2 => $to]),
3315 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3316 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3318 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3319 $statistics['filters'][] = [
3320 'title' => $field['title'],
3321 'value' => $pair[$rel],
3326 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3329 $pair = $this->getOperationPair(
3330 CRM_Utils_Array
::value('operatorType', $field),
3333 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3334 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3335 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3336 if (in_array($op, ['bw', 'nbw']) && ($min ||
$max)) {
3337 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3339 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3340 $this->setEntityRefDefaults($field, $tableName);
3341 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3343 CRM_Utils_Array
::value('api', $field['attributes'], []));
3345 foreach ($result['values'] as $v) {
3346 $values[] = $v['label'];
3348 $value = "{$pair[$op]} " . implode(', ', $values);
3350 elseif ($op == 'nll' ||
$op == 'nnll') {
3351 $value = $pair[$op];
3353 elseif (is_array($val) && (!empty($val))) {
3354 $options = CRM_Utils_Array
::value('options', $field, []);
3355 foreach ($val as $key => $valIds) {
3356 if (isset($options[$valIds])) {
3357 $val[$key] = $options[$valIds];
3360 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3361 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3362 $val = implode(', ', $val);
3363 $value = "{$pair[$op]} " . $val;
3365 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3366 isset($field['options']) &&
3367 is_array($field['options']) && !empty($field['options'])
3369 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3370 CRM_Utils_Array
::value($val, $field['options'], $val);
3373 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3376 if ($value && empty($field['no_display'])) {
3377 $statistics['filters'][] = [
3378 'title' => CRM_Utils_Array
::value('title', $field),
3379 'value' => CRM_Utils_String
::htmlToText($value),
3389 * End post processing.
3391 * @param array|null $rows
3393 public function endPostProcess(&$rows = NULL) {
3394 $this->assign('report_class', get_class($this));
3395 if ($this->_storeResultSet
) {
3396 $this->_resultSet
= $rows;
3399 if ($this->_outputMode
== 'print' ||
3400 $this->_outputMode
== 'pdf' ||
3404 $content = $this->compileContent();
3405 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3409 if ($this->_sendmail
) {
3410 $config = CRM_Core_Config
::singleton();
3413 if ($this->_outputMode
== 'csv') {
3415 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3416 ": {$url}</p>" . '<p>' .
3417 ts('The report is attached as a CSV file.') . '</p>' .
3418 $this->_formValues
['report_footer'];
3420 $csvFullFilename = $config->templateCompileDir
.
3421 CRM_Utils_File
::makeFileName('CiviReport.csv');
3422 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3423 file_put_contents($csvFullFilename, $csvContent);
3425 'fullPath' => $csvFullFilename,
3426 'mime_type' => 'text/csv',
3427 'cleanName' => 'CiviReport.csv',
3430 if ($this->_outputMode
== 'pdf') {
3431 // generate PDF content
3432 $pdfFullFilename = $config->templateCompileDir
.
3433 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3434 file_put_contents($pdfFullFilename,
3435 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3436 TRUE, ['orientation' => 'landscape']
3439 // generate Email Content
3441 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3442 ": {$url}</p>" . '<p>' .
3443 ts('The report is attached as a PDF file.') . '</p>' .
3444 $this->_formValues
['report_footer'];
3447 'fullPath' => $pdfFullFilename,
3448 'mime_type' => 'application/pdf',
3449 'cleanName' => 'CiviReport.pdf',
3453 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3454 $this->_outputMode
, $attachments
3457 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3460 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3464 elseif ($this->_outputMode
== 'print') {
3468 // Nb. Once upon a time we used a package called Open Flash Charts to
3469 // draw charts, and we had a feature whereby a browser could send the
3470 // server a PNG version of the chart, which could then be included in a
3471 // PDF by including <img> tags in the HTML for the conversion below.
3473 // This feature stopped working when browsers stopped supporting Flash,
3474 // and although we have a different client-side charting library in
3475 // place, we decided not to reimplement the (rather convoluted)
3476 // browser-sending-rendered-chart-to-server process.
3478 // If this feature is required in future we should find a better way to
3479 // render charts on the server side, e.g. server-created SVG.
3480 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, ['orientation' => 'landscape']);
3482 CRM_Utils_System
::civiExit();
3484 elseif ($this->_outputMode
== 'csv') {
3485 CRM_Report_Utils_Report
::export2csv($this, $rows);
3487 elseif ($this->_outputMode
== 'group') {
3488 $group = $this->_params
['groups'];
3489 $this->add2group($group);
3494 * Set store result set indicator to TRUE.
3496 * @todo explain what this does
3498 public function storeResultSet() {
3499 $this->_storeResultSet
= TRUE;
3507 public function getResultSet() {
3508 return $this->_resultSet
;
3512 * Get the sql used to generate the report.
3516 public function getReportSql() {
3517 return $this->sqlArray
;
3521 * Use the form name to create the tpl file name.
3525 public function getTemplateFileName() {
3526 $defaultTpl = parent
::getTemplateFileName();
3527 $template = CRM_Core_Smarty
::singleton();
3528 if (!$template->template_exists($defaultTpl)) {
3529 $defaultTpl = 'CRM/Report/Form.tpl';
3535 * Compile the report content.
3537 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3541 public function compileContent() {
3542 $templateFile = $this->getHookedTemplateFileName();
3543 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3544 CRM_Core_Form
::$_template->fetch($templateFile) .
3545 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3549 * Post process function.
3551 public function postProcess() {
3552 // get ready with post process params
3553 $this->beginPostProcess();
3556 $sql = $this->buildQuery();
3558 // build array of result based on column headers. This method also allows
3559 // modifying column headers before using it to build result set i.e $rows.
3561 $this->buildRows($sql, $rows);
3563 // format result set.
3564 $this->formatDisplay($rows);
3566 // assign variables to templates
3567 $this->doTemplateAssignment($rows);
3569 // do print / pdf / instance stuff if needed
3570 $this->endPostProcess($rows);
3576 * @param int $rowCount
3580 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3581 // lets do the pager if in html mode
3582 $this->_limit
= NULL;
3584 // CRM-14115, over-ride row count if rowCount is specified in URL
3585 if ($this->_dashBoardRowCount
) {
3586 $rowCount = $this->_dashBoardRowCount
;
3588 if ($this->addPaging
) {
3589 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3591 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3593 // @todo all http vars should be extracted in the preProcess
3594 // - not randomly in the class
3595 if (!$pageId && !empty($_POST)) {
3596 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3597 $pageId = max((int) $_POST['crmPID_B'], 1);
3599 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3600 $pageId = max((int) $_POST['crmPID'], 1);
3602 unset($_POST['crmPID_B'], $_POST['crmPID']);
3605 $pageId = $pageId ?
$pageId : 1;
3606 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3607 $offset = ($pageId - 1) * $rowCount;
3609 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3610 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3612 $this->_limit
= " LIMIT $offset, $rowCount";
3613 return [$offset, $rowCount];
3615 if ($this->_limitValue
) {
3616 if ($this->_offsetValue
) {
3617 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3620 $this->_limit
= " LIMIT " . $this->_limitValue
;
3628 * @param int $rowCount
3630 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3631 // CRM-14115, over-ride row count if rowCount is specified in URL
3632 if ($this->_dashBoardRowCount
) {
3633 $rowCount = $this->_dashBoardRowCount
;
3636 if ($this->_limit
&& ($this->_limit
!= '')) {
3637 if (!$this->_rowsFound
) {
3638 $sql = "SELECT FOUND_ROWS();";
3639 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3642 'total' => $this->_rowsFound
,
3643 'rowCount' => $rowCount,
3644 'status' => ts('Records') . ' %%StatusMessage%%',
3645 'buttonBottom' => 'PagerBottomButton',
3646 'buttonTop' => 'PagerTopButton',
3648 if (!empty($this->controller
)) {
3649 // This happens when being called from the api Really we want the api to be able to
3650 // pass paging parameters, but at this stage just preventing test crashes.
3651 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3654 $pager = new CRM_Utils_Pager($params);
3655 $this->assign_by_ref('pager', $pager);
3656 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3661 * Build a group filter with contempt for large data sets.
3663 * This function has been retained as it takes time to migrate the reports over
3664 * to the new method which will not crash on large datasets.
3668 * @param string $field
3669 * @param mixed $value
3674 public function legacySlowGroupFilterClause($field, $value, $op) {
3675 $smartGroupQuery = "";
3677 $group = new CRM_Contact_DAO_Group();
3678 $group->is_active
= 1;
3681 while ($group->fetch()) {
3682 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3683 $group->saved_search_id
3685 $smartGroups[] = $group->id
;
3689 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3691 $smartGroupQuery = '';
3692 if (!empty($smartGroups)) {
3693 $smartGroups = implode(',', $smartGroups);
3694 $smartGroupQuery = " UNION DISTINCT
3695 SELECT DISTINCT smartgroup_contact.contact_id
3696 FROM civicrm_group_contact_cache smartgroup_contact
3697 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3700 $sqlOp = $this->getSQLOperator($op);
3701 if (!is_array($value)) {
3704 //include child groups if any
3705 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3707 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3709 $contactAlias = $this->_aliases
['civicrm_contact'];
3710 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3711 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3713 return " {$contactAlias}.id {$sqlOp} (
3714 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3715 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3716 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3717 {$smartGroupQuery} ) ";
3721 * Build where clause for groups.
3723 * @param string $field
3724 * @param mixed $value
3729 public function whereGroupClause($field, $value, $op) {
3730 if ($this->groupFilterNotOptimised
) {
3731 return $this->legacySlowGroupFilterClause($field, $value, $op);
3733 if ($op === 'notin') {
3734 return " group_temp_table.id IS NULL ";
3736 // We will have used an inner join instead.
3741 * Create a table of the contact ids included by the group filter.
3743 * This function is called by both the api (tests) and the UI.
3745 public function buildGroupTempTable() {
3746 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3749 $filteredGroups = (array) $this->_params
['gid_value'];
3751 $groups = civicrm_api3('Group', 'get', [
3753 'id' => ['IN' => $filteredGroups],
3754 'saved_search_id' => ['>' => 0],
3757 $smartGroups = array_keys($groups['values']);
3760 SELECT DISTINCT group_contact.contact_id as id
3761 FROM civicrm_group_contact group_contact
3762 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3763 AND group_contact.status = 'Added' ";
3765 if (!empty($smartGroups)) {
3766 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3767 $smartGroups = implode(',', $smartGroups);
3770 SELECT smartgroup_contact.contact_id as id
3771 FROM civicrm_group_contact_cache smartgroup_contact
3772 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3775 $this->groupTempTable
= $this->createTemporaryTable('rptgrp', $query);
3776 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3780 * Execute query and add it to the developer tab.
3782 * @param string $query
3783 * @param array $params
3785 * @return \CRM_Core_DAO|object
3787 protected function executeReportQuery($query, $params = []) {
3788 $this->addToDeveloperTab($query);
3789 return CRM_Core_DAO
::executeQuery($query, $params);
3793 * Build where clause for tags.
3795 * @param string $field
3796 * @param mixed $value
3801 public function whereTagClause($field, $value, $op) {
3802 // not using left join in query because if any contact
3803 // belongs to more than one tag, results duplicate
3805 $sqlOp = $this->getSQLOperator($op);
3806 if (!is_array($value)) {
3809 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3810 $entity_table = $this->_tagFilterTable
;
3811 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3812 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3813 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3814 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3818 * Generate membership organization clause.
3820 * @param mixed $value
3821 * @param string $op SQL Operator
3825 public function whereMembershipOrgClause($value, $op) {
3826 $sqlOp = $this->getSQLOperator($op);
3827 if (!is_array($value)) {
3831 $tmp_membership_org_sql_list = implode(', ', $value);
3832 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3833 SELECT DISTINCT mem.contact_id
3834 FROM civicrm_membership mem
3835 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3836 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3837 WHERE mt.member_of_contact_id IN (" .
3838 $tmp_membership_org_sql_list . ")
3839 AND mt.is_active = '1'
3840 AND mem_status.is_current_member = '1'
3841 AND mem_status.is_active = '1' ) ";
3845 * Generate Membership Type SQL Clause.
3847 * @param mixed $value
3853 public function whereMembershipTypeClause($value, $op) {
3854 $sqlOp = $this->getSQLOperator($op);
3855 if (!is_array($value)) {
3859 $tmp_membership_sql_list = implode(', ', $value);
3860 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3861 SELECT DISTINCT mem.contact_id
3862 FROM civicrm_membership mem
3863 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3864 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3865 WHERE mem.membership_type_id IN (" .
3866 $tmp_membership_sql_list . ")
3867 AND mt.is_active = '1'
3868 AND mem_status.is_current_member = '1'
3869 AND mem_status.is_active = '1' ) ";
3873 * Buld contact acl clause
3874 * @deprecated in favor of buildPermissionClause
3876 * @param string $tableAlias
3878 public function buildACLClause($tableAlias = 'contact_a') {
3879 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3883 * Build the permision clause for all entities in this report
3885 public function buildPermissionClause() {
3887 foreach ($this->selectedTables() as $tableName) {
3888 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3889 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3890 $tableAlias = $this->_columns
[$tableName]['alias'];
3891 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3892 foreach ($clauses as $field => $clause) {
3893 // Skip contact_id field if redundant
3894 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3895 $ret["$tableName.$field"] = $clause;
3900 // Override output from buildACLClause
3901 $this->_aclFrom
= NULL;
3902 $this->_aclWhere
= implode(' AND ', $ret);
3906 * Add custom data to the columns.
3908 * @param bool $addFields
3909 * @param array $permCustomGroupIds
3911 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = []) {
3912 if (empty($this->_customGroupExtends
)) {
3915 if (!is_array($this->_customGroupExtends
)) {
3916 $this->_customGroupExtends
= [$this->_customGroupExtends
];
3918 $customGroupWhere = '';
3919 if (!empty($permCustomGroupIds)) {
3920 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3924 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3925 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3926 FROM civicrm_custom_group cg
3927 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3928 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3930 cg.is_active = 1 AND
3931 cf.is_active = 1 AND
3932 cf.is_searchable = 1
3933 ORDER BY cg.weight, cf.weight";
3934 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3937 while ($customDAO->fetch()) {
3938 if ($customDAO->table_name
!= $curTable) {
3939 $curTable = $customDAO->table_name
;
3940 $curFields = $curFilters = [];
3943 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3944 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3945 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3946 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3948 foreach (['fields', 'filters', 'group_bys'] as $colKey) {
3949 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3950 $this->_columns
[$curTable][$colKey] = [];
3954 $fieldName = 'custom_' . $customDAO->cf_id
;
3957 // this makes aliasing work in favor
3958 $curFields[$fieldName] = [
3959 'name' => $customDAO->column_name
,
3960 'title' => $customDAO->label
,
3961 'dataType' => $customDAO->data_type
,
3962 'htmlType' => $customDAO->html_type
,
3965 if ($this->_customGroupFilters
) {
3966 // this makes aliasing work in favor
3967 $curFilters[$fieldName] = [
3968 'name' => $customDAO->column_name
,
3969 'title' => $customDAO->label
,
3970 'dataType' => $customDAO->data_type
,
3971 'htmlType' => $customDAO->html_type
,
3975 switch ($customDAO->data_type
) {
3978 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3979 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3980 // CRM-6946, show time part for datetime date fields
3981 if ($customDAO->time_format
) {
3982 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3987 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3988 $curFilters[$fieldName]['options'] = ['' => ts('- select -')] + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
3989 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3993 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3994 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3998 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3999 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
4000 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
4004 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
4005 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
4009 case 'StateProvince':
4011 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4013 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4014 if ((is_array($options) && count($options) != 0) ||
(!is_array($options) && $options !== FALSE)) {
4015 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4016 $curFilters[$fieldName]['options'] = $options;
4020 case 'ContactReference':
4021 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4022 $curFilters[$fieldName]['name'] = 'display_name';
4023 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4025 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4026 $curFields[$fieldName]['name'] = 'display_name';
4027 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4031 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4032 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4036 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
4037 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4038 if ($options !== FALSE) {
4039 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
4040 $curFilters[$fieldName]['options'] = $options;
4044 if (!array_key_exists('type', $curFields[$fieldName])) {
4045 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], []);
4049 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
4051 if ($this->_customGroupFilters
) {
4052 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
4054 if ($this->_customGroupGroupBy
) {
4055 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
4061 * Build custom data from clause.
4063 * @param bool $joinsForFiltersOnly
4064 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
4066 public function customDataFrom($joinsForFiltersOnly = FALSE) {
4067 if (empty($this->_customGroupExtends
)) {
4070 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
4071 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
4072 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
4074 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
4075 while ($customTablesDAO->fetch()) {
4076 $customTables[] = $customTablesDAO->table_name
;
4079 foreach ($this->_columns
as $table => $prop) {
4080 if (in_array($table, $customTables)) {
4081 $extendsTable = $mapper[$prop['extends']];
4082 // Check field is required for rendering the report.
4083 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4086 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
4088 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
4090 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4091 // handle for ContactReference
4092 if (array_key_exists('fields', $prop)) {
4093 foreach ($prop['fields'] as $fieldName => $field) {
4094 if (CRM_Utils_Array
::value('dataType', $field) ==
4097 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4099 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4108 * Check if the field is selected.
4110 * @param string $prop
4114 public function isFieldSelected($prop) {
4119 if (!empty($this->_params
['fields'])) {
4120 foreach (array_keys($prop['fields']) as $fieldAlias) {
4121 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4122 if ($customFieldId) {
4123 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4127 //might be survey response field.
4128 if (!empty($this->_params
['fields']['survey_response']) &&
4129 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4137 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4138 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4139 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4140 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4147 if (!empty($this->_params
['order_bys'])) {
4148 foreach (array_keys($prop['fields']) as $fieldAlias) {
4149 foreach ($this->_params
['order_bys'] as $orderBy) {
4150 if ($fieldAlias == $orderBy['column'] &&
4151 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4158 return $this->isFieldFiltered($prop);
4163 * Check if the field is used as a filter.
4165 * @param string $prop
4169 protected function isFieldFiltered($prop) {
4170 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4171 foreach ($prop['filters'] as $fieldAlias => $val) {
4180 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4181 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4182 ||
($attach != 'relative' &&
4183 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4189 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4190 in_array($this->_params
[$fieldAlias . '_op'], ['nll', 'nnll'])
4201 * Check for empty order_by configurations and remove them.
4203 * Also set template to hide them.
4205 * @param array $formValues
4207 public function preProcessOrderBy(&$formValues) {
4208 // Object to show/hide form elements
4209 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4211 $_showHide->addShow('optionField_1');
4213 // Cycle through order_by options; skip any empty ones, and hide them as well
4216 if (!empty($formValues['order_bys'])) {
4217 foreach ($formValues['order_bys'] as $order_by) {
4218 if ($order_by['column'] && $order_by['column'] != '-') {
4219 $_showHide->addShow('optionField_' . $n);
4220 $orderBys[$n] = $order_by;
4225 for ($i = $n; $i <= 5; $i++
) {
4227 $_showHide->addHide('optionField_' . $i);
4231 // overwrite order_by options with modified values
4232 if (!empty($orderBys)) {
4233 $formValues['order_bys'] = $orderBys;
4236 $formValues['order_bys'] = [1 => ['column' => '-']];
4239 // assign show/hide data to template
4240 $_showHide->addToTemplate();
4244 * Check if table name has columns in SELECT clause.
4246 * @param string $tableName
4247 * Name of table (index of $this->_columns array).
4251 public function isTableSelected($tableName) {
4252 return in_array($tableName, $this->selectedTables());
4256 * Check if table name has columns in WHERE or HAVING clause.
4258 * @param string $tableName
4259 * Name of table (index of $this->_columns array).
4263 public function isTableFiltered($tableName) {
4264 // Cause the array to be generated if not previously done.
4265 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4266 $this->selectedTables();
4268 return in_array($tableName, $this->filteredTables
);
4272 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4274 * If the array is unset it will be built.
4279 public function selectedTables() {
4280 if (!$this->_selectedTables
) {
4281 $orderByColumns = [];
4282 if (array_key_exists('order_bys', $this->_params
) &&
4283 is_array($this->_params
['order_bys'])
4285 foreach ($this->_params
['order_bys'] as $orderBy) {
4286 $orderByColumns[] = $orderBy['column'];
4290 foreach ($this->_columns
as $tableName => $table) {
4291 if (array_key_exists('fields', $table)) {
4292 foreach ($table['fields'] as $fieldName => $field) {
4293 if (!empty($field['required']) ||
4294 !empty($this->_params
['fields'][$fieldName])
4296 $this->_selectedTables
[] = $tableName;
4301 if (array_key_exists('order_bys', $table)) {
4302 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4303 if (in_array($orderByName, $orderByColumns)) {
4304 $this->_selectedTables
[] = $tableName;
4309 if (array_key_exists('filters', $table)) {
4310 foreach ($table['filters'] as $filterName => $filter) {
4311 if ((isset($this->_params
["{$filterName}_value"])
4312 && !CRM_Utils_System
::isNull($this->_params
["{$filterName}_value"]))
4313 ||
!empty($this->_params
["{$filterName}_relative"])
4314 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4316 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4319 $this->_selectedTables
[] = $tableName;
4320 $this->filteredTables
[] = $tableName;
4327 return $this->_selectedTables
;
4331 * Add campaign fields.
4332 * @param string $entityTable
4333 * @param bool $groupBy
4334 * Add GroupBy? Not appropriate for detail report.
4335 * @param bool $orderBy
4336 * Add OrderBy? Not appropriate for detail report.
4337 * @param bool $filters
4340 public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) {
4341 // Check if CiviCampaign is a) enabled and b) has active campaigns
4342 $config = CRM_Core_Config
::singleton();
4343 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents
);
4344 if ($campaignEnabled) {
4345 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE);
4346 // If we have a campaign, build out the relevant elements
4347 if (!empty($getCampaigns['campaigns'])) {
4348 $this->campaigns
= $getCampaigns['campaigns'];
4349 asort($this->campaigns
);
4350 $this->_columns
[$entityTable]['fields']['campaign_id'] = ['title' => ts('Campaign'), 'default' => 'false'];
4352 $this->_columns
[$entityTable]['filters']['campaign_id'] = [
4353 'title' => ts('Campaign'),
4354 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4355 'options' => $this->campaigns
,
4356 'type' => CRM_Utils_Type
::T_INT
,
4361 $this->_columns
[$entityTable]['group_bys']['campaign_id'] = ['title' => ts('Campaign')];
4365 $this->_columns
[$entityTable]['order_bys']['campaign_id'] = ['title' => ts('Campaign')];
4372 * Add address fields.
4374 * @deprecated - use getAddressColumns which is a more accurate description
4375 * and also accepts an array of options rather than a long list
4377 * adding address fields to construct function in reports
4379 * @param bool $groupBy
4380 * Add GroupBy? Not appropriate for detail report.
4381 * @param bool $orderBy
4382 * Add GroupBy? Not appropriate for detail report.
4383 * @param bool $filters
4384 * @param array $defaults
4387 * address fields for construct clause
4389 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = ['country_id' => TRUE]) {
4390 $defaultAddressFields = [
4391 'street_address' => ts('Street Address'),
4392 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4393 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4394 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4395 'street_number' => ts('Street Number'),
4396 'street_name' => ts('Street Name'),
4397 'street_unit' => ts('Street Unit'),
4398 'city' => ts('City'),
4399 'postal_code' => ts('Postal Code'),
4400 'postal_code_suffix' => ts('Postal Code Suffix'),
4401 'country_id' => ts('Country'),
4402 'state_province_id' => ts('State/Province'),
4403 'county_id' => ts('County'),
4406 'civicrm_address' => [
4407 'dao' => 'CRM_Core_DAO_Address',
4410 'title' => ts('Address Name'),
4411 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4415 'grouping' => 'location-fields',
4418 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4419 $addressFields['civicrm_address']['fields'][$fieldName] = [
4420 'title' => $fieldLabel,
4421 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4425 $street_address_filters = $general_address_filters = [];
4427 // Address filter depends on whether street address parsing is enabled.
4429 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4432 if ($addressOptions['street_address_parsing']) {
4433 $street_address_filters = [
4434 'street_number' => [
4435 'title' => ts('Street Number'),
4436 'type' => CRM_Utils_Type
::T_INT
,
4437 'name' => 'street_number',
4440 'title' => ts('Street Name'),
4441 'name' => 'street_name',
4442 'type' => CRM_Utils_Type
::T_STRING
,
4447 $street_address_filters = [
4448 'street_address' => [
4449 'title' => ts('Street Address'),
4450 'type' => CRM_Utils_Type
::T_STRING
,
4451 'name' => 'street_address',
4455 $general_address_filters = [
4457 'title' => ts('Postal Code'),
4458 'type' => CRM_Utils_Type
::T_STRING
,
4459 'name' => 'postal_code',
4462 'title' => ts('City'),
4463 'type' => CRM_Utils_Type
::T_STRING
,
4467 'name' => 'country_id',
4468 'title' => ts('Country'),
4469 'type' => CRM_Utils_Type
::T_INT
,
4470 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4471 'options' => CRM_Core_PseudoConstant
::country(),
4473 'state_province_id' => [
4474 'name' => 'state_province_id',
4475 'title' => ts('State/Province'),
4476 'type' => CRM_Utils_Type
::T_INT
,
4477 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4481 'name' => 'county_id',
4482 'title' => ts('County'),
4483 'type' => CRM_Utils_Type
::T_INT
,
4484 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4489 $addressFields['civicrm_address']['filters'] = array_merge(
4490 $street_address_filters,
4491 $general_address_filters);
4494 $addressFields['civicrm_address']['order_bys'] = [
4495 'street_name' => ['title' => ts('Street Name')],
4496 'street_number' => ['title' => ts('Odd / Even Street Number')],
4497 'street_address' => NULL,
4499 'postal_code' => NULL,
4504 $addressFields['civicrm_address']['group_bys'] = [
4505 'street_address' => NULL,
4507 'postal_code' => NULL,
4508 'state_province_id' => [
4509 'title' => ts('State/Province'),
4512 'title' => ts('Country'),
4515 'title' => ts('County'),
4519 return $addressFields;
4523 * Do AlterDisplay processing on Address Fields.
4524 * If there are multiple address field values then
4525 * on basis of provided separator the code values are translated into respective labels
4528 * @param array $rows
4529 * @param int $rowNum
4530 * @param string $baseUrl
4531 * @param string $linkText
4532 * @param string $separator
4536 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4537 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4538 $entryFound = FALSE;
4540 'civicrm_address_country_id' => 'country',
4541 'civicrm_address_county_id' => 'county',
4542 'civicrm_address_state_province_id' => 'stateProvince',
4544 foreach ($columnMap as $fieldName => $fnName) {
4545 if (array_key_exists($fieldName, $row)) {
4546 if ($values = $row[$fieldName]) {
4547 $values = (array) explode($separator, $values);
4548 $rows[$rowNum][$fieldName] = [];
4549 $addressField = $fnName == 'stateProvince' ?
'state' : $fnName;
4550 foreach ($values as $value) {
4551 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant
::$fnName($value);
4553 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4555 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4556 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4557 $criteriaQueryParams,
4558 str_replace('civicrm_address_', '', $fieldName),
4559 str_replace('civicrm_address_', '', $fieldName),
4560 implode(',', $values)
4561 ), $this->_absoluteUrl
, $this->_id
4563 $rows[$rowNum]["{$fieldName}_link"] = $url;
4564 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", [1 => $linkText, 2 => $addressField]);
4575 * Do AlterDisplay processing on Address Fields.
4578 * @param array $rows
4579 * @param int $rowNum
4580 * @param string $baseUrl
4581 * @param string $linkText
4585 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4586 $entryFound = FALSE;
4587 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4588 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4589 $addLinks = ['gender_id' => 'Gender'];
4590 foreach (['prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language'] as $fieldName) {
4591 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4592 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4593 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4595 foreach ($rowValues as $rowValue) {
4597 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4600 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4601 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4602 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4609 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4611 foreach ($yesNoFields as $fieldName) {
4612 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4613 // Since these are essentially 'negative fields' it feels like it
4614 // makes sense to only highlight the exceptions hence no 'No'.
4615 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4620 // Handle employer id
4621 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4622 $employerId = $row['civicrm_contact_employer_id'];
4624 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact
::displayName($employerId);
4625 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
4626 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4635 * Adjusts dates passed in to YEAR() for fiscal year.
4637 * @param string $fieldName
4641 public function fiscalYearOffset($fieldName) {
4642 $config = CRM_Core_Config
::singleton();
4643 $fy = $config->fiscalYearStart
;
4644 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4645 ($fy['d'] == 1 && $fy['M'] == 1)
4647 return "YEAR( $fieldName )";
4649 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4650 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4654 * Add Address into From Table if required.
4656 * @deprecated use joinAddressFromContact
4657 * (left here in case extensions use it).
4659 public function addAddressFromClause() {
4660 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinAddressFromContact');
4661 // include address field if address column is to be included
4662 if ((isset($this->_addressField
) &&
4663 $this->_addressField
4665 $this->isTableSelected('civicrm_address')
4668 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4669 ON ({$this->_aliases['civicrm_contact']}.id =
4670 {$this->_aliases['civicrm_address']}.contact_id) AND
4671 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4676 * Add Phone into From Table if required.
4678 * @deprecated use joinPhoneFromContact
4679 * (left here in case extensions use it).
4681 public function addPhoneFromClause() {
4682 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinPhoneFromContact');
4683 // include address field if address column is to be included
4684 if ($this->isTableSelected('civicrm_phone')) {
4686 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4687 ON ({$this->_aliases['civicrm_contact']}.id =
4688 {$this->_aliases['civicrm_phone']}.contact_id) AND
4689 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4694 * Add Address into From Table if required.
4696 * Prefix will be added to both tables as
4697 * it is assumed you are using it to get address of a secondary contact.
4699 * @param string $prefix
4700 * @param array $extra Additional options.
4701 * Not currently used in core but may be used in override extensions.
4703 protected function joinAddressFromContact($prefix = '', $extra = []) {
4704 $defaults = ['primary_only' => TRUE];
4705 $params = array_merge($defaults, $extra);
4706 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4707 $isJoinRequired = $this->_addressField
;
4708 foreach ($addressTables as $addressTable) {
4709 if ($this->isTableSelected($prefix . $addressTable)) {
4710 $isJoinRequired = TRUE;
4713 if ($isJoinRequired) {
4715 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4716 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4717 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id)";
4718 if ($params['primary_only']) {
4720 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4722 $this->_from
.= $fromJoin;
4727 * Add Country into From Table if required.
4729 * Prefix will be added to both tables as
4730 * it is assumed you are using it to get address of a secondary contact.
4732 * @param string $prefix
4733 * @param array $extra Additional options.
4734 * Not currently used in core but may be used in override extensions.
4736 protected function joinCountryFromAddress($prefix = '', $extra = []) {
4737 $defaults = ['primary_only' => TRUE];
4738 $params = array_merge($defaults, $extra);
4739 // include country field if country column is to be included
4740 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4741 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4742 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4745 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4746 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id";
4747 if ($params['primary_only']) {
4749 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4751 $this->_from
.= $fromJoin;
4756 * Add Phone into From Table if required.
4758 * Prefix will be added to both tables as
4759 * it is assumed you are using it to get address of a secondary contact.
4761 * @param string $prefix
4762 * @param array $extra Additional options.
4763 * Not currently used in core but may be used in override extensions.
4765 protected function joinPhoneFromContact($prefix = '', $extra = []) {
4766 $defaults = ['primary_only' => TRUE];
4767 $params = array_merge($defaults, $extra);
4768 // include phone field if phone column is to be included
4769 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4771 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4772 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id";
4773 if ($params['primary_only']) {
4775 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4777 $this->_from
.= $fromJoin;
4782 * Add Email into From Table if required.
4784 * Prefix will be added to both tables as
4785 * it is assumed you are using it to get address of a secondary contact.
4787 * @param string $prefix
4788 * @param array $extra Additional options.
4789 * Not currently used in core but may be used in override extensions.
4791 protected function joinEmailFromContact($prefix = '', $extra = []) {
4792 $defaults = ['primary_only' => TRUE];
4793 $params = array_merge($defaults, $extra);
4794 // include email field if email column is to be included
4795 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4797 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4798 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id";
4799 if ($params['primary_only']) {
4801 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1 ";
4803 $this->_from
.= $fromJoin;
4808 * Add Financial Transaction into From Table if required.
4810 public function addFinancialTrxnFromClause() {
4811 if ($this->isTableSelected('civicrm_financial_trxn')) {
4813 LEFT JOIN civicrm_entity_financial_trxn eftcc
4814 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4815 eftcc.entity_table = 'civicrm_contribution')
4816 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4817 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4822 * Get phone columns to add to array.
4824 * @param array $options
4825 * - prefix Prefix to add to table (in case of more than one instance of the table)
4826 * - prefix_label Label to give columns from this phone table instance
4829 * phone columns definition
4831 public function getPhoneColumns($options = []) {
4834 'prefix_label' => '',
4837 $options = array_merge($defaultOptions, $options);
4840 $options['prefix'] . 'civicrm_phone' => [
4841 'dao' => 'CRM_Core_DAO_Phone',
4843 $options['prefix'] . 'phone' => [
4844 'title' => $options['prefix_label'] . ts('Phone'),
4854 * Get a standard set of contact fields.
4855 * @deprecated - use getColumns('Contact') instead
4858 public function getBasicContactFields() {
4861 'title' => ts('Contact Name'),
4866 'no_display' => TRUE,
4870 'title' => ts('Contact Prefix'),
4873 'title' => ts('First Name'),
4876 'title' => ts('Nick Name'),
4879 'title' => ts('Middle Name'),
4882 'title' => ts('Last Name'),
4885 'title' => ts('Contact Suffix'),
4887 'postal_greeting_display' => ['title' => ts('Postal Greeting')],
4888 'email_greeting_display' => ['title' => ts('Email Greeting')],
4889 'addressee_display' => ['title' => ts('Addressee')],
4891 'title' => ts('Contact Type'),
4893 'contact_sub_type' => [
4894 'title' => ts('Contact Subtype'),
4897 'title' => ts('Gender'),
4900 'title' => ts('Birth Date'),
4903 'title' => ts('Age'),
4904 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4907 'title' => ts('Contact Job title'),
4909 'organization_name' => [
4910 'title' => ts('Organization Name'),
4912 'external_identifier' => [
4913 'title' => ts('Contact identifier from external system'),
4915 'do_not_email' => [],
4916 'do_not_phone' => [],
4917 'do_not_mail' => [],
4920 'is_deceased' => [],
4921 'preferred_language' => [],
4923 'title' => ts('Current Employer'),
4929 * Get a standard set of contact filters.
4931 * @param array $defaults
4935 public function getBasicContactFilters($defaults = []) {
4938 'title' => ts('Contact Name'),
4941 'title' => ts('Contact Source'),
4942 'type' => CRM_Utils_Type
::T_STRING
,
4945 'title' => ts('Contact ID'),
4946 'no_display' => TRUE,
4949 'title' => ts('Gender'),
4950 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4951 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4954 'title' => ts('Birth Date'),
4955 'operatorType' => CRM_Report_Form
::OP_DATE
,
4958 'title' => ts('Contact Type'),
4960 'contact_sub_type' => [
4961 'title' => ts('Contact Subtype'),
4963 'modified_date' => [
4964 'title' => ts('Contact Modified'),
4965 'operatorType' => CRM_Report_Form
::OP_DATE
,
4966 'type' => CRM_Utils_Type
::T_DATE
,
4969 'title' => ts('Deceased'),
4970 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4971 'default' => CRM_Utils_Array
::value('deceased', $defaults, 0),
4974 'title' => ts('Do not email'),
4975 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4978 'title' => ts('Do not phone'),
4979 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4982 'title' => ts('Do not mail'),
4983 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4986 'title' => ts('Do not SMS'),
4987 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4990 'title' => ts('Do not bulk email'),
4991 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4993 'preferred_language' => [
4994 'title' => ts('Preferred Language'),
4997 'no_display' => TRUE,
4999 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5005 * Add contact to group.
5007 * @param int $groupID
5009 public function add2group($groupID) {
5010 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
5011 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
5012 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
5013 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
5014 $sql = str_replace('WITH ROLLUP', '', $sql);
5015 $dao = CRM_Core_DAO
::executeQuery($sql);
5018 // Add resulting contacts to group
5019 while ($dao->fetch()) {
5020 if ($dao->addtogroup_contact_id
) {
5021 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
5025 if (!empty($contact_ids)) {
5026 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
5027 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
5030 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
5036 * Apply common settings to entityRef fields.
5038 * @param array $field
5039 * @param string $table
5041 public function setEntityRefDefaults(&$field, $table) {
5042 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : [];
5043 $field['attributes'] +
= [
5044 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
5046 'placeholder' => ts('- select -'),
5051 * Add link fields to the row.
5053 * Function adds the _link & _hover fields to the row.
5056 * @param string $baseUrl
5057 * @param string $linkText
5058 * @param string $value
5059 * @param string $fieldName
5060 * @param string $tablePrefix
5061 * @param string $fieldLabel
5065 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
5066 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
5067 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
5068 "reset=1&force=1&{$criteriaQueryParams}&" .
5069 $fieldName . "_op=in&{$fieldName}_value={$value}",
5070 $this->_absoluteUrl
, $this->_id
5072 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
5073 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
5074 [1 => $linkText, 2 => $fieldLabel]
5079 * Get label for show results buttons.
5083 public function getResultsLabel() {
5084 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
5085 return $showResultsLabel;
5089 * Determine the output mode from the url or input.
5092 * - pdf : Render as pdf
5093 * - csv : Render as csv
5094 * - print : Render in print format
5095 * - save : save the report and display the new report
5096 * - copy : save the report as a new instance and display that.
5097 * - group : go to the add to group screen.
5099 * Potentially chart variations could also be included but the complexity
5100 * is that we might print a bar chart as a pdf.
5102 protected function setOutputMode() {
5103 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
5106 CRM_Core_DAO
::$_nullObject,
5108 CRM_Utils_Array
::value('task', $this->_params
)
5110 // if contacts are added to group
5111 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
5112 $this->_outputMode
= 'group';
5114 if (isset($this->_params
['task'])) {
5115 unset($this->_params
['task']);
5120 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5123 * @param $columnName
5125 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5126 // add new column with date value for the datetime field
5127 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5128 CRM_Core_DAO
::executeQuery($tempQuery);
5129 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5130 CRM_Core_DAO
::executeQuery($updateQuery);
5131 $this->_selectClauses
[] = "{$columnName}_date";
5132 $this->_select
.= ", {$columnName}_date";
5133 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5134 unset($this->_sections
["{$columnName}"]);
5135 $this->assign('sections', $this->_sections
);
5139 * Get an array of the columns that have been selected for display.
5143 public function getSelectColumns() {
5144 $selectColumns = [];
5145 foreach ($this->_columns
as $tableName => $table) {
5146 if (array_key_exists('fields', $table)) {
5147 foreach ($table['fields'] as $fieldName => $field) {
5148 if (!empty($field['required']) ||
5149 !empty($this->_params
['fields'][$fieldName])
5152 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5157 return $selectColumns;
5161 * Add location tables to the query if they are used for filtering.
5163 * This is for when we are running the query separately for filtering and retrieving display fields.
5165 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5166 if ($this->isTableFiltered('civicrm_email')) {
5168 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5169 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5170 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5172 if ($this->isTableFiltered('civicrm_phone')) {
5174 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5175 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5176 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5178 if ($this->isTableFiltered('civicrm_address')) {
5180 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5181 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5182 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5187 * Set the base table for the FROM clause.
5189 * Sets up the from clause, allowing for the possibility it might be a
5190 * temp table pre-filtered by groups if a group filter is in use.
5192 * @param string $baseTable
5193 * @param string $field
5194 * @param null $tableAlias
5196 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5198 $tableAlias = $this->_aliases
[$baseTable];
5200 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5201 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5202 $this->_from
.= " {$this->_aclFrom} ";
5206 * Join the temp table contacting contacts who are members of the filtered groups.
5208 * If we are using an IN filter we use an inner join, otherwise a left join.
5210 * @param string $baseTable
5211 * @param string $field
5212 * @param string $tableAlias
5214 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5215 if ($this->groupTempTable
) {
5216 if ($this->_params
['gid_op'] == 'in') {
5217 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5218 ON group_temp_table.id = $tableAlias.{$field} ";
5222 LEFT JOIN $this->groupTempTable group_temp_table
5223 ON $tableAlias.{$field} = group_temp_table.id ";
5229 * Get all labels for fields that are used in a group concat.
5231 * @param string $options
5232 * comma separated option values.
5233 * @param string $baoName
5234 * The BAO name for the field.
5235 * @param string $fieldName
5236 * The name of the field for which labels should be retrieved.
5240 public function getLabels($options, $baoName, $fieldName) {
5241 $types = explode(',', $options);
5243 foreach ($types as $value) {
5244 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5246 return implode(', ', array_filter($labels));
5250 * Add statistics columns.
5252 * If a group by is in play then add columns for the statistics fields.
5254 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5255 * column header field.
5257 * @param array $field
5258 * @param string $tableName
5259 * @param string $fieldName
5260 * @param array $select
5264 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5265 foreach ($field['statistics'] as $stat => $label) {
5266 $alias = "{$tableName}_{$fieldName}_{$stat}";
5267 switch (strtolower($stat)) {
5270 $select[] = "$stat({$field['dbAlias']}) as $alias";
5271 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5272 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5273 $this->_statFields
[$label] = $alias;
5274 $this->_selectAliases
[] = $alias;
5278 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5279 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5280 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5281 $this->_statFields
[$label] = $alias;
5282 $this->_selectAliases
[] = $alias;
5285 case 'count_distinct':
5286 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5287 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5288 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5289 $this->_statFields
[$label] = $alias;
5290 $this->_selectAliases
[] = $alias;
5294 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5295 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5296 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5297 $this->_statFields
[$label] = $alias;
5298 $this->_selectAliases
[] = $alias;
5306 * Add a basic field to the select clause.
5308 * @param string $tableName
5309 * @param string $fieldName
5310 * @param array $field
5311 * @param string $select
5314 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5315 $alias = "{$tableName}_{$fieldName}";
5316 $select[] = "{$field['dbAlias']} as $alias";
5317 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
5318 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
5319 $this->_selectAliases
[] = $alias;
5326 * @param array $table
5327 * @param string $tableName
5332 protected function setTableAlias($table, $tableName) {
5333 if (!isset($table['alias'])) {
5334 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5338 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5341 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5342 return $this->_aliases
[$tableName];
5346 * Function to add columns to reports.
5348 * This is ported from extended reports, which also adds join filters to the options.
5350 * @param string $type
5351 * @param array $options
5352 * - prefix - A string to prepend to the table name
5353 * - prefix_label A string to prepend to the fields
5354 * - fields (bool) - should the fields for this table be made available
5355 * - group_by (bool) - should the group bys for this table be made available.
5356 * - order_by (bool) - should the group bys for this table be made available.
5357 * - filters (bool) - should the filters for this table by made available.
5358 * - fields_defaults (array) array of fields that should be displayed by default.
5359 * - filters_defaults (array) array of fields that should be filtered by default.
5360 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5361 * - join_fields (array) fields available from join (requires additional custom code).
5362 * - group_by_defaults (array) array of group bys that should be applied by default.
5363 * - order_by_defaults (array) array of order bys that should be applied by default.
5364 * - custom_fields (array) array of entity types for custom fields (not usually required).
5365 * - contact_type (string) optional restriction on contact type for some tables.
5366 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5370 protected function getColumns($type, $options = []) {
5373 'prefix_label' => '',
5375 'group_bys' => FALSE,
5376 'order_bys' => TRUE,
5378 'join_filters' => FALSE,
5379 'fields_defaults' => [],
5380 'filters_defaults' => [],
5381 'group_bys_defaults' => [],
5382 'order_bys_defaults' => [],
5384 $options = array_merge($defaultOptions, $options);
5386 $fn = 'get' . $type . 'Columns';
5387 return $this->$fn($options);
5391 * Get columns for contact table.
5393 * @param array $options
5397 protected function getContactColumns($options = []) {
5399 'custom_fields' => ['Individual', 'Contact', 'Organization'],
5400 'fields_defaults' => ['display_name', 'id'],
5401 'order_bys_defaults' => ['sort_name ASC'],
5402 'contact_type' => NULL,
5405 $options = array_merge($defaultOptions, $options);
5407 $tableAlias = $options['prefix'] . 'contact';
5410 $options['prefix'] . 'display_name' => [
5411 'name' => 'display_name',
5412 'title' => $options['prefix_label'] . ts('Contact Name'),
5413 'is_fields' => TRUE,
5415 $options['prefix'] . 'sort_name' => [
5416 'name' => 'sort_name',
5417 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5418 'is_fields' => TRUE,
5419 'is_filters' => TRUE,
5420 'is_order_bys' => TRUE,
5422 $options['prefix'] . 'id' => [
5424 'title' => $options['prefix_label'] . ts('Contact ID'),
5425 'alter_display' => 'alterContactID',
5426 'type' => CRM_Utils_Type
::T_INT
,
5427 'is_order_bys' => TRUE,
5428 'is_group_bys' => TRUE,
5429 'is_fields' => TRUE,
5430 'is_filters' => TRUE,
5432 $options['prefix'] . 'external_identifier' => [
5433 'name' => 'external_identifier',
5434 'title' => $options['prefix_label'] . ts('External ID'),
5435 'type' => CRM_Utils_Type
::T_INT
,
5436 'is_fields' => TRUE,
5438 $options['prefix'] . 'contact_type' => [
5439 'title' => $options['prefix_label'] . ts('Contact Type'),
5440 'name' => 'contact_type',
5441 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5442 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5443 'is_fields' => TRUE,
5444 'is_filters' => TRUE,
5445 'is_group_bys' => TRUE,
5447 $options['prefix'] . 'contact_sub_type' => [
5448 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5449 'name' => 'contact_sub_type',
5450 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5451 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5452 'is_fields' => TRUE,
5453 'is_filters' => TRUE,
5454 'is_group_bys' => TRUE,
5456 $options['prefix'] . 'is_deleted' => [
5457 'title' => $options['prefix_label'] . ts('Is deleted'),
5458 'name' => 'is_deleted',
5459 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5460 'is_fields' => FALSE,
5461 'is_filters' => TRUE,
5462 'is_group_bys' => FALSE,
5464 $options['prefix'] . 'external_identifier' => [
5465 'title' => $options['prefix_label'] . ts('Contact identifier from external system'),
5466 'name' => 'external_identifier',
5467 'is_fields' => TRUE,
5468 'is_filters' => FALSE,
5469 'is_group_bys' => FALSE,
5470 'is_order_bys' => TRUE,
5472 $options['prefix'] . 'preferred_language' => [
5473 'title' => $options['prefix_label'] . ts('Preferred Language'),
5474 'name' => 'preferred_language',
5475 'is_fields' => TRUE,
5476 'is_filters' => TRUE,
5477 'is_group_bys' => TRUE,
5478 'is_order_bys' => TRUE,
5482 'postal_greeting_display' => 'Postal Greeting',
5483 'email_greeting_display' => 'Email Greeting',
5484 'addressee_display' => 'Addressee',
5485 ] as $field => $title) {
5486 $spec[$options['prefix'] . $field] = [
5487 'title' => $options['prefix_label'] . ts($title),
5489 'is_fields' => TRUE,
5490 'is_filters' => FALSE,
5491 'is_group_bys' => FALSE,
5494 foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'is_opt_out'] as $field) {
5495 $spec[$options['prefix'] . $field] = [
5497 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5498 'is_fields' => TRUE,
5499 'is_filters' => TRUE,
5500 'is_group_bys' => FALSE,
5503 $individualFields = [
5504 $options['prefix'] . 'first_name' => [
5505 'name' => 'first_name',
5506 'title' => $options['prefix_label'] . ts('First Name'),
5507 'is_fields' => TRUE,
5508 'is_filters' => TRUE,
5509 'is_order_bys' => TRUE,
5511 $options['prefix'] . 'middle_name' => [
5512 'name' => 'middle_name',
5513 'title' => $options['prefix_label'] . ts('Middle Name'),
5514 'is_fields' => TRUE,
5516 $options['prefix'] . 'last_name' => [
5517 'name' => 'last_name',
5518 'title' => $options['prefix_label'] . ts('Last Name'),
5519 'default_order' => 'ASC',
5520 'is_fields' => TRUE,
5522 $options['prefix'] . 'nick_name' => [
5523 'name' => 'nick_name',
5524 'title' => $options['prefix_label'] . ts('Nick Name'),
5525 'is_fields' => TRUE,
5527 $options['prefix'] . 'prefix_id' => [
5528 'name' => 'prefix_id',
5529 'title' => $options['prefix_label'] . ts('Prefix'),
5530 'options' => CRM_Contact_BAO_Contact
::buildOptions('prefix_id'),
5531 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5532 'is_fields' => TRUE,
5533 'is_filters' => TRUE,
5535 $options['prefix'] . 'suffix_id' => [
5536 'name' => 'suffix_id',
5537 'title' => $options['prefix_label'] . ts('Suffix'),
5538 'options' => CRM_Contact_BAO_Contact
::buildOptions('suffix_id'),
5539 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5540 'is_fields' => TRUE,
5541 'is_filters' => TRUE,
5543 $options['prefix'] . 'gender_id' => [
5544 'name' => 'gender_id',
5545 'title' => $options['prefix_label'] . ts('Gender'),
5546 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5547 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5548 'is_fields' => TRUE,
5549 'is_filters' => TRUE,
5552 'title' => $options['prefix_label'] . ts('Birth Date'),
5553 'operatorType' => CRM_Report_Form
::OP_DATE
,
5554 'type' => CRM_Utils_Type
::T_DATE
,
5555 'is_fields' => TRUE,
5556 'is_filters' => TRUE,
5559 'title' => $options['prefix_label'] . ts('Age'),
5560 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5561 'type' => CRM_Utils_Type
::T_INT
,
5562 'is_fields' => TRUE,
5564 $options['prefix'] . 'is_deceased' => [
5565 'title' => $options['prefix_label'] . ts('Is deceased'),
5566 'name' => 'is_deceased',
5567 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5568 'is_fields' => FALSE,
5569 'is_filters' => TRUE,
5570 'is_group_bys' => FALSE,
5572 $options['prefix'] . 'job_title' => [
5573 'name' => 'job_title',
5574 'is_fields' => TRUE,
5575 'is_filters' => FALSE,
5576 'is_group_bys' => FALSE,
5578 $options['prefix'] . 'employer_id' => [
5579 'title' => $options['prefix_label'] . ts('Current Employer'),
5580 'type' => CRM_Utils_Type
::T_INT
,
5581 'name' => 'employer_id',
5582 'is_fields' => TRUE,
5583 'is_filters' => FALSE,
5584 'is_group_bys' => TRUE,
5587 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5588 $spec = array_merge($spec, $individualFields);
5591 if (!empty($options['custom_fields'])) {
5592 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = [
5593 'extends' => $options['custom_fields'],
5594 'title' => $options['prefix_label'],
5595 'filters' => $options['filters'],
5596 'prefix' => $options['prefix'],
5597 'prefix_label' => $options['prefix_label'],
5601 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5605 * Get address columns to add to array.
5607 * @param array $options
5608 * - prefix Prefix to add to table (in case of more than one instance of the table)
5609 * - prefix_label Label to give columns from this address table instance
5610 * - group_bys enable these fields for group by - default false
5611 * - order_bys enable these fields for order by
5612 * - filters enable these fields for filtering
5614 * @return array address columns definition
5616 protected function getAddressColumns($options = []) {
5619 'prefix_label' => '',
5621 'group_bys' => FALSE,
5622 'order_bys' => TRUE,
5624 'join_filters' => FALSE,
5625 'fields_defaults' => [],
5626 'filters_defaults' => [],
5627 'group_bys_defaults' => [],
5628 'order_bys_defaults' => [],
5631 $options = array_merge($defaultOptions, $options);
5632 $defaults = $this->getDefaultsFromOptions($options);
5633 $tableAlias = $options['prefix'] . 'address';
5636 $options['prefix'] . 'name' => [
5637 'title' => $options['prefix_label'] . ts('Address Name'),
5639 'is_fields' => TRUE,
5641 $options['prefix'] . 'street_number' => [
5642 'name' => 'street_number',
5643 'title' => $options['prefix_label'] . ts('Street Number'),
5645 'is_fields' => TRUE,
5647 $options['prefix'] . 'odd_street_number' => [
5648 'title' => ts('Odd / Even Street Number'),
5649 'name' => 'odd_street_number',
5650 'type' => CRM_Utils_Type
::T_INT
,
5651 'no_display' => TRUE,
5653 'dbAlias' => "({$tableAlias}_civireport.street_number % 2)",
5654 'is_fields' => TRUE,
5655 'is_order_bys' => TRUE,
5657 $options['prefix'] . 'street_name' => [
5658 'name' => 'street_name',
5659 'title' => $options['prefix_label'] . ts('Street Name'),
5661 'is_fields' => TRUE,
5662 'is_filters' => TRUE,
5663 'operator' => 'like',
5664 'is_order_bys' => TRUE,
5666 $options['prefix'] . 'street_address' => [
5667 'title' => $options['prefix_label'] . ts('Street Address'),
5668 'name' => 'street_address',
5669 'is_fields' => TRUE,
5670 'is_filters' => TRUE,
5671 'is_group_bys' => TRUE,
5673 $options['prefix'] . 'supplemental_address_1' => [
5674 'title' => $options['prefix_label'] . ts('Supplementary Address Field 1'),
5675 'name' => 'supplemental_address_1',
5676 'is_fields' => TRUE,
5678 $options['prefix'] . 'supplemental_address_2' => [
5679 'title' => $options['prefix_label'] . ts('Supplementary Address Field 2'),
5680 'name' => 'supplemental_address_2',
5681 'is_fields' => TRUE,
5683 $options['prefix'] . 'supplemental_address_3' => [
5684 'title' => $options['prefix_label'] . ts('Supplementary Address Field 3'),
5685 'name' => 'supplemental_address_3',
5686 'is_fields' => TRUE,
5688 $options['prefix'] . 'street_number' => [
5689 'name' => 'street_number',
5690 'title' => $options['prefix_label'] . ts('Street Number'),
5692 'is_order_bys' => TRUE,
5693 'is_filters' => TRUE,
5694 'is_fields' => TRUE,
5696 $options['prefix'] . 'street_unit' => [
5697 'name' => 'street_unit',
5698 'title' => $options['prefix_label'] . ts('Street Unit'),
5700 'is_fields' => TRUE,
5702 $options['prefix'] . 'city' => [
5703 'title' => $options['prefix_label'] . ts('City'),
5705 'operator' => 'like',
5706 'is_fields' => TRUE,
5707 'is_filters' => TRUE,
5708 'is_group_bys' => TRUE,
5709 'is_order_bys' => TRUE,
5711 $options['prefix'] . 'postal_code' => [
5712 'title' => $options['prefix_label'] . ts('Postal Code'),
5713 'name' => 'postal_code',
5715 'is_fields' => TRUE,
5716 'is_filters' => TRUE,
5717 'is_group_bys' => TRUE,
5718 'is_order_bys' => TRUE,
5720 $options['prefix'] . 'postal_code_suffix' => [
5721 'title' => $options['prefix_label'] . ts('Postal Code Suffix'),
5722 'name' => 'postal_code_suffix',
5724 'is_fields' => TRUE,
5725 'is_filters' => TRUE,
5726 'is_group_bys' => TRUE,
5727 'is_order_bys' => TRUE,
5729 $options['prefix'] . 'county_id' => [
5730 'title' => $options['prefix_label'] . ts('County'),
5731 'alter_display' => 'alterCountyID',
5732 'name' => 'county_id',
5733 'type' => CRM_Utils_Type
::T_INT
,
5734 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5735 'options' => CRM_Core_PseudoConstant
::county(),
5736 'is_fields' => TRUE,
5737 'is_filters' => TRUE,
5738 'is_group_bys' => TRUE,
5740 $options['prefix'] . 'state_province_id' => [
5741 'title' => $options['prefix_label'] . ts('State/Province'),
5742 'alter_display' => 'alterStateProvinceID',
5743 'name' => 'state_province_id',
5744 'type' => CRM_Utils_Type
::T_INT
,
5745 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5746 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5747 'is_fields' => TRUE,
5748 'is_filters' => TRUE,
5749 'is_group_bys' => TRUE,
5751 $options['prefix'] . 'country_id' => [
5752 'title' => $options['prefix_label'] . ts('Country'),
5753 'alter_display' => 'alterCountryID',
5754 'name' => 'country_id',
5755 'is_fields' => TRUE,
5756 'is_filters' => TRUE,
5757 'is_group_bys' => TRUE,
5758 'type' => CRM_Utils_Type
::T_INT
,
5759 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5760 'options' => CRM_Core_PseudoConstant
::country(),
5762 $options['prefix'] . 'location_type_id' => [
5763 'name' => 'location_type_id',
5764 'title' => $options['prefix_label'] . ts('Location Type'),
5765 'type' => CRM_Utils_Type
::T_INT
,
5766 'is_fields' => TRUE,
5767 'alter_display' => 'alterLocationTypeID',
5769 $options['prefix'] . 'id' => [
5770 'title' => $options['prefix_label'] . ts('ID'),
5772 'is_fields' => TRUE,
5774 $options['prefix'] . 'is_primary' => [
5775 'name' => 'is_primary',
5776 'title' => $options['prefix_label'] . ts('Primary Address?'),
5777 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5778 'is_fields' => TRUE,
5781 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5785 * Build the columns.
5787 * The normal report class needs you to remember to do a few things that are often erratic
5789 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5790 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5791 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5792 * means any saved filters / fields on saved report instances. This will mean that matching names from
5793 * different tables may be ambigious, but it will smooth any code transition.
5794 * - note that it assumes the value being passed in is the actual table field name
5796 * 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
5797 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5799 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5800 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5801 * the core classes can start to move towards that.
5803 * @param array $specs
5804 * @param string $tableName
5805 * @param string $daoName
5806 * @param string $tableAlias
5807 * @param array $defaults
5808 * @param array $options
5812 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = [], $options = []) {
5814 $tableAlias = str_replace('civicrm_', '', $tableName);
5816 $types = ['filters', 'group_bys', 'order_bys', 'join_filters'];
5817 $columns = [$tableName => array_fill_keys($types, [])];
5818 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5819 $columns[$tableName]['dao'] = $daoName;
5820 $columns[$tableName]['alias'] = $tableAlias;
5822 foreach ($specs as $specName => $spec) {
5823 if (empty($spec['name'])) {
5824 $spec['name'] = $specName;
5827 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5828 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5829 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5830 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5831 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5834 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5835 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5838 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5839 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5842 foreach ($types as $type) {
5843 if ($options[$type] && !empty($spec['is_' . $type])) {
5844 $columns[$tableName][$type][$fieldAlias] = $spec;
5845 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5846 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5855 * Store group bys into array - so we can check elsewhere what is grouped.
5857 protected function storeGroupByArray() {
5859 if (!CRM_Utils_Array
::value('group_bys', $this->_params
)
5860 ||
!is_array($this->_params
['group_bys'])) {
5861 $this->_params
['group_bys'] = [];
5864 foreach ($this->_columns
as $tableName => $table) {
5865 $table = $this->_columns
[$tableName];
5866 if (array_key_exists('group_bys', $table)) {
5867 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5868 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5869 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5870 if (!empty($field['chart'])) {
5871 $this->assign('chartSupported', TRUE);
5874 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5875 !empty($this->_params
['group_bys_freq'][$fieldName])
5878 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5880 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5883 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
5886 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_{$this->_params['group_bys_freq'][$fieldName]} FROM {$field['dbAlias']})";
5891 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5892 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5907 protected function getDefaultsFromOptions($options) {
5909 'fields_defaults' => $options['fields_defaults'],
5910 'filters_defaults' => $options['filters_defaults'],
5911 'group_bys_defaults' => $options['group_bys_defaults'],
5912 'order_bys_defaults' => $options['order_bys_defaults'],
5918 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5920 * Full group by mode dictates that a field must either be in the group by function or
5921 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5924 * @param string $tableName
5925 * @param string $fieldName
5926 * @param string $field
5929 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5930 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5931 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5932 $label = CRM_Utils_Array
::value('title', $field);
5933 $alias = $field['tplField'] ??
"{$tableName}_{$fieldName}";
5934 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5935 $this->_selectAliases
[] = $alias;
5936 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5937 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5939 return "({$field['dbAlias']}) as $alias";
5945 * Generate clause for the selected filter.
5947 * @param array $field
5948 * Field specification
5949 * @param string $fieldName
5953 * Relevant where clause.
5955 protected function generateFilterClause($field, $fieldName) {
5956 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
5957 if (CRM_Utils_Array
::value('operatorType', $field) ==
5958 CRM_Report_Form
::OP_MONTH
5960 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5961 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
5962 if (is_array($value) && !empty($value)) {
5963 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
5968 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
5969 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
5970 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
5971 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
5972 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
5973 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
5977 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5979 return $this->whereClause($field,
5981 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
5982 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
5983 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)