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
292 protected $_offsetValue = NULL;
296 protected $_sections = NULL;
297 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
298 protected $_absoluteUrl = FALSE;
301 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
305 protected $_storeResultSet = FALSE;
308 * When _storeResultSet Flag is set use this var to store result set in form of array
312 protected $_resultSet = [];
315 * To what frequency group-by a date column
319 protected $_groupByDateFreq = [
321 'YEARWEEK' => 'Week',
322 'QUARTER' => 'Quarter',
327 * Variables to hold the acl inner join and where clause
330 protected $_aclFrom = NULL;
331 protected $_aclWhere = NULL;
334 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
336 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
340 protected $_selectedTables = [];
343 * Array of DAO tables having columns included in WHERE or HAVING clause
347 protected $filteredTables;
350 * Output mode e.g 'print', 'csv', 'pdf'.
354 protected $_outputMode;
357 * Format of any chart in use.
359 * (it's unclear if this could be merged with outputMode at this stage)
365 public $_having = NULL;
366 public $_select = NULL;
367 public $_selectClauses = [];
368 public $_columnHeaders = [];
369 public $_orderBy = NULL;
370 public $_orderByFields = [];
371 public $_orderByArray = [];
373 * Array of clauses to group by.
377 protected $_groupByArray = [];
378 public $_groupBy = NULL;
379 public $_whereClauses = [];
380 public $_havingClauses = [];
383 * DashBoardRowCount Dashboard row count
386 public $_dashBoardRowCount;
389 * Is this being called without a form controller (ie. the report is being render outside the normal form
390 * - e.g the api is retrieving the rows
393 public $noController = FALSE;
396 * Variable to hold the currency alias
399 protected $_currencyColumn = NULL;
404 protected $_interval;
409 protected $_sendmail;
422 * @var string Report description.
424 public $_description;
427 * @var bool Is an address field selected.
428 * This was intended to determine if the address table should be joined in
429 * The isTableSelected function is now preferred for this purpose
431 protected $_addressField;
434 * @var bool Is an email field selected.
435 * This was intended to determine if the email table should be joined in
436 * The isTableSelected function is now preferred for this purpose
438 protected $_emailField;
441 * @var bool Is a phone field selected.
442 * This was intended to determine if the phone table should be joined in
443 * The isTableSelected function is now preferred for this purpose
445 protected $_phoneField;
448 * @var bool Create new report instance? (or update existing) on save.
450 protected $_createNew;
453 * When a grand total row has calculated the status we pop it off to here.
455 * This allows us to access it from the stats function and avoid recalculating.
458 protected $rollupRow = [];
461 * @var string Database attributes - character set and collation
463 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
466 * SQL being run in this report.
468 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
476 * An instruction not to add a Group By.
478 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
480 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
481 * such as in pivot charts when no row header is set
485 protected $noGroupBy = FALSE;
488 * SQL being run in this report as an array.
490 * The sql in the report is stored in this variable in order to be returned to api & test calls.
498 * Tables created for the report that need removal afterwards.
500 * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x']
503 protected $temporaryTables = [];
506 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
509 public $optimisedForOnlyFullGroupBy = TRUE;
514 public function __construct() {
515 parent
::__construct();
517 $this->addClass('crm-report-form');
519 if ($this->_tagFilter
) {
520 $this->buildTagFilter();
522 if ($this->_exposeContactID
) {
523 if (array_key_exists('civicrm_contact', $this->_columns
)) {
524 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = [
526 'title' => ts('Contact ID'),
532 if ($this->_groupFilter
) {
533 $this->buildGroupFilter();
536 // Get all custom groups
537 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
539 // Get the custom groupIds for which the user has VIEW permission
540 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
541 // and addCustomDataToColumns() will allow access to all custom groups.
542 $permCustomGroupIds = [];
543 if (!CRM_Core_Permission
::check('access all custom data')) {
544 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
545 // do not allow custom data for reports if user doesn't have
546 // permission to access custom data.
547 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
548 $this->_customGroupExtends
= [];
552 // merge custom data columns to _columns list, if any
553 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
555 // add / modify display columns, filters ..etc
556 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
558 //assign currencyColumn variable to tpl
559 $this->assign('currencyColumn', $this->_currencyColumn
);
563 * Shared pre-process function.
565 * If overriding preProcess function this should still be called.
569 public function preProcessCommon() {
570 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
572 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
574 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
576 $this->assign('section', $this->_section
);
577 CRM_Core_Region
::instance('page-header')->add([
578 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
580 if (!$this->noController
) {
581 $this->setID($this->get('instanceId'));
584 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
586 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
590 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
591 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
592 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
596 $this->assign('instanceId', $this->_id
);
597 $params = ['id' => $this->_id
];
598 $this->_instanceValues
= [];
599 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
601 $this->_instanceValues
603 if (empty($this->_instanceValues
)) {
604 CRM_Core_Error
::fatal("Report could not be loaded.");
606 $this->_title
= $this->_instanceValues
['title'];
607 if (!empty($this->_instanceValues
['permission']) &&
608 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
609 CRM_Core_Permission
::check('administer Reports')
612 CRM_Utils_System
::permissionDenied();
613 CRM_Utils_System
::civiExit();
616 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
618 $this->_formValues
= unserialize($formValues);
621 $this->_formValues
= NULL;
624 $this->setOutputMode();
626 if ($this->_outputMode
== 'copy') {
627 $this->_createNew
= TRUE;
628 $this->_params
= $this->_formValues
;
629 $this->_params
['view_mode'] = 'criteria';
630 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', [
631 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
632 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
634 // Do not pass go. Do not collect another chance to re-run the same query.
635 CRM_Report_Form_Instance
::postProcess($this);
638 // lets always do a force if reset is found in the url.
639 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
640 // in the comment line above these 2.
641 if (!empty($_REQUEST['reset'])
642 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), ['save', 'criteria'])) {
647 $this->assign('mode', 'instance');
649 elseif (!$this->noController
) {
650 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
651 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
652 if (($instanceCount > 0) && $optionValueID) {
653 $this->assign('instanceUrl',
654 CRM_Utils_System
::url('civicrm/report/list',
655 "reset=1&ovid=$optionValueID"
659 if ($optionValueID) {
660 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
664 $this->assign('mode', 'template');
667 // lets display the Report Settings section
668 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
670 // Do not display Report Settings section if administer Reports permission is absent OR
671 // if report instance is reserved and administer reserved reports absent
672 if (!CRM_Core_Permission
::check('administer Reports') ||
673 ($this->_instanceValues
['is_reserved'] &&
674 !CRM_Core_Permission
::check('administer reserved reports'))
676 $this->_instanceForm
= FALSE;
679 $this->assign('criteriaForm', FALSE);
680 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
681 if (CRM_Core_Permission
::check('administer Reports') ||
682 CRM_Core_Permission
::check('access Report Criteria')
684 if (!$this->_instanceValues
['is_reserved'] ||
685 CRM_Core_Permission
::check('administer reserved reports')
687 $this->assign('criteriaForm', TRUE);
688 $this->_criteriaForm
= TRUE;
692 // Special permissions check for private instance if it's not the current contact instance
694 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
695 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
696 if (!CRM_Core_Permission
::check('access all private reports')) {
697 $this->_instanceForm
= FALSE;
698 $this->assign('criteriaForm', FALSE);
702 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
703 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
704 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
705 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
711 public function addBreadCrumb() {
715 'title' => ts('Report Templates'),
716 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
720 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
724 * Pre process function.
726 * Called prior to build form.
728 public function preProcess() {
729 $this->preProcessCommon();
732 $this->addBreadCrumb();
735 foreach ($this->_columns
as $tableName => $table) {
736 $this->setTableAlias($table, $tableName);
739 // higher preference to bao object
740 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
743 if (method_exists($daoOrBaoName, 'exportableFields')) {
744 $expFields = $daoOrBaoName::exportableFields();
747 $expFields = $daoOrBaoName::export();
751 $doNotCopy = ['required', 'default'];
753 $fieldGroups = ['fields', 'filters', 'group_bys', 'order_bys'];
754 foreach ($fieldGroups as $fieldGrp) {
755 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
756 foreach ($table[$fieldGrp] as $fieldName => $field) {
757 // $name is the field name used to reference the BAO/DAO export fields array
758 $name = isset($field['name']) ?
$field['name'] : $fieldName;
760 // Sometimes the field name key in the BAO/DAO export fields array is
761 // different from the actual database field name.
762 // Unset $field['name'] so that actual database field name can be obtained
763 // from the BAO/DAO export fields array.
764 unset($field['name']);
766 if (array_key_exists($name, $expFields)) {
767 foreach ($doNotCopy as $dnc) {
768 // unset the values we don't want to be copied.
769 unset($expFields[$name][$dnc]);
772 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
775 foreach ($expFields[$name] as $property => $val) {
776 if (!array_key_exists($property, $field)) {
777 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
784 if (!empty($field['no_repeat'])) {
785 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
787 if (!empty($field['no_display'])) {
788 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
791 // set alias = table-name, unless already set
792 $alias = isset($field['alias']) ?
$field['alias'] : (
793 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
795 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
797 // set name = fieldName, unless already set
798 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
799 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
802 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
803 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
806 // set dbAlias = alias.name, unless already set
807 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
808 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
810 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
813 // a few auto fills for filters
814 if ($fieldGrp == 'filters') {
815 // fill operator types
816 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
817 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
818 case CRM_Utils_Type
::T_MONEY
:
819 case CRM_Utils_Type
::T_FLOAT
:
820 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
823 case CRM_Utils_Type
::T_INT
:
824 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
827 case CRM_Utils_Type
::T_DATE
:
828 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
831 case CRM_Utils_Type
::T_BOOLEAN
:
832 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
833 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
834 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
845 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
847 // with multiple options operator-type is generally multi-select
848 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
849 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
851 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
858 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
859 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
862 $this->_columns
[$tableName]['metadata'][$fieldName] = array_merge($this->_columns
[$tableName][$fieldGrp][$fieldName], $this->_columns
[$tableName]['metadata'][$fieldName]);
868 // copy filters to a separate handy variable
869 if (array_key_exists('filters', $table)) {
870 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
873 if (array_key_exists('group_bys', $table)) {
874 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
877 if (array_key_exists('fields', $table)) {
878 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
883 $this->setDefaultValues(FALSE);
886 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
887 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
888 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
889 CRM_Report_Utils_Get
::processChart($this->_defaults
);
892 $this->_formValues
= $this->_defaults
;
893 $this->postProcess();
898 * Set default values.
900 * @param bool $freeze
904 public function setDefaultValues($freeze = TRUE) {
907 // FIXME: generalizing form field naming conventions would reduce
908 // Lots of lines below.
909 foreach ($this->_columns
as $tableName => $table) {
910 if (array_key_exists('fields', $table)) {
911 foreach ($table['fields'] as $fieldName => $field) {
912 if (empty($field['no_display'])) {
913 if (!empty($field['required'])) {
915 $this->_defaults
['fields'][$fieldName] = 1;
918 // find element object, so that we could use quickform's freeze method
919 // for required elements
920 $obj = $this->getElementFromGroup("fields", $fieldName);
922 $freezeGroup[] = $obj;
926 elseif (isset($field['default'])) {
927 $this->_defaults
['fields'][$fieldName] = $field['default'];
933 if (array_key_exists('group_bys', $table)) {
934 foreach ($table['group_bys'] as $fieldName => $field) {
935 if (isset($field['default'])) {
936 if (!empty($field['frequency'])) {
937 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
939 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
943 if (array_key_exists('filters', $table)) {
944 foreach ($table['filters'] as $fieldName => $field) {
945 if (isset($field['default'])) {
946 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
948 if (is_array($field['default'])) {
949 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
950 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
951 $this->_defaults
["{$fieldName}_relative"] = 0;
954 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
958 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
959 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
960 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
962 $this->_defaults
["{$fieldName}_value"] = $field['default'];
965 //assign default value as "in" for multiselect
966 //operator, To freeze the select element
967 if (CRM_Utils_Array
::value('operatorType', $field) ==
968 CRM_Report_Form
::OP_MULTISELECT
970 $this->_defaults
["{$fieldName}_op"] = 'in';
972 if (CRM_Utils_Array
::value('operatorType', $field) ==
973 CRM_Report_Form
::OP_ENTITYREF
975 $this->_defaults
["{$fieldName}_op"] = 'in';
977 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
978 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
980 $this->_defaults
["{$fieldName}_op"] = 'mhas';
982 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
983 $this->_defaults
["{$fieldName}_op"] = $op;
989 empty($this->_formValues
['order_bys']) &&
990 (array_key_exists('order_bys', $table) &&
991 is_array($table['order_bys']))
993 if (!array_key_exists('order_bys', $this->_defaults
)) {
994 $this->_defaults
['order_bys'] = [];
996 foreach ($table['order_bys'] as $fieldName => $field) {
997 if (!empty($field['default']) ||
!empty($field['default_order']) ||
998 CRM_Utils_Array
::value('default_is_section', $field) ||
999 !empty($field['default_weight'])
1002 'column' => $fieldName,
1003 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
1004 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
1007 if (!empty($field['default_weight'])) {
1008 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
1011 array_unshift($this->_defaults
['order_bys'], $order_by);
1017 foreach ($this->_options
as $fieldName => $field) {
1018 if (isset($field['default'])) {
1019 $this->_defaults
['options'][$fieldName] = $field['default'];
1024 if (!empty($this->_submitValues
)) {
1025 $this->preProcessOrderBy($this->_submitValues
);
1028 $this->preProcessOrderBy($this->_defaults
);
1031 // lets finish freezing task here itself
1032 if (!empty($freezeGroup)) {
1033 foreach ($freezeGroup as $elem) {
1038 if ($this->_formValues
) {
1039 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1042 if ($this->_instanceValues
) {
1043 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1046 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1048 return $this->_defaults
;
1052 * Get element from group.
1054 * @param string $group
1055 * @param string $grpFieldName
1059 public function getElementFromGroup($group, $grpFieldName) {
1060 $eleObj = $this->getElement($group);
1061 foreach ($eleObj->_elements
as $index => $obj) {
1062 if ($grpFieldName == $obj->_attributes
['name']) {
1070 * Setter for $_params.
1072 * @param array $params
1074 public function setParams($params) {
1075 $this->_params
= $params;
1079 * Getter for $_params.
1081 * @return void|array $params
1083 public function getParams() {
1084 return $this->_params
;
1090 * @param int $instanceID
1092 public function setID($instanceID) {
1093 $this->_id
= $instanceID;
1097 * Setter for $_force.
1099 * @param bool $isForce
1101 public function setForce($isForce) {
1102 $this->_force
= $isForce;
1106 * Setter for $_limitValue.
1108 * @param int $_limitValue
1110 public function setLimitValue($_limitValue) {
1111 $this->_limitValue
= $_limitValue;
1115 * Setter for $_offsetValue.
1117 * @param int $_offsetValue
1119 public function setOffsetValue($_offsetValue) {
1120 $this->_offsetValue
= $_offsetValue;
1124 * Setter for $addPaging.
1126 * @param bool $value
1128 public function setAddPaging($value) {
1129 $this->addPaging
= $value;
1133 * Getter for $_defaultValues.
1137 public function getDefaultValues() {
1138 return $this->_defaults
;
1142 * Remove any temporary tables.
1144 public function cleanUpTemporaryTables() {
1145 foreach ($this->temporaryTables
as $temporaryTable) {
1146 CRM_Core_DAO
::executeQuery('DROP ' . ($temporaryTable['temporary'] ?
'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']);
1151 * Create a temporary table.
1153 * This function creates a table AND adds the details to the developer tab & $this->>temporary tables.
1155 * @param string $identifier
1156 * This is the key that will be used for the table in the temporaryTables property.
1157 * @param string $sql
1158 * Sql select statement or column description (the latter requires the columns flag)
1159 * @param bool $isColumns
1160 * Is the sql describing columns to create (rather than using a select query).
1161 * @param bool $isMemory
1162 * Create a memory table rather than a normal INNODB table.
1166 public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) {
1167 $tempTable = CRM_Utils_SQL_TempTable
::build()->setUtf8();
1169 $tempTable->setMemory();
1172 $tempTable->createWithColumns($sql);
1175 $tempTable->createWithQuery($sql);
1177 $name = $tempTable->getName();
1178 // Developers may force tables to be durable to assist in debugging so lets check.
1179 $isNotTrueTemporary = $tempTable->isDurable();
1180 $this->addToDeveloperTab($tempTable->getCreateSql());
1181 $this->temporaryTables
[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name];
1186 * Add columns to report.
1188 public function addColumns() {
1191 foreach ($this->_columns
as $tableName => $table) {
1192 if (array_key_exists('fields', $table)) {
1193 foreach ($table['fields'] as $fieldName => $field) {
1195 if (empty($field['no_display'])) {
1196 foreach (['table', 'field'] as $var) {
1197 if (!empty($
{$var}['grouping'])) {
1198 if (!is_array($
{$var}['grouping'])) {
1199 $tableName = $
{$var}['grouping'];
1202 $tableName = array_keys($
{$var}['grouping']);
1203 $tableName = $tableName[0];
1204 $groupTitle = array_values($
{$var}['grouping']);
1205 $groupTitle = $groupTitle[0];
1210 if (!$groupTitle && isset($table['group_title'])) {
1211 $groupTitle = $table['group_title'];
1212 // Having a group_title is secret code for being a custom group
1213 // which cryptically translates to needing an accordion.
1214 // here we make that explicit.
1215 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1218 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1219 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1220 $colGroups[$tableName]['group_title'] = $groupTitle;
1222 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1228 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1229 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1231 if (!empty($colGroups)) {
1232 $this->tabs
['FieldSelection'] = [
1233 'title' => ts('Columns'),
1234 'tpl' => 'FieldSelection',
1235 'div_label' => 'col-groups',
1238 // Note this assignment is only really required in buildForm. It is being 'over-called'
1239 // to reduce risk of being missed due to overridden functions.
1240 $this->assign('tabs', $this->tabs
);
1243 $this->assign('colGroups', $colGroups);
1247 * Add filters to report.
1249 public function addFilters() {
1250 $filters = $filterGroups = [];
1253 foreach ($this->_filters
as $table => $attributes) {
1254 if (isset($this->_columns
[$table]['group_title'])) {
1255 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1256 // which magically means to 'display in an accordian'
1257 // here we make this explicit.
1258 $filterGroups[$table] = [
1259 'group_title' => $this->_columns
[$table]['group_title'],
1260 'use_accordian_for_field_selection' => TRUE,
1264 foreach ($attributes as $fieldName => $field) {
1265 // get ready with option value pair
1266 // @ 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
1268 $operations = $this->getOperationPair(
1269 CRM_Utils_Array
::value('operatorType', $field),
1272 $filters[$table][$fieldName] = $field;
1274 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1275 case CRM_Report_Form
::OP_MONTH
:
1276 if (!array_key_exists('options', $field) ||
1277 !is_array($field['options']) ||
empty($field['options'])
1279 // If there's no option list for this filter, define one.
1280 $field['options'] = [
1282 2 => ts('February'),
1289 9 => ts('September'),
1290 10 => ts('October'),
1291 11 => ts('November'),
1292 12 => ts('December'),
1294 // Add this option list to this column _columns. This is
1295 // required so that filter statistics show properly.
1296 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1298 case CRM_Report_Form
::OP_MULTISELECT
:
1299 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1300 // assume a multi-select field
1301 if (!empty($field['options']) ||
1302 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1304 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1305 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1308 if (count($operations) <= 1) {
1311 if ($fieldName == 'state_province_id' ||
1312 $fieldName == 'county_id'
1314 $this->addChainSelect($fieldName . '_value', [
1321 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], [
1322 'style' => 'min-width:250px',
1323 'class' => 'crm-select2 huge',
1325 'placeholder' => ts('- select -'),
1331 case CRM_Report_Form
::OP_SELECT
:
1332 // assume a select field
1333 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1334 if (!empty($field['options'])) {
1335 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1339 case CRM_Report_Form
::OP_ENTITYREF
:
1340 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1341 $this->setEntityRefDefaults($field, $table);
1342 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1345 case CRM_Report_Form
::OP_DATE
:
1346 // build datetime fields
1347 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1351 case CRM_Report_Form
::OP_DATETIME
:
1352 // build datetime fields
1353 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1357 case CRM_Report_Form
::OP_INT
:
1358 case CRM_Report_Form
::OP_FLOAT
:
1359 // and a min value input box
1360 $this->add('text', "{$fieldName}_min", ts('Min'));
1361 // and a max value input box
1362 $this->add('text', "{$fieldName}_max", ts('Max'));
1364 // default type is string
1365 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1366 ['onchange' => "return showHideMaxMinVal( '$fieldName', this.value );"]
1368 // we need text box for value input
1369 $this->add('text', "{$fieldName}_value", NULL, ['class' => 'huge']);
1374 if (!empty($filters)) {
1375 $this->tabs
['Filters'] = [
1376 'title' => ts('Filters'),
1378 'div_label' => 'set-filters',
1381 $this->assign('filters', $filters);
1382 $this->assign('filterGroups', $filterGroups);
1386 * Function to assign the tabs to the template in the correct order.
1388 * We want the tabs to wind up in this order (if not overridden).
1396 protected function assignTabs() {
1404 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1405 $order = array_merge($order, $this->tabs
);
1406 $this->assign('tabs', $order);
1410 * The intent is to add a tab for developers to view the sql.
1412 * Currently using dpm.
1414 * @param string $sql
1416 public function addToDeveloperTab($sql) {
1417 if (!CRM_Core_Permission
::check('view report sql')) {
1420 $ignored_output_modes = ['pdf', 'csv', 'print'];
1421 if (in_array($this->_outputMode
, $ignored_output_modes)) {
1424 $this->tabs
['Developer'] = [
1425 'title' => ts('Developer'),
1426 'tpl' => 'Developer',
1427 'div_label' => 'set-developer',
1430 $this->assignTabs();
1431 $this->sqlArray
[] = $sql;
1432 foreach ($this->sqlArray
as $sql) {
1433 foreach (['LEFT JOIN'] as $term) {
1434 $sql = str_replace($term, '<br> ' . $term, $sql);
1436 foreach (['FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';'] as $term) {
1437 $sql = str_replace($term, '<br><br>' . $term, $sql);
1439 $this->sqlFormattedArray
[] = $sql;
1440 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1442 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL
::getSqlModes());
1447 * Add options defined in $this->_options to the report.
1449 public function addOptions() {
1450 if (!empty($this->_options
)) {
1451 // FIXME: For now lets build all elements as checkboxes.
1452 // Once we clear with the format we can build elements based on type
1454 foreach ($this->_options
as $fieldName => $field) {
1457 if ($field['type'] == 'select') {
1458 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1460 elseif ($field['type'] == 'checkbox') {
1461 $options[$field['title']] = $fieldName;
1462 $this->addCheckBox($fieldName, NULL,
1464 NULL, NULL, NULL, $this->_fourColumnAttribute
1469 if (!empty($this->_options
) &&
1471 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1473 $this->tabs
['ReportOptions'] = [
1474 'title' => ts('Display Options'),
1475 'tpl' => 'ReportOptions',
1476 'div_label' => 'other-options',
1479 $this->assign('otherOptions', $this->_options
);
1483 * Add chart options to the report.
1485 public function addChartOptions() {
1486 if (!empty($this->_charts
)) {
1487 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1488 $this->assign('charts', $this->_charts
);
1489 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1494 * Add group by options to the report.
1496 public function addGroupBys() {
1497 $options = $freqElements = [];
1499 foreach ($this->_columns
as $tableName => $table) {
1500 if (array_key_exists('group_bys', $table)) {
1501 foreach ($table['group_bys'] as $fieldName => $field) {
1502 if (!empty($field) && empty($field['no_display'])) {
1503 $options[$field['title']] = $fieldName;
1504 if (!empty($field['frequency'])) {
1505 $freqElements[$field['title']] = $fieldName;
1511 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1512 NULL, NULL, NULL, $this->_fourColumnAttribute
1514 $this->assign('groupByElements', $options);
1515 if (!empty($options)) {
1516 $this->tabs
['GroupBy'] = [
1517 'title' => ts('Grouping'),
1519 'div_label' => 'group-by-elements',
1523 foreach ($freqElements as $name) {
1524 $this->addElement('select', "group_bys_freq[$name]",
1525 ts('Frequency'), $this->_groupByDateFreq
1531 * Add data for order by tab.
1533 public function addOrderBys() {
1535 foreach ($this->_columns
as $tableName => $table) {
1537 // Report developer may define any column to order by; include these as order-by options.
1538 if (array_key_exists('order_bys', $table)) {
1539 foreach ($table['order_bys'] as $fieldName => $field) {
1540 if (!empty($field)) {
1541 $options[$fieldName] = $field['title'];
1546 // Add searchable custom fields as order-by options, if so requested
1547 // (These are already indexed, so allowing to order on them is cheap.)
1549 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1550 array_key_exists('extends', $table) && !empty($table['extends'])
1552 foreach ($table['fields'] as $fieldName => $field) {
1553 if (empty($field['no_display'])) {
1554 $options[$fieldName] = $field['title'];
1562 $this->assign('orderByOptions', $options);
1563 if (!empty($options)) {
1564 $this->tabs
['OrderBy'] = [
1565 'title' => ts('Sorting'),
1567 'div_label' => 'order-by-elements',
1571 if (!empty($options)) {
1573 '-' => ' - none - ',
1575 for ($i = 1; $i <= 5; $i++
) {
1576 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1577 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
1578 'ASC' => ts('Ascending'),
1579 'DESC' => ts('Descending'),
1581 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, ['id' => "order_by_section_$i"]);
1582 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, ['id' => "order_by_pagebreak_$i"]);
1588 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1590 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1591 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1594 public function buildInstanceAndButtons() {
1595 CRM_Report_Form_Instance
::buildForm($this);
1596 $this->_actionButtonName
= $this->getButtonName('submit');
1597 $this->addTaskMenu($this->getActions($this->_id
));
1599 $this->assign('instanceForm', $this->_instanceForm
);
1601 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1602 $permission = CRM_Core_Permission
::getPermission();
1603 if ($this->_instanceForm
&& $permission == CRM_Core_Permission
::EDIT
&&
1604 $this->_add2groupSupported
1606 $this->addElement('select', 'groups', ts('Group'),
1607 ['' => ts('Add Contacts to Group')] +
1608 CRM_Core_PseudoConstant
::nestedGroup(),
1609 ['class' => 'crm-select2 crm-action-menu fa-plus huge']
1611 $this->assign('group', TRUE);
1614 $this->addElement('submit', $this->_groupButtonName
, '', ['style' => 'display: none;']);
1616 $this->addChartOptions();
1617 $showResultsLabel = $this->getResultsLabel();
1621 'name' => $showResultsLabel,
1622 'isDefault' => TRUE,
1628 * Has this form been submitted already?
1632 public function resultsDisplayed() {
1633 $buttonName = $this->controller
->getButtonName();
1634 return ($buttonName ||
$this->_outputMode
);
1638 * Get the actions for this report instance.
1640 * @param int $instanceId
1644 protected function getActions($instanceId) {
1645 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1646 if (empty($instanceId)) {
1647 $actions['report_instance.save'] = [
1648 'title' => ts('Create Report'),
1650 'is_confirm' => TRUE,
1651 'confirm_title' => ts('Create Report'),
1652 'confirm_refresh_fields' => json_encode([
1653 'title' => ['selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''],
1654 'description' => ['selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''],
1658 unset($actions['report_instance.delete']);
1661 if (!$this->_csvSupported
) {
1662 unset($actions['report_instance.csv']);
1669 * Main build form function.
1671 public function buildQuickForm() {
1672 $this->addColumns();
1674 $this->addFilters();
1676 $this->addOptions();
1678 $this->addGroupBys();
1680 $this->addOrderBys();
1682 $this->buildInstanceAndButtons();
1684 // Add form rule for report.
1689 $this->addFormRule([get_class($this), 'formRule'], $this);
1691 $this->assignTabs();
1695 * A form rule function for custom data.
1697 * The rule ensures that fields selected in group_by if any) should only be the ones
1698 * present in display/select fields criteria;
1699 * note: works if and only if any custom field selected in group_by.
1701 * @param array $fields
1702 * @param array $ignoreFields
1706 public function customDataFormRule($fields, $ignoreFields = []) {
1708 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1709 !empty($fields['group_bys'])
1711 foreach ($this->_columns
as $tableName => $table) {
1712 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1713 substr($tableName, 0, 12) == 'custom_value') &&
1714 !empty($this->_columns
[$tableName]['fields'])
1716 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1717 if (array_key_exists($fieldName, $fields['group_bys']) &&
1718 !array_key_exists($fieldName, $fields['fields'])
1720 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1722 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1723 foreach ($fields['fields'] as $fld => $val) {
1724 if (!array_key_exists($fld, $fields['group_bys']) &&
1725 !in_array($fld, $ignoreFields)
1727 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1739 * Get operators to display on form.
1741 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1743 * @param string $type
1744 * @param string $fieldName
1748 public function getOperationPair($type = "string", $fieldName = NULL) {
1749 // FIXME: At some point we should move these key-val pairs
1750 // to option_group and option_value table.
1752 case CRM_Report_Form
::OP_INT
:
1753 case CRM_Report_Form
::OP_FLOAT
:
1756 'lte' => ts('Is less than or equal to'),
1757 'gte' => ts('Is greater than or equal to'),
1758 'bw' => ts('Is between'),
1759 'eq' => ts('Is equal to'),
1760 'lt' => ts('Is less than'),
1761 'gt' => ts('Is greater than'),
1762 'neq' => ts('Is not equal to'),
1763 'nbw' => ts('Is not between'),
1764 'nll' => ts('Is empty (Null)'),
1765 'nnll' => ts('Is not empty (Null)'),
1769 case CRM_Report_Form
::OP_SELECT
:
1771 'eq' => ts('Is equal to'),
1775 case CRM_Report_Form
::OP_MONTH
:
1776 case CRM_Report_Form
::OP_MULTISELECT
:
1777 case CRM_Report_Form
::OP_ENTITYREF
:
1780 'in' => ts('Is one of'),
1781 'notin' => ts('Is not one of'),
1782 'nll' => ts('Is empty (Null)'),
1783 'nnll' => ts('Is not empty (Null)'),
1787 case CRM_Report_Form
::OP_DATE
:
1790 'nll' => ts('Is empty (Null)'),
1791 'nnll' => ts('Is not empty (Null)'),
1795 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1796 // use this operator for the values, concatenated with separator. For e.g if
1797 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1799 'mhas' => ts('Is one of'),
1800 'mnot' => ts('Is not one of'),
1807 'has' => ts('Contains'),
1808 'sw' => ts('Starts with'),
1809 'ew' => ts('Ends with'),
1810 'nhas' => ts('Does not contain'),
1811 'eq' => ts('Is equal to'),
1812 'neq' => ts('Is not equal to'),
1813 'nll' => ts('Is empty (Null)'),
1814 'nnll' => ts('Is not empty (Null)'),
1821 * Build the tag filter field to display on the filters tab.
1823 public function buildTagFilter() {
1824 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1825 if (!empty($contactTags)) {
1826 $this->_columns
['civicrm_tag'] = [
1827 'dao' => 'CRM_Core_DAO_Tag',
1831 'title' => ts('Tag'),
1832 'type' => CRM_Utils_Type
::T_INT
,
1834 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1835 'options' => $contactTags,
1843 * Adds group filters to _columns (called from _Construct).
1845 public function buildGroupFilter() {
1846 $this->_columns
['civicrm_group']['filters'] = [
1848 'name' => 'group_id',
1849 'title' => ts('Group'),
1850 'type' => CRM_Utils_Type
::T_INT
,
1851 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1853 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1856 if (empty($this->_columns
['civicrm_group']['dao'])) {
1857 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1859 if (empty($this->_columns
['civicrm_group']['alias'])) {
1860 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1865 * Get SQL operator from form text version.
1867 * @param string $operator
1871 public function getSQLOperator($operator = "like") {
1872 switch ($operator) {
1905 return 'IS NOT NULL';
1914 * Generate where clause.
1916 * This can be overridden in reports for special treatment of a field
1918 * @param array $field Field specifications
1919 * @param string $op Query operator (not an exact match to sql)
1920 * @param mixed $value
1924 * @return null|string
1926 public function whereClause(&$field, $op, $value, $min, $max) {
1928 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1930 // CRM-18010: Ensure type of each report filters
1932 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1939 if (($min !== NULL && strlen($min) > 0) ||
1940 ($max !== NULL && strlen($max) > 0)
1944 $min = CRM_Utils_Type
::escape($min, $type);
1946 $clauses[] = "( {$field['dbAlias']} >= $min )";
1949 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1953 $max = CRM_Utils_Type
::escape($max, $type);
1955 $clauses[] = "( {$field['dbAlias']} <= $max )";
1958 $clauses[] = "( {$field['dbAlias']} > $max )";
1962 if (!empty($clauses)) {
1964 $clause = implode(' AND ', $clauses);
1967 $clause = '(' . implode('OR', $clauses) . ')';
1975 if ($value !== NULL && strlen($value) > 0) {
1976 $value = CRM_Utils_Type
::escape($value, $type);
1977 if (strpos($value, '%') === FALSE) {
1978 $value = "'%{$value}%'";
1981 $value = "'{$value}'";
1983 $sqlOP = $this->getSQLOperator($op);
1984 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1990 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1991 $value = explode(',', $value);
1993 if ($value !== NULL && is_array($value) && count($value) > 0) {
1994 $sqlOP = $this->getSQLOperator($op);
1995 if (CRM_Utils_Array
::value('type', $field) ==
1996 CRM_Utils_Type
::T_STRING
1998 //cycle through selections and escape values
1999 foreach ($value as $key => $selection) {
2000 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
2003 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
2007 // for numerical values
2008 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
2011 if ($op == 'notin') {
2012 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
2015 $clause = "( " . $clause . " )";
2022 // multiple has or multiple not
2023 if ($value !== NULL && count($value) > 0) {
2024 $value = CRM_Utils_Type
::escapeAll($value, $type);
2025 $operator = $op == 'mnot' ?
'NOT' : '';
2026 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2027 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2033 if ($value !== NULL && strlen($value) > 0) {
2034 $value = CRM_Utils_Type
::escape($value, $type);
2035 if (strpos($value, '%') === FALSE) {
2037 $value = "'{$value}%'";
2040 $value = "'%{$value}'";
2044 $value = "'{$value}'";
2046 $sqlOP = $this->getSQLOperator($op);
2047 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2053 $sqlOP = $this->getSQLOperator($op);
2054 $clause = "( {$field['dbAlias']} $sqlOP )";
2060 //CRM-18457: some custom field passes value in array format against binary operator
2061 if (is_array($value) && count($value)) {
2066 if ($value !== NULL && $value !== '') {
2067 if (isset($field['clause'])) {
2068 // FIXME: we not doing escape here. Better solution is to use two
2069 // different types - data-type and filter-type
2070 $clause = $field['clause'];
2072 elseif (!is_array($value)) {
2073 $value = CRM_Utils_Type
::escape($value, $type);
2074 $sqlOP = $this->getSQLOperator($op);
2075 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
2076 $value = "'{$value}'";
2078 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2084 //dev/core/544 Add report support for multiple contact subTypes
2085 if ($field['name'] == 'contact_sub_type' && $clause) {
2086 $clause = $this->whereSubtypeClause($field, $value, $op);
2088 if (!empty($field['group']) && $clause) {
2089 $clause = $this->whereGroupClause($field, $value, $op);
2091 elseif (!empty($field['tag']) && $clause) {
2092 // not using left join in query because if any contact
2093 // belongs to more than one tag, results duplicate
2095 $clause = $this->whereTagClause($field, $value, $op);
2097 elseif (!empty($field['membership_org']) && $clause) {
2098 $clause = $this->whereMembershipOrgClause($value, $op);
2100 elseif (!empty($field['membership_type']) && $clause) {
2101 $clause = $this->whereMembershipTypeClause($value, $op);
2107 * Get SQL where clause for contact subtypes
2108 * @param string $field
2109 * @param mixed $value
2110 * @param string $op SQL Operator
2114 public function whereSubtypeClause($field, $value, $op) {
2116 $subtypeFilters = count($value);
2117 for ($i = 0; $i < $subtypeFilters; $i++
) {
2118 $clause .= "{$field['dbAlias']} LIKE '%$value[$i]%'";
2119 if ($i !== ($subtypeFilters - 1)) {
2128 * Get SQL where clause for a date field.
2130 * @param string $fieldName
2131 * @param string $relative
2132 * @param string $from
2134 * @param string $type
2135 * @param string $fromTime
2136 * @param string $toTime
2138 * @return null|string
2140 public function dateClause(
2142 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2145 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2146 $sqlOP = $this->getSQLOperator($relative);
2147 return "( {$fieldName} {$sqlOP} )";
2150 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2153 $clauses[] = "( {$fieldName} >= $from )";
2157 $clauses[] = "( {$fieldName} <= {$to} )";
2160 if (!empty($clauses)) {
2161 return implode(' AND ', $clauses);
2168 * Get values for from and to for date ranges.
2172 * @param bool $relative
2173 * @param string $from
2175 * @param string $fromTime
2176 * @param string $toTime
2180 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2181 if (empty($toTime)) {
2182 // odd legacy behaviour to treat NULL as 'end of the day'
2183 // recommend updating reports to call CRM_Utils_Date::getFromTo
2184 //directly (default on the function is the actual default there).
2187 return CRM_Utils_Date
::getFromTo($relative, $from, $to, $fromTime, $toTime);
2191 * Alter display of rows.
2193 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2194 * such as rendering contacts as links.
2196 * @param array $rows
2197 * Rows generated by SQL, with an array for each row.
2199 public function alterDisplay(&$rows) {
2203 * Alter the way in which custom data fields are displayed.
2205 * @param array $rows
2207 public function alterCustomDataDisplay(&$rows) {
2208 // custom code to alter rows having custom values
2209 if (empty($this->_customGroupExtends
)) {
2214 $customFieldIds = [];
2215 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2216 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2217 $customFieldIds[$fieldAlias] = $fieldId;
2220 if (empty($customFieldIds)) {
2224 // skip for type date and ContactReference since date format is already handled
2226 SELECT cg.table_name, cf.id
2227 FROM civicrm_custom_field cf
2228 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2229 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2230 cg.is_active = 1 AND
2231 cf.is_active = 1 AND
2232 cf.is_searchable = 1 AND
2233 cf.data_type NOT IN ('ContactReference', 'Date') AND
2234 cf.id IN (" . implode(",", $customFieldIds) . ")";
2236 $dao = CRM_Core_DAO
::executeQuery($query);
2237 while ($dao->fetch()) {
2238 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2242 $entryFound = FALSE;
2243 foreach ($rows as $rowNum => $row) {
2244 foreach ($row as $tableCol => $val) {
2245 if (array_key_exists($tableCol, $customFields)) {
2246 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2251 // skip looking further in rows, if first row itself doesn't
2252 // have the column we need
2260 * Remove duplicate rows.
2262 * @param array $rows
2264 public function removeDuplicates(&$rows) {
2265 if (empty($this->_noRepeats
)) {
2270 foreach ($rows as $key => $list) {
2271 foreach ($list as $colName => $colVal) {
2272 if (array_key_exists($colName, $checkList) &&
2273 $checkList[$colName] == $colVal
2275 $rows[$key][$colName] = "";
2277 if (in_array($colName, $this->_noRepeats
)) {
2278 $checkList[$colName] = $colVal;
2285 * Fix subtotal display.
2288 * @param array $fields
2289 * @param bool $subtotal
2291 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2292 foreach ($row as $colName => $colVal) {
2293 if (in_array($colName, $fields)) {
2295 elseif (isset($this->_columnHeaders
[$colName])) {
2297 $row[$colName] = 'Subtotal';
2301 unset($row[$colName]);
2308 * Calculate grant total.
2310 * @param array $rows
2314 public function grandTotal(&$rows) {
2315 if (!$this->_rollup ||
count($rows) == 1) {
2319 $this->moveSummaryColumnsToTheRightHandSide();
2321 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2325 $this->rollupRow
= array_pop($rows);
2327 foreach ($this->_columnHeaders
as $fld => $val) {
2328 if (!in_array($fld, $this->_statFields
)) {
2329 if (!$this->_grandFlag
) {
2330 $this->rollupRow
[$fld] = ts('Grand Total');
2331 $this->_grandFlag
= TRUE;
2334 $this->rollupRow
[$fld] = "";
2339 $this->assign('grandStat', $this->rollupRow
);
2344 * Format display output.
2346 * @param array $rows
2347 * @param bool $pager
2349 public function formatDisplay(&$rows, $pager = TRUE) {
2350 // set pager based on if any limit was applied in the query.
2355 // allow building charts if any
2356 if (!empty($this->_params
['charts']) && !empty($rows)) {
2357 $this->buildChart($rows);
2358 $this->assign('chartEnabled', TRUE);
2359 $this->_chartId
= "{$this->_params['charts']}_" .
2360 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2362 $this->assign('chartId', $this->_chartId
);
2365 // unset columns not to be displayed.
2366 foreach ($this->_columnHeaders
as $key => $value) {
2367 if (!empty($value['no_display'])) {
2368 unset($this->_columnHeaders
[$key]);
2372 // unset columns not to be displayed.
2373 if (!empty($rows)) {
2374 foreach ($this->_noDisplay
as $noDisplayField) {
2375 foreach ($rows as $rowNum => $row) {
2376 unset($this->_columnHeaders
[$noDisplayField]);
2381 // build array of section totals
2382 $this->sectionTotals();
2384 // process grand-total row
2385 $this->grandTotal($rows);
2387 // Find alter display functions.
2388 $firstRow = reset($rows);
2390 $selectedFields = array_keys($firstRow);
2391 $alterFunctions = $alterMap = $alterSpecs = [];
2392 foreach ($this->_columns
as $tableName => $table) {
2393 if (array_key_exists('metadata', $table)) {
2394 foreach ($table['metadata'] as $field => $specs) {
2395 if (in_array($tableName . '_' . $field, $selectedFields)) {
2396 if (array_key_exists('alter_display', $specs)) {
2397 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2398 $alterMap[$tableName . '_' . $field] = $field;
2399 $alterSpecs[$tableName . '_' . $field] = NULL;
2401 // Add any alters that can be intuited from the field specs.
2402 // So far only boolean but a lot more could be.
2403 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2404 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2405 $alterMap[$tableName . '_' . $field] = $field;
2406 $alterSpecs[$tableName . '_' . $field] = NULL;
2413 // Run the alter display functions
2414 foreach ($rows as $index => & $row) {
2415 foreach ($row as $selectedField => $value) {
2416 if (array_key_exists($selectedField, $alterFunctions)) {
2417 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2423 // use this method for formatting rows for display purpose.
2424 $this->alterDisplay($rows);
2425 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2427 // use this method for formatting custom rows for display purpose.
2428 $this->alterCustomDataDisplay($rows);
2434 * @param $selectedfield
2435 * @param $criteriaFieldName
2439 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2440 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2441 $row[$selectedfield . '_link'] = $url;
2442 $row[$selectedfield . '_hover'] = ts("%1 for this state.", [
2446 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2447 if (!is_array($states)) {
2455 * @param $selectedField
2456 * @param $criteriaFieldName
2460 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2461 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2462 $row[$selectedField . '_link'] = $url;
2463 $row[$selectedField . '_hover'] = ts("%1 for this country.", [
2466 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2467 if (!is_array($countries)) {
2475 * @param $selectedfield
2476 * @param $criteriaFieldName
2480 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2481 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2482 $row[$selectedfield . '_link'] = $url;
2483 $row[$selectedfield . '_hover'] = ts("%1 for this county.", [
2486 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2487 if (!is_array($counties)) {
2495 * @param $selectedfield
2496 * @param $criteriaFieldName
2500 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2501 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value);
2511 protected function alterContactID($value, &$row, $fieldname) {
2512 $nameField = substr($fieldname, 0, -2) . 'name';
2513 static $first = TRUE;
2514 static $viewContactList = FALSE;
2516 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2519 if (!$viewContactList) {
2522 if (array_key_exists($nameField, $row)) {
2523 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2526 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2536 protected function alterBoolean($value) {
2537 $options = [0 => '', 1 => ts('Yes')];
2538 if (isset($options[$value])) {
2539 return $options[$value];
2547 * @param array $rows
2549 public function buildChart(&$rows) {
2550 // override this method for building charts.
2553 // select() method below has been added recently (v3.3), and many of the report templates might
2554 // still be having their own select() method. We should fix them as and when encountered and move
2555 // towards generalizing the select() method below.
2558 * Generate the SELECT clause and set class variable $_select.
2560 public function select() {
2561 $select = $this->_selectAliases
= [];
2562 $this->storeGroupByArray();
2564 foreach ($this->_columns
as $tableName => $table) {
2565 if (array_key_exists('fields', $table)) {
2566 foreach ($table['fields'] as $fieldName => $field) {
2567 if ($tableName == 'civicrm_address') {
2568 // deprecated, use $this->isTableSelected.
2569 $this->_addressField
= TRUE;
2571 if ($tableName == 'civicrm_email') {
2572 $this->_emailField
= TRUE;
2574 if ($tableName == 'civicrm_phone') {
2575 $this->_phoneField
= TRUE;
2578 if (!empty($field['required']) ||
2579 !empty($this->_params
['fields'][$fieldName])
2582 // 1. In many cases we want select clause to be built in slightly different way
2583 // for a particular field of a particular type.
2584 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2586 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2587 if ($selectClause) {
2588 $select[] = $selectClause;
2592 // include statistics columns only if set
2593 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2594 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2598 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2599 if ($selectClause) {
2600 $select[] = $selectClause;
2603 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2610 // select for group bys
2611 if (array_key_exists('group_bys', $table)) {
2612 foreach ($table['group_bys'] as $fieldName => $field) {
2614 if ($tableName == 'civicrm_address') {
2615 $this->_addressField
= TRUE;
2617 if ($tableName == 'civicrm_email') {
2618 $this->_emailField
= TRUE;
2620 if ($tableName == 'civicrm_phone') {
2621 $this->_phoneField
= TRUE;
2623 // 1. In many cases we want select clause to be built in slightly different way
2624 // for a particular field of a particular type.
2625 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2627 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2628 if ($selectClause) {
2629 $select[] = $selectClause;
2633 if (!empty($this->_params
['group_bys']) &&
2634 !empty($this->_params
['group_bys'][$fieldName]) &&
2635 !empty($this->_params
['group_bys_freq'])
2637 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2639 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2640 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2641 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2642 $field['title'] = 'Week';
2646 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2647 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2648 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2649 $field['title'] = 'Year';
2653 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2654 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2655 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2656 $field['title'] = 'Month';
2660 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2661 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2662 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2663 $field['title'] = 'Quarter';
2666 // for graphs and charts -
2667 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2668 $this->_interval
= $field['title'];
2669 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2670 = $field['title'] . ' Beginning';
2671 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2672 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2674 // just to make sure these values are transferred to rows.
2675 // since we 'll need them for calculation purpose,
2676 // e.g making subtotals look nicer or graphs
2677 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
2678 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
2685 if (empty($select)) {
2686 // CRM-21412 Do not give fatal error on report when no fields selected
2690 $this->_selectClauses
= $select;
2691 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2695 * Build select clause for a single field.
2697 * @param string $tableName
2698 * @param string $tableKey
2699 * @param string $fieldName
2700 * @param string $field
2704 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2705 if (!empty($field['pseudofield'])) {
2706 $alias = "{$tableName}_{$fieldName}";
2707 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2708 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2709 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = CRM_Utils_Array
::value('dbAlias', $field);
2710 $this->_selectAliases
[] = $alias;
2711 return ' 1 as ' . $alias;
2717 * Build where clause.
2719 public function where() {
2720 $this->storeWhereHavingClauseArray();
2722 if (empty($this->_whereClauses
)) {
2723 $this->_where
= "WHERE ( 1 ) ";
2724 $this->_having
= "";
2727 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2730 if ($this->_aclWhere
) {
2731 $this->_where
.= " AND {$this->_aclWhere} ";
2734 if (!empty($this->_havingClauses
)) {
2735 // use this clause to construct group by clause.
2736 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2741 * Store Where clauses into an array.
2743 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2744 * temp table that may not be part of the final where clause or added
2745 * in other functions
2747 public function storeWhereHavingClauseArray() {
2748 foreach ($this->_columns
as $tableName => $table) {
2749 if (array_key_exists('filters', $table)) {
2750 foreach ($table['filters'] as $fieldName => $field) {
2751 // respect pseudofield to filter spec so fields can be marked as
2752 // not to be handled here
2753 if (!empty($field['pseudofield'])) {
2756 $clause = $this->generateFilterClause($field, $fieldName);
2758 if (!empty($clause)) {
2759 if (!empty($field['having'])) {
2760 $this->_havingClauses
[] = $clause;
2763 $this->_whereClauses
[] = $clause;
2775 public function processReportMode() {
2776 $this->setOutputMode();
2779 = CRM_Utils_Request
::retrieve(
2782 CRM_Core_DAO
::$_nullObject
2785 $this->_absoluteUrl
= FALSE;
2787 $this->assign('printOnly', FALSE);
2789 if ($this->_outputMode
== 'print' ||
2790 ($this->_sendmail
&& !$this->_outputMode
)
2792 $this->assign('printOnly', TRUE);
2794 $this->addPaging
= FALSE;
2795 $this->assign('outputMode', 'print');
2796 $this->_outputMode
= 'print';
2797 if ($this->_sendmail
) {
2798 $this->_absoluteUrl
= TRUE;
2801 elseif ($this->_outputMode
== 'pdf') {
2803 $this->addPaging
= FALSE;
2804 $this->_absoluteUrl
= TRUE;
2806 elseif ($this->_outputMode
== 'csv') {
2808 $this->_absoluteUrl
= TRUE;
2809 $this->addPaging
= FALSE;
2811 elseif ($this->_outputMode
== 'group') {
2812 $this->assign('outputMode', 'group');
2814 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2815 $this->assign('outputMode', 'create_report');
2817 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2818 $this->_createNew
= TRUE;
2821 $this->assign('outputMode', $this->_outputMode
);
2822 $this->assign('printOnly', $printOnly);
2823 // Get today's date to include in printed reports
2825 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2826 $this->assign('reportDate', $reportDate);
2831 * Post Processing function for Form.
2833 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2834 * This function is not accessed when the api calls the report.
2836 public function beginPostProcess() {
2837 $this->setParams($this->controller
->exportValues($this->_name
));
2838 if (empty($this->_params
) &&
2841 $this->setParams($this->_formValues
);
2844 // hack to fix params when submitted from dashboard, CRM-8532
2845 // fields array is missing because form building etc is skipped
2846 // in dashboard mode for report
2847 //@todo - this could be done in the dashboard no we have a setter
2848 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2849 $this->setParams($this->_formValues
);
2852 $this->processReportMode();
2854 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2855 $this->_createNew
= ($this->_outputMode
== 'copy');
2856 CRM_Report_Form_Instance
::postProcess($this);
2858 if ($this->_outputMode
== 'delete') {
2859 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2862 $this->_formValues
= $this->_params
;
2864 $this->beginPostProcessCommon();
2868 * BeginPostProcess function run in both report mode and non-report mode (api).
2870 public function beginPostProcessCommon() {
2874 * Build the report query.
2876 * @param bool $applyLimit
2880 public function buildQuery($applyLimit = TRUE) {
2881 $this->buildGroupTempTable();
2884 $this->customDataFrom();
2885 $this->buildPermissionClause();
2890 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
2891 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
2893 $clause = "{$field['dbAlias']} as {$alias}";
2895 $this->_select
.= ", $clause ";
2898 if ($applyLimit && empty($this->_params
['charts'])) {
2901 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2903 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2904 $this->addToDeveloperTab($sql);
2909 * Build group by clause.
2911 public function groupBy() {
2912 $this->storeGroupByArray();
2914 if (!empty($this->_groupByArray
)) {
2915 if ($this->optimisedForOnlyFullGroupBy
) {
2916 // We should probably deprecate this code path. What happens here is that
2917 // the group by is amended to reflect the select columns. This often breaks the
2918 // results. Retrofitting group strict group by onto existing report classes
2920 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2923 $this->_groupBy
= ' GROUP BY ' . implode($this->_groupByArray
);
2929 * Build order by clause.
2931 public function orderBy() {
2932 $this->_orderBy
= "";
2933 $this->_sections
= [];
2934 $this->storeOrderByArray();
2935 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2936 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2938 $this->assign('sections', $this->_sections
);
2942 * Extract order by fields and store as an array.
2944 * In some cases other functions want to know which fields are selected for ordering by
2945 * Separating this into a separate function allows it to be called separately from constructing
2946 * the order by clause
2948 public function storeOrderByArray() {
2951 if (!empty($this->_params
['order_bys']) &&
2952 is_array($this->_params
['order_bys']) &&
2953 !empty($this->_params
['order_bys'])
2956 // Process order_bys in user-specified order
2957 foreach ($this->_params
['order_bys'] as $orderBy) {
2959 foreach ($this->_columns
as $tableName => $table) {
2960 if (array_key_exists('order_bys', $table)) {
2961 // For DAO columns defined in $this->_columns
2962 $fields = $table['order_bys'];
2964 elseif (array_key_exists('extends', $table)) {
2965 // For custom fields referenced in $this->_customGroupExtends
2966 $fields = CRM_Utils_Array
::value('fields', $table, []);
2971 if (!empty($fields) && is_array($fields)) {
2972 foreach ($fields as $fieldName => $field) {
2973 if ($fieldName == $orderBy['column']) {
2974 $orderByField = array_merge($field, $orderBy);
2975 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2982 if (!empty($orderByField)) {
2983 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2984 if ($this->groupConcatTested
) {
2985 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
2988 // Not sure when this is preferable to using tplField (which has
2989 // definitely been tested to work in cases then this does not.
2990 // in caution not switching unless report has been tested for
2991 // group concat functionality.
2992 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2995 // Record any section headers for assignment to the template
2996 if (!empty($orderBy['section'])) {
2997 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2998 $this->_sections
[$orderByField['tplField']] = $orderByField;
3004 $this->_orderByArray
= $orderBys;
3006 $this->assign('sections', $this->_sections
);
3010 * Determine unselected columns.
3014 public function unselectedOrderByColumns() {
3015 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
3019 * Determine unselected columns.
3023 public function unselectedSectionColumns() {
3024 if (is_array($this->_sections
)) {
3025 return array_diff_key($this->_sections
, $this->getSelectColumns());
3033 * Build output rows.
3035 * @param string $sql
3036 * @param array $rows
3038 public function buildRows($sql, &$rows) {
3039 if (!$this->optimisedForOnlyFullGroupBy
) {
3040 CRM_Core_DAO
::disableFullGroupByMode();
3042 $dao = CRM_Core_DAO
::executeQuery($sql);
3043 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
3044 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
3046 CRM_Core_DAO
::reenableFullGroupByMode();
3047 if (!is_array($rows)) {
3051 // use this method to modify $this->_columnHeaders
3052 $this->modifyColumnHeaders();
3054 $unselectedSectionColumns = $this->unselectedSectionColumns();
3056 while ($dao->fetch()) {
3058 foreach ($this->_columnHeaders
as $key => $value) {
3059 if (property_exists($dao, $key)) {
3060 $row[$key] = $dao->$key;
3064 // section headers not selected for display need to be added to row
3065 foreach ($unselectedSectionColumns as $key => $values) {
3066 if (property_exists($dao, $key)) {
3067 $row[$key] = $dao->$key;
3076 * Calculate section totals.
3078 * When "order by" fields are marked as sections, this assigns to the template
3079 * an array of total counts for each section. This data is used by the Smarty
3080 * plugin {sectionTotal}.
3082 public function sectionTotals() {
3084 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3085 if (empty($this->_selectAliases
)) {
3089 if (!empty($this->_sections
)) {
3090 // build the query with no LIMIT clause
3091 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3092 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3094 // pull section aliases out of $this->_sections
3095 $sectionAliases = array_keys($this->_sections
);
3098 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3099 $ifnulls[] = "ifnull($alias, '') as $alias";
3101 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3102 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3104 // Group (un-limited) report by all aliases and get counts. This might
3105 // be done more efficiently when the contents of $sql are known, ie. by
3106 // overriding this method in the report class.
3108 $query = $this->_select
.
3109 ", count(*) as ct from ($sql) as subquery group by " .
3110 implode(", ", $sectionAliases);
3112 // initialize array of total counts
3114 $dao = CRM_Core_DAO
::executeQuery($query);
3115 while ($dao->fetch()) {
3117 // let $this->_alterDisplay translate any integer ids to human-readable values.
3118 $rows[0] = $dao->toArray();
3119 $this->alterDisplay($rows);
3122 // add totals for all permutations of section values
3125 $aliasCount = count($sectionAliases);
3126 foreach ($sectionAliases as $alias) {
3127 $values[] = $row[$alias];
3128 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3129 if ($i == $aliasCount) {
3130 // the last alias is the lowest-level section header; use count as-is
3131 $totals[$key] = $dao->ct
;
3134 // other aliases are higher level; roll count into their total
3135 $totals[$key] +
= $dao->ct
;
3139 $this->assign('sectionTotals', $totals);
3144 * Modify column headers.
3146 public function modifyColumnHeaders() {
3147 // use this method to modify $this->_columnHeaders
3151 * Move totals columns to the right edge of the table.
3153 * It seems like a more logical layout to have any totals columns on the far right regardless of
3154 * the location of the rest of their table.
3156 public function moveSummaryColumnsToTheRightHandSide() {
3157 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3158 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3162 * Assign rows to the template.
3164 * @param array $rows
3166 public function doTemplateAssignment(&$rows) {
3167 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
3168 $this->assign_by_ref('rows', $rows);
3169 $this->assign('statistics', $this->statistics($rows));
3173 * Build report statistics.
3175 * Override this method to build your own statistics.
3177 * @param array $rows
3181 public function statistics(&$rows) {
3184 $count = count($rows);
3185 // Why do we increment the count for rollup seems to artificially inflate the count.
3186 // It seems perhaps intentional to include the summary row in the count of results - although
3187 // this just seems odd.
3188 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3192 $this->countStat($statistics, $count);
3194 $this->groupByStat($statistics);
3196 $this->filterStat($statistics);
3202 * Add count statistics.
3204 * @param array $statistics
3207 public function countStat(&$statistics, $count) {
3208 $statistics['counts']['rowCount'] = [
3209 'title' => ts('Row(s) Listed'),
3213 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3214 $statistics['counts']['rowsFound'] = [
3215 'title' => ts('Total Row(s)'),
3216 'value' => $this->_rowsFound
,
3222 * Add group by statistics.
3224 * @param array $statistics
3226 public function groupByStat(&$statistics) {
3227 if (!empty($this->_params
['group_bys']) &&
3228 is_array($this->_params
['group_bys']) &&
3229 !empty($this->_params
['group_bys'])
3231 foreach ($this->_columns
as $tableName => $table) {
3232 if (array_key_exists('group_bys', $table)) {
3233 foreach ($table['group_bys'] as $fieldName => $field) {
3234 if (!empty($this->_params
['group_bys'][$fieldName])) {
3235 $combinations[] = $field['title'];
3240 $statistics['groups'][] = [
3241 'title' => ts('Grouping(s)'),
3242 'value' => implode(' & ', $combinations),
3248 * Filter statistics.
3250 * @param array $statistics
3252 public function filterStat(&$statistics) {
3253 foreach ($this->_columns
as $tableName => $table) {
3254 if (array_key_exists('filters', $table)) {
3255 foreach ($table['filters'] as $fieldName => $field) {
3256 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3257 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3258 CRM_Utils_Array
::value('operatorType', $field) !=
3259 CRM_Report_Form
::OP_MONTH
3263 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3264 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3265 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3266 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3267 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3269 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3270 $from = CRM_Utils_Date
::customFormat($from, NULL, [$from_time_format]);
3272 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3273 $to = CRM_Utils_Date
::customFormat($to, NULL, [$to_time_format]);
3276 $statistics['filters'][] = [
3277 'title' => $field['title'],
3278 'value' => ts("Between %1 and %2", [1 => $from, 2 => $to]),
3281 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3282 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3284 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3285 $statistics['filters'][] = [
3286 'title' => $field['title'],
3287 'value' => $pair[$rel],
3292 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3295 $pair = $this->getOperationPair(
3296 CRM_Utils_Array
::value('operatorType', $field),
3299 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3300 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3301 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3302 if (in_array($op, ['bw', 'nbw']) && ($min ||
$max)) {
3303 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3305 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3306 $this->setEntityRefDefaults($field, $tableName);
3307 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3309 CRM_Utils_Array
::value('api', $field['attributes'], []));
3311 foreach ($result['values'] as $v) {
3312 $values[] = $v['label'];
3314 $value = "{$pair[$op]} " . implode(', ', $values);
3316 elseif ($op == 'nll' ||
$op == 'nnll') {
3317 $value = $pair[$op];
3319 elseif (is_array($val) && (!empty($val))) {
3320 $options = CRM_Utils_Array
::value('options', $field, []);
3321 foreach ($val as $key => $valIds) {
3322 if (isset($options[$valIds])) {
3323 $val[$key] = $options[$valIds];
3326 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3327 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3328 $val = implode(', ', $val);
3329 $value = "{$pair[$op]} " . $val;
3331 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3332 isset($field['options']) &&
3333 is_array($field['options']) && !empty($field['options'])
3335 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3336 CRM_Utils_Array
::value($val, $field['options'], $val);
3339 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3342 if ($value && empty($field['no_display'])) {
3343 $statistics['filters'][] = [
3344 'title' => CRM_Utils_Array
::value('title', $field),
3355 * End post processing.
3357 * @param array|null $rows
3359 public function endPostProcess(&$rows = NULL) {
3360 $this->assign('report_class', get_class($this));
3361 if ($this->_storeResultSet
) {
3362 $this->_resultSet
= $rows;
3365 if ($this->_outputMode
== 'print' ||
3366 $this->_outputMode
== 'pdf' ||
3370 $content = $this->compileContent();
3371 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3375 if ($this->_sendmail
) {
3376 $config = CRM_Core_Config
::singleton();
3379 if ($this->_outputMode
== 'csv') {
3381 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3382 ": {$url}</p>" . '<p>' .
3383 ts('The report is attached as a CSV file.') . '</p>' .
3384 $this->_formValues
['report_footer'];
3386 $csvFullFilename = $config->templateCompileDir
.
3387 CRM_Utils_File
::makeFileName('CiviReport.csv');
3388 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3389 file_put_contents($csvFullFilename, $csvContent);
3391 'fullPath' => $csvFullFilename,
3392 'mime_type' => 'text/csv',
3393 'cleanName' => 'CiviReport.csv',
3396 if ($this->_outputMode
== 'pdf') {
3397 // generate PDF content
3398 $pdfFullFilename = $config->templateCompileDir
.
3399 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3400 file_put_contents($pdfFullFilename,
3401 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3402 TRUE, ['orientation' => 'landscape']
3405 // generate Email Content
3407 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3408 ": {$url}</p>" . '<p>' .
3409 ts('The report is attached as a PDF file.') . '</p>' .
3410 $this->_formValues
['report_footer'];
3413 'fullPath' => $pdfFullFilename,
3414 'mime_type' => 'application/pdf',
3415 'cleanName' => 'CiviReport.pdf',
3419 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3420 $this->_outputMode
, $attachments
3423 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3426 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3430 elseif ($this->_outputMode
== 'print') {
3434 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3435 $config = CRM_Core_Config
::singleton();
3436 //get chart image name
3437 $chartImg = $this->_chartId
. '.png';
3438 //get image url path
3440 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3442 $uploadUrl .= $chartImg;
3443 //get image doc path to overwrite
3445 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3446 'openFlashChart/' . $chartImg;
3448 $chart = imagecreatefrompng($uploadUrl);
3449 //convert it into formatted png
3450 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3451 //overwrite with same image
3452 imagepng($chart, $uploadImg);
3454 imagedestroy($chart);
3456 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, ['orientation' => 'landscape']);
3458 CRM_Utils_System
::civiExit();
3460 elseif ($this->_outputMode
== 'csv') {
3461 CRM_Report_Utils_Report
::export2csv($this, $rows);
3463 elseif ($this->_outputMode
== 'group') {
3464 $group = $this->_params
['groups'];
3465 $this->add2group($group);
3470 * Set store result set indicator to TRUE.
3472 * @todo explain what this does
3474 public function storeResultSet() {
3475 $this->_storeResultSet
= TRUE;
3483 public function getResultSet() {
3484 return $this->_resultSet
;
3488 * Get the sql used to generate the report.
3492 public function getReportSql() {
3493 return $this->sqlArray
;
3497 * Use the form name to create the tpl file name.
3501 public function getTemplateFileName() {
3502 $defaultTpl = parent
::getTemplateFileName();
3503 $template = CRM_Core_Smarty
::singleton();
3504 if (!$template->template_exists($defaultTpl)) {
3505 $defaultTpl = 'CRM/Report/Form.tpl';
3511 * Compile the report content.
3513 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3517 public function compileContent() {
3518 $templateFile = $this->getHookedTemplateFileName();
3519 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3520 CRM_Core_Form
::$_template->fetch($templateFile) .
3521 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3525 * Post process function.
3527 public function postProcess() {
3528 // get ready with post process params
3529 $this->beginPostProcess();
3532 $sql = $this->buildQuery();
3534 // build array of result based on column headers. This method also allows
3535 // modifying column headers before using it to build result set i.e $rows.
3537 $this->buildRows($sql, $rows);
3539 // format result set.
3540 $this->formatDisplay($rows);
3542 // assign variables to templates
3543 $this->doTemplateAssignment($rows);
3545 // do print / pdf / instance stuff if needed
3546 $this->endPostProcess($rows);
3552 * @param int $rowCount
3556 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3557 // lets do the pager if in html mode
3558 $this->_limit
= NULL;
3560 // CRM-14115, over-ride row count if rowCount is specified in URL
3561 if ($this->_dashBoardRowCount
) {
3562 $rowCount = $this->_dashBoardRowCount
;
3564 if ($this->addPaging
) {
3565 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3567 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3569 // @todo all http vars should be extracted in the preProcess
3570 // - not randomly in the class
3571 if (!$pageId && !empty($_POST)) {
3572 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3573 $pageId = max((int) $_POST['crmPID_B'], 1);
3575 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3576 $pageId = max((int) $_POST['crmPID'], 1);
3578 unset($_POST['crmPID_B'], $_POST['crmPID']);
3581 $pageId = $pageId ?
$pageId : 1;
3582 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3583 $offset = ($pageId - 1) * $rowCount;
3585 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3586 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3588 $this->_limit
= " LIMIT $offset, $rowCount";
3589 return [$offset, $rowCount];
3591 if ($this->_limitValue
) {
3592 if ($this->_offsetValue
) {
3593 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3596 $this->_limit
= " LIMIT " . $this->_limitValue
;
3604 * @param int $rowCount
3606 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3607 // CRM-14115, over-ride row count if rowCount is specified in URL
3608 if ($this->_dashBoardRowCount
) {
3609 $rowCount = $this->_dashBoardRowCount
;
3612 if ($this->_limit
&& ($this->_limit
!= '')) {
3613 if (!$this->_rowsFound
) {
3614 $sql = "SELECT FOUND_ROWS();";
3615 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3618 'total' => $this->_rowsFound
,
3619 'rowCount' => $rowCount,
3620 'status' => ts('Records') . ' %%StatusMessage%%',
3621 'buttonBottom' => 'PagerBottomButton',
3622 'buttonTop' => 'PagerTopButton',
3624 if (!empty($this->controller
)) {
3625 // This happens when being called from the api Really we want the api to be able to
3626 // pass paging parameters, but at this stage just preventing test crashes.
3627 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3630 $pager = new CRM_Utils_Pager($params);
3631 $this->assign_by_ref('pager', $pager);
3632 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3637 * Build a group filter with contempt for large data sets.
3639 * This function has been retained as it takes time to migrate the reports over
3640 * to the new method which will not crash on large datasets.
3644 * @param string $field
3645 * @param mixed $value
3650 public function legacySlowGroupFilterClause($field, $value, $op) {
3651 $smartGroupQuery = "";
3653 $group = new CRM_Contact_DAO_Group();
3654 $group->is_active
= 1;
3657 while ($group->fetch()) {
3658 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3659 $group->saved_search_id
3661 $smartGroups[] = $group->id
;
3665 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3667 $smartGroupQuery = '';
3668 if (!empty($smartGroups)) {
3669 $smartGroups = implode(',', $smartGroups);
3670 $smartGroupQuery = " UNION DISTINCT
3671 SELECT DISTINCT smartgroup_contact.contact_id
3672 FROM civicrm_group_contact_cache smartgroup_contact
3673 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3676 $sqlOp = $this->getSQLOperator($op);
3677 if (!is_array($value)) {
3680 //include child groups if any
3681 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3683 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3685 $contactAlias = $this->_aliases
['civicrm_contact'];
3686 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3687 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3689 return " {$contactAlias}.id {$sqlOp} (
3690 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3691 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3692 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3693 {$smartGroupQuery} ) ";
3697 * Build where clause for groups.
3699 * @param string $field
3700 * @param mixed $value
3705 public function whereGroupClause($field, $value, $op) {
3706 if ($this->groupFilterNotOptimised
) {
3707 return $this->legacySlowGroupFilterClause($field, $value, $op);
3709 if ($op === 'notin') {
3710 return " group_temp_table.id IS NULL ";
3712 // We will have used an inner join instead.
3717 * Create a table of the contact ids included by the group filter.
3719 * This function is called by both the api (tests) and the UI.
3721 public function buildGroupTempTable() {
3722 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3725 $filteredGroups = (array) $this->_params
['gid_value'];
3727 $groups = civicrm_api3('Group', 'get', [
3729 'id' => ['IN' => $filteredGroups],
3730 'saved_search_id' => ['>' => 0],
3733 $smartGroups = array_keys($groups['values']);
3736 SELECT DISTINCT group_contact.contact_id as id
3737 FROM civicrm_group_contact group_contact
3738 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3739 AND group_contact.status = 'Added' ";
3741 if (!empty($smartGroups)) {
3742 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3743 $smartGroups = implode(',', $smartGroups);
3746 SELECT smartgroup_contact.contact_id as id
3747 FROM civicrm_group_contact_cache smartgroup_contact
3748 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3751 $this->groupTempTable
= $this->createTemporaryTable('rptgrp', $query);
3752 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3756 * Execute query and add it to the developer tab.
3758 * @param string $query
3759 * @param array $params
3761 * @return \CRM_Core_DAO|object
3763 protected function executeReportQuery($query, $params = []) {
3764 $this->addToDeveloperTab($query);
3765 return CRM_Core_DAO
::executeQuery($query, $params);
3769 * Build where clause for tags.
3771 * @param string $field
3772 * @param mixed $value
3777 public function whereTagClause($field, $value, $op) {
3778 // not using left join in query because if any contact
3779 // belongs to more than one tag, results duplicate
3781 $sqlOp = $this->getSQLOperator($op);
3782 if (!is_array($value)) {
3785 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3786 $entity_table = $this->_tagFilterTable
;
3787 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3788 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3789 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3790 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3794 * Generate membership organization clause.
3796 * @param mixed $value
3797 * @param string $op SQL Operator
3801 public function whereMembershipOrgClause($value, $op) {
3802 $sqlOp = $this->getSQLOperator($op);
3803 if (!is_array($value)) {
3807 $tmp_membership_org_sql_list = implode(', ', $value);
3808 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3809 SELECT DISTINCT mem.contact_id
3810 FROM civicrm_membership mem
3811 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3812 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3813 WHERE mt.member_of_contact_id IN (" .
3814 $tmp_membership_org_sql_list . ")
3815 AND mt.is_active = '1'
3816 AND mem_status.is_current_member = '1'
3817 AND mem_status.is_active = '1' ) ";
3821 * Generate Membership Type SQL Clause.
3823 * @param mixed $value
3829 public function whereMembershipTypeClause($value, $op) {
3830 $sqlOp = $this->getSQLOperator($op);
3831 if (!is_array($value)) {
3835 $tmp_membership_sql_list = implode(', ', $value);
3836 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3837 SELECT DISTINCT mem.contact_id
3838 FROM civicrm_membership mem
3839 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3840 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3841 WHERE mem.membership_type_id IN (" .
3842 $tmp_membership_sql_list . ")
3843 AND mt.is_active = '1'
3844 AND mem_status.is_current_member = '1'
3845 AND mem_status.is_active = '1' ) ";
3849 * Buld contact acl clause
3850 * @deprecated in favor of buildPermissionClause
3852 * @param string $tableAlias
3854 public function buildACLClause($tableAlias = 'contact_a') {
3855 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3859 * Build the permision clause for all entities in this report
3861 public function buildPermissionClause() {
3863 foreach ($this->selectedTables() as $tableName) {
3864 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3865 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3866 $tableAlias = $this->_columns
[$tableName]['alias'];
3867 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3868 foreach ($clauses as $field => $clause) {
3869 // Skip contact_id field if redundant
3870 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3871 $ret["$tableName.$field"] = $clause;
3876 // Override output from buildACLClause
3877 $this->_aclFrom
= NULL;
3878 $this->_aclWhere
= implode(' AND ', $ret);
3882 * Add custom data to the columns.
3884 * @param bool $addFields
3885 * @param array $permCustomGroupIds
3887 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = []) {
3888 if (empty($this->_customGroupExtends
)) {
3891 if (!is_array($this->_customGroupExtends
)) {
3892 $this->_customGroupExtends
= [$this->_customGroupExtends
];
3894 $customGroupWhere = '';
3895 if (!empty($permCustomGroupIds)) {
3896 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3900 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3901 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3902 FROM civicrm_custom_group cg
3903 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3904 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3906 cg.is_active = 1 AND
3907 cf.is_active = 1 AND
3908 cf.is_searchable = 1
3909 ORDER BY cg.weight, cf.weight";
3910 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3913 while ($customDAO->fetch()) {
3914 if ($customDAO->table_name
!= $curTable) {
3915 $curTable = $customDAO->table_name
;
3916 $curFields = $curFilters = [];
3919 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3920 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3921 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3922 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3924 foreach (['fields', 'filters', 'group_bys'] as $colKey) {
3925 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3926 $this->_columns
[$curTable][$colKey] = [];
3930 $fieldName = 'custom_' . $customDAO->cf_id
;
3933 // this makes aliasing work in favor
3934 $curFields[$fieldName] = [
3935 'name' => $customDAO->column_name
,
3936 'title' => $customDAO->label
,
3937 'dataType' => $customDAO->data_type
,
3938 'htmlType' => $customDAO->html_type
,
3941 if ($this->_customGroupFilters
) {
3942 // this makes aliasing work in favor
3943 $curFilters[$fieldName] = [
3944 'name' => $customDAO->column_name
,
3945 'title' => $customDAO->label
,
3946 'dataType' => $customDAO->data_type
,
3947 'htmlType' => $customDAO->html_type
,
3951 switch ($customDAO->data_type
) {
3954 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3955 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3956 // CRM-6946, show time part for datetime date fields
3957 if ($customDAO->time_format
) {
3958 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3963 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3964 $curFilters[$fieldName]['options'] = ['' => ts('- select -')] + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
3965 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3969 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3970 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3974 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3975 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3976 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3980 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3981 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3985 case 'StateProvince':
3987 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3989 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
3990 if ((is_array($options) && count($options) != 0) ||
(!is_array($options) && $options !== FALSE)) {
3991 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3992 $curFilters[$fieldName]['options'] = $options;
3996 case 'ContactReference':
3997 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3998 $curFilters[$fieldName]['name'] = 'display_name';
3999 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4001 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4002 $curFields[$fieldName]['name'] = 'display_name';
4003 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4007 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4008 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
4012 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
4013 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, [], 'search');
4014 if ($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 if (!array_key_exists('type', $curFields[$fieldName])) {
4021 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], []);
4025 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
4027 if ($this->_customGroupFilters
) {
4028 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
4030 if ($this->_customGroupGroupBy
) {
4031 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
4037 * Build custom data from clause.
4039 * @param bool $joinsForFiltersOnly
4040 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
4042 public function customDataFrom($joinsForFiltersOnly = FALSE) {
4043 if (empty($this->_customGroupExtends
)) {
4046 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
4047 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
4048 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
4050 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
4051 while ($customTablesDAO->fetch()) {
4052 $customTables[] = $customTablesDAO->table_name
;
4055 foreach ($this->_columns
as $table => $prop) {
4056 if (in_array($table, $customTables)) {
4057 $extendsTable = $mapper[$prop['extends']];
4058 // Check field is required for rendering the report.
4059 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4062 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
4064 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
4066 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4067 // handle for ContactReference
4068 if (array_key_exists('fields', $prop)) {
4069 foreach ($prop['fields'] as $fieldName => $field) {
4070 if (CRM_Utils_Array
::value('dataType', $field) ==
4073 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4075 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4084 * Check if the field is selected.
4086 * @param string $prop
4090 public function isFieldSelected($prop) {
4095 if (!empty($this->_params
['fields'])) {
4096 foreach (array_keys($prop['fields']) as $fieldAlias) {
4097 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4098 if ($customFieldId) {
4099 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4103 //might be survey response field.
4104 if (!empty($this->_params
['fields']['survey_response']) &&
4105 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4113 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4114 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4115 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4116 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4123 if (!empty($this->_params
['order_bys'])) {
4124 foreach (array_keys($prop['fields']) as $fieldAlias) {
4125 foreach ($this->_params
['order_bys'] as $orderBy) {
4126 if ($fieldAlias == $orderBy['column'] &&
4127 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4134 return $this->isFieldFiltered($prop);
4139 * Check if the field is used as a filter.
4141 * @param string $prop
4145 protected function isFieldFiltered($prop) {
4146 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4147 foreach ($prop['filters'] as $fieldAlias => $val) {
4156 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4157 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4158 ||
($attach != 'relative' &&
4159 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4165 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4166 in_array($this->_params
[$fieldAlias . '_op'], ['nll', 'nnll'])
4177 * Check for empty order_by configurations and remove them.
4179 * Also set template to hide them.
4181 * @param array $formValues
4183 public function preProcessOrderBy(&$formValues) {
4184 // Object to show/hide form elements
4185 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4187 $_showHide->addShow('optionField_1');
4189 // Cycle through order_by options; skip any empty ones, and hide them as well
4192 if (!empty($formValues['order_bys'])) {
4193 foreach ($formValues['order_bys'] as $order_by) {
4194 if ($order_by['column'] && $order_by['column'] != '-') {
4195 $_showHide->addShow('optionField_' . $n);
4196 $orderBys[$n] = $order_by;
4201 for ($i = $n; $i <= 5; $i++
) {
4203 $_showHide->addHide('optionField_' . $i);
4207 // overwrite order_by options with modified values
4208 if (!empty($orderBys)) {
4209 $formValues['order_bys'] = $orderBys;
4212 $formValues['order_bys'] = [1 => ['column' => '-']];
4215 // assign show/hide data to template
4216 $_showHide->addToTemplate();
4220 * Check if table name has columns in SELECT clause.
4222 * @param string $tableName
4223 * Name of table (index of $this->_columns array).
4227 public function isTableSelected($tableName) {
4228 return in_array($tableName, $this->selectedTables());
4232 * Check if table name has columns in WHERE or HAVING clause.
4234 * @param string $tableName
4235 * Name of table (index of $this->_columns array).
4239 public function isTableFiltered($tableName) {
4240 // Cause the array to be generated if not previously done.
4241 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4242 $this->selectedTables();
4244 return in_array($tableName, $this->filteredTables
);
4248 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4250 * If the array is unset it will be built.
4255 public function selectedTables() {
4256 if (!$this->_selectedTables
) {
4257 $orderByColumns = [];
4258 if (array_key_exists('order_bys', $this->_params
) &&
4259 is_array($this->_params
['order_bys'])
4261 foreach ($this->_params
['order_bys'] as $orderBy) {
4262 $orderByColumns[] = $orderBy['column'];
4266 foreach ($this->_columns
as $tableName => $table) {
4267 if (array_key_exists('fields', $table)) {
4268 foreach ($table['fields'] as $fieldName => $field) {
4269 if (!empty($field['required']) ||
4270 !empty($this->_params
['fields'][$fieldName])
4272 $this->_selectedTables
[] = $tableName;
4277 if (array_key_exists('order_bys', $table)) {
4278 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4279 if (in_array($orderByName, $orderByColumns)) {
4280 $this->_selectedTables
[] = $tableName;
4285 if (array_key_exists('filters', $table)) {
4286 foreach ($table['filters'] as $filterName => $filter) {
4287 if (!empty($this->_params
["{$filterName}_value"])
4288 ||
!empty($this->_params
["{$filterName}_relative"])
4289 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4291 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4294 $this->_selectedTables
[] = $tableName;
4295 $this->filteredTables
[] = $tableName;
4302 return $this->_selectedTables
;
4306 * Add campaign fields.
4307 * @param string $entityTable
4308 * @param bool $groupBy
4309 * Add GroupBy? Not appropriate for detail report.
4310 * @param bool $orderBy
4311 * Add OrderBy? Not appropriate for detail report.
4312 * @param bool $filters
4315 public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) {
4316 // Check if CiviCampaign is a) enabled and b) has active campaigns
4317 $config = CRM_Core_Config
::singleton();
4318 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents
);
4319 if ($campaignEnabled) {
4320 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE);
4321 // If we have a campaign, build out the relevant elements
4322 if (!empty($getCampaigns['campaigns'])) {
4323 $this->campaigns
= $getCampaigns['campaigns'];
4324 asort($this->campaigns
);
4325 $this->_columns
[$entityTable]['fields']['campaign_id'] = ['title' => ts('Campaign'), 'default' => 'false'];
4327 $this->_columns
[$entityTable]['filters']['campaign_id'] = [
4328 'title' => ts('Campaign'),
4329 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4330 'options' => $this->campaigns
,
4331 'type' => CRM_Utils_Type
::T_INT
,
4336 $this->_columns
[$entityTable]['group_bys']['campaign_id'] = ['title' => ts('Campaign')];
4340 $this->_columns
[$entityTable]['order_bys']['campaign_id'] = ['title' => ts('Campaign')];
4347 * Add address fields.
4349 * @deprecated - use getAddressColumns which is a more accurate description
4350 * and also accepts an array of options rather than a long list
4352 * adding address fields to construct function in reports
4354 * @param bool $groupBy
4355 * Add GroupBy? Not appropriate for detail report.
4356 * @param bool $orderBy
4357 * Add GroupBy? Not appropriate for detail report.
4358 * @param bool $filters
4359 * @param array $defaults
4362 * address fields for construct clause
4364 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = ['country_id' => TRUE]) {
4365 $defaultAddressFields = [
4366 'street_address' => ts('Street Address'),
4367 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4368 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4369 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4370 'street_number' => ts('Street Number'),
4371 'street_name' => ts('Street Name'),
4372 'street_unit' => ts('Street Unit'),
4373 'city' => ts('City'),
4374 'postal_code' => ts('Postal Code'),
4375 'postal_code_suffix' => ts('Postal Code Suffix'),
4376 'country_id' => ts('Country'),
4377 'state_province_id' => ts('State/Province'),
4378 'county_id' => ts('County'),
4381 'civicrm_address' => [
4382 'dao' => 'CRM_Core_DAO_Address',
4385 'title' => ts('Address Name'),
4386 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4390 'grouping' => 'location-fields',
4393 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4394 $addressFields['civicrm_address']['fields'][$fieldName] = [
4395 'title' => $fieldLabel,
4396 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4400 $street_address_filters = $general_address_filters = [];
4402 // Address filter depends on whether street address parsing is enabled.
4404 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4407 if ($addressOptions['street_address_parsing']) {
4408 $street_address_filters = [
4409 'street_number' => [
4410 'title' => ts('Street Number'),
4411 'type' => CRM_Utils_Type
::T_INT
,
4412 'name' => 'street_number',
4415 'title' => ts('Street Name'),
4416 'name' => 'street_name',
4417 'type' => CRM_Utils_Type
::T_STRING
,
4422 $street_address_filters = [
4423 'street_address' => [
4424 'title' => ts('Street Address'),
4425 'type' => CRM_Utils_Type
::T_STRING
,
4426 'name' => 'street_address',
4430 $general_address_filters = [
4432 'title' => ts('Postal Code'),
4433 'type' => CRM_Utils_Type
::T_STRING
,
4434 'name' => 'postal_code',
4437 'title' => ts('City'),
4438 'type' => CRM_Utils_Type
::T_STRING
,
4442 'name' => 'country_id',
4443 'title' => ts('Country'),
4444 'type' => CRM_Utils_Type
::T_INT
,
4445 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4446 'options' => CRM_Core_PseudoConstant
::country(),
4448 'state_province_id' => [
4449 'name' => 'state_province_id',
4450 'title' => ts('State/Province'),
4451 'type' => CRM_Utils_Type
::T_INT
,
4452 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4456 'name' => 'county_id',
4457 'title' => ts('County'),
4458 'type' => CRM_Utils_Type
::T_INT
,
4459 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4464 $addressFields['civicrm_address']['filters'] = array_merge(
4465 $street_address_filters,
4466 $general_address_filters);
4469 $addressFields['civicrm_address']['order_bys'] = [
4470 'street_name' => ['title' => ts('Street Name')],
4471 'street_number' => ['title' => ts('Odd / Even Street Number')],
4472 'street_address' => NULL,
4474 'postal_code' => NULL,
4479 $addressFields['civicrm_address']['group_bys'] = [
4480 'street_address' => NULL,
4482 'postal_code' => NULL,
4483 'state_province_id' => [
4484 'title' => ts('State/Province'),
4487 'title' => ts('Country'),
4490 'title' => ts('County'),
4494 return $addressFields;
4498 * Do AlterDisplay processing on Address Fields.
4499 * If there are multiple address field values then
4500 * on basis of provided separator the code values are translated into respective labels
4503 * @param array $rows
4504 * @param int $rowNum
4505 * @param string $baseUrl
4506 * @param string $linkText
4507 * @param string $separator
4511 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4512 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4513 $entryFound = FALSE;
4515 'civicrm_address_country_id' => 'country',
4516 'civicrm_address_county_id' => 'county',
4517 'civicrm_address_state_province_id' => 'stateProvince',
4519 foreach ($columnMap as $fieldName => $fnName) {
4520 if (array_key_exists($fieldName, $row)) {
4521 if ($values = $row[$fieldName]) {
4522 $values = (array) explode($separator, $values);
4523 $rows[$rowNum][$fieldName] = [];
4524 $addressField = $fnName == 'stateProvince' ?
'state' : $fnName;
4525 foreach ($values as $value) {
4526 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant
::$fnName($value);
4528 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4530 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4531 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4532 $criteriaQueryParams,
4533 str_replace('civicrm_address_', '', $fieldName),
4534 str_replace('civicrm_address_', '', $fieldName),
4535 implode(',', $values)
4536 ), $this->_absoluteUrl
, $this->_id
4538 $rows[$rowNum]["{$fieldName}_link"] = $url;
4539 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", [1 => $linkText, 2 => $addressField]);
4550 * Do AlterDisplay processing on Address Fields.
4553 * @param array $rows
4554 * @param int $rowNum
4555 * @param string $baseUrl
4556 * @param string $linkText
4560 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4561 $entryFound = FALSE;
4562 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4563 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4564 $addLinks = ['gender_id' => 'Gender'];
4565 foreach (['prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language'] as $fieldName) {
4566 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4567 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4568 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4570 foreach ($rowValues as $rowValue) {
4572 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4575 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4576 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4577 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4584 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4586 foreach ($yesNoFields as $fieldName) {
4587 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4588 // Since these are essentially 'negative fields' it feels like it
4589 // makes sense to only highlight the exceptions hence no 'No'.
4590 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4595 // Handle employer id
4596 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4597 $employerId = $row['civicrm_contact_employer_id'];
4599 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact
::displayName($employerId);
4600 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
4601 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4610 * Adjusts dates passed in to YEAR() for fiscal year.
4612 * @param string $fieldName
4616 public function fiscalYearOffset($fieldName) {
4617 $config = CRM_Core_Config
::singleton();
4618 $fy = $config->fiscalYearStart
;
4619 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4620 ($fy['d'] == 1 && $fy['M'] == 1)
4622 return "YEAR( $fieldName )";
4624 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4625 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4629 * Add Address into From Table if required.
4631 * @deprecated use joinAddressFromContact
4632 * (left here in case extensions use it).
4634 public function addAddressFromClause() {
4635 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinAddressFromContact');
4636 // include address field if address column is to be included
4637 if ((isset($this->_addressField
) &&
4638 $this->_addressField
4640 $this->isTableSelected('civicrm_address')
4643 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4644 ON ({$this->_aliases['civicrm_contact']}.id =
4645 {$this->_aliases['civicrm_address']}.contact_id) AND
4646 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4651 * Add Phone into From Table if required.
4653 * @deprecated use joinPhoneFromContact
4654 * (left here in case extensions use it).
4656 public function addPhoneFromClause() {
4657 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinPhoneFromContact');
4658 // include address field if address column is to be included
4659 if ($this->isTableSelected('civicrm_phone')) {
4661 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4662 ON ({$this->_aliases['civicrm_contact']}.id =
4663 {$this->_aliases['civicrm_phone']}.contact_id) AND
4664 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4669 * Add Address into From Table if required.
4671 * Prefix will be added to both tables as
4672 * it is assumed you are using it to get address of a secondary contact.
4674 * @param string $prefix
4675 * @param array $extra Additional options.
4676 * Not currently used in core but may be used in override extensions.
4678 protected function joinAddressFromContact($prefix = '', $extra = []) {
4679 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4680 $isJoinRequired = $this->_addressField
;
4681 foreach ($addressTables as $addressTable) {
4682 if ($this->isTableSelected($prefix . $addressTable)) {
4683 $isJoinRequired = TRUE;
4686 if ($isJoinRequired) {
4688 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4689 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4690 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id) AND
4691 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4696 * Add Country into From Table if required.
4698 * Prefix will be added to both tables as
4699 * it is assumed you are using it to get address of a secondary contact.
4701 * @param string $prefix
4702 * @param array $extra Additional options.
4703 * Not currently used in core but may be used in override extensions.
4705 protected function joinCountryFromAddress($prefix = '', $extra = []) {
4706 // include country field if country column is to be included
4707 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4708 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4709 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4712 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4713 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id AND
4714 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4719 * Add Phone into From Table if required.
4721 * Prefix will be added to both tables as
4722 * it is assumed you are using it to get address of a secondary contact.
4724 * @param string $prefix
4725 * @param array $extra Additional options.
4726 * Not currently used in core but may be used in override extensions.
4728 protected function joinPhoneFromContact($prefix = '', $extra = []) {
4729 // include phone field if phone column is to be included
4730 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4732 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4733 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id AND
4734 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4739 * Add Email into From Table if required.
4741 * Prefix will be added to both tables as
4742 * it is assumed you are using it to get address of a secondary contact.
4744 * @param string $prefix
4745 * @param array $extra Additional options.
4746 * Not currently used in core but may be used in override extensions.
4748 protected function joinEmailFromContact($prefix = '', $extra = []) {
4749 // include email field if email column is to be included
4750 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4752 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4753 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id AND
4754 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1) ";
4759 * Add Financial Transaction into From Table if required.
4761 public function addFinancialTrxnFromClause() {
4762 if ($this->isTableSelected('civicrm_financial_trxn')) {
4764 LEFT JOIN civicrm_entity_financial_trxn eftcc
4765 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4766 eftcc.entity_table = 'civicrm_contribution')
4767 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4768 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4773 * Get phone columns to add to array.
4775 * @param array $options
4776 * - prefix Prefix to add to table (in case of more than one instance of the table)
4777 * - prefix_label Label to give columns from this phone table instance
4780 * phone columns definition
4782 public function getPhoneColumns($options = []) {
4785 'prefix_label' => '',
4788 $options = array_merge($defaultOptions, $options);
4791 $options['prefix'] . 'civicrm_phone' => [
4792 'dao' => 'CRM_Core_DAO_Phone',
4794 $options['prefix'] . 'phone' => [
4795 'title' => $options['prefix_label'] . ts('Phone'),
4805 * Get a standard set of contact fields.
4806 * @deprecated - use getColumns('Contact') instead
4809 public function getBasicContactFields() {
4812 'title' => ts('Contact Name'),
4817 'no_display' => TRUE,
4821 'title' => ts('Contact Prefix'),
4824 'title' => ts('First Name'),
4827 'title' => ts('Nick Name'),
4830 'title' => ts('Middle Name'),
4833 'title' => ts('Last Name'),
4836 'title' => ts('Contact Suffix'),
4838 'postal_greeting_display' => ['title' => ts('Postal Greeting')],
4839 'email_greeting_display' => ['title' => ts('Email Greeting')],
4840 'addressee_display' => ['title' => ts('Addressee')],
4842 'title' => ts('Contact Type'),
4844 'contact_sub_type' => [
4845 'title' => ts('Contact Subtype'),
4848 'title' => ts('Gender'),
4851 'title' => ts('Birth Date'),
4854 'title' => ts('Age'),
4855 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4858 'title' => ts('Contact Job title'),
4860 'organization_name' => [
4861 'title' => ts('Organization Name'),
4863 'external_identifier' => [
4864 'title' => ts('Contact identifier from external system'),
4866 'do_not_email' => [],
4867 'do_not_phone' => [],
4868 'do_not_mail' => [],
4871 'is_deceased' => [],
4872 'preferred_language' => [],
4874 'title' => ts('Current Employer'),
4880 * Get a standard set of contact filters.
4882 * @param array $defaults
4886 public function getBasicContactFilters($defaults = []) {
4889 'title' => ts('Contact Name'),
4892 'title' => ts('Contact Source'),
4893 'type' => CRM_Utils_Type
::T_STRING
,
4896 'title' => ts('Contact ID'),
4897 'no_display' => TRUE,
4900 'title' => ts('Gender'),
4901 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4902 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4905 'title' => ts('Birth Date'),
4906 'operatorType' => CRM_Report_Form
::OP_DATE
,
4909 'title' => ts('Contact Type'),
4911 'contact_sub_type' => [
4912 'title' => ts('Contact Subtype'),
4914 'modified_date' => [
4915 'title' => ts('Contact Modified'),
4916 'operatorType' => CRM_Report_Form
::OP_DATE
,
4917 'type' => CRM_Utils_Type
::T_DATE
,
4920 'title' => ts('Deceased'),
4921 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4922 'default' => CRM_Utils_Array
::value('deceased', $defaults, 0),
4925 'title' => ts('Do not email'),
4926 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4929 'title' => ts('Do not phone'),
4930 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4933 'title' => ts('Do not mail'),
4934 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4937 'title' => ts('Do not SMS'),
4938 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4941 'title' => ts('Do not bulk email'),
4942 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4944 'preferred_language' => [
4945 'title' => ts('Preferred Language'),
4948 'no_display' => TRUE,
4950 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4956 * Add contact to group.
4958 * @param int $groupID
4960 public function add2group($groupID) {
4961 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4962 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4963 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4964 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4965 $sql = str_replace('WITH ROLLUP', '', $sql);
4966 $dao = CRM_Core_DAO
::executeQuery($sql);
4969 // Add resulting contacts to group
4970 while ($dao->fetch()) {
4971 if ($dao->addtogroup_contact_id
) {
4972 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4976 if (!empty($contact_ids)) {
4977 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4978 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4981 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4987 * Show charts on print screen.
4989 public static function uploadChartImage() {
4990 // upload strictly for '.png' images
4991 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4992 if (preg_match('/\.png$/', $name)) {
4994 // Get the RAW .png from the input.
4995 $httpRawPostData = file_get_contents("php://input");
4997 // prepare the directory
4998 $config = CRM_Core_Config
::singleton();
5000 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
5002 if (!file_exists($defaultPath)) {
5003 mkdir($defaultPath, 0777, TRUE);
5006 // full path to the saved image including filename
5007 $destination = $defaultPath . $name;
5010 $jfh = fopen($destination, 'w') or die("can't open file");
5011 fwrite($jfh, $httpRawPostData);
5013 CRM_Utils_System
::civiExit();
5018 * Apply common settings to entityRef fields.
5020 * @param array $field
5021 * @param string $table
5023 public function setEntityRefDefaults(&$field, $table) {
5024 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : [];
5025 $field['attributes'] +
= [
5026 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
5028 'placeholder' => ts('- select -'),
5033 * Add link fields to the row.
5035 * Function adds the _link & _hover fields to the row.
5038 * @param string $baseUrl
5039 * @param string $linkText
5040 * @param string $value
5041 * @param string $fieldName
5042 * @param string $tablePrefix
5043 * @param string $fieldLabel
5047 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
5048 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
5049 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
5050 "reset=1&force=1&{$criteriaQueryParams}&" .
5051 $fieldName . "_op=in&{$fieldName}_value={$value}",
5052 $this->_absoluteUrl
, $this->_id
5054 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
5055 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
5056 [1 => $linkText, 2 => $fieldLabel]
5061 * Get label for show results buttons.
5065 public function getResultsLabel() {
5066 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
5067 return $showResultsLabel;
5071 * Determine the output mode from the url or input.
5074 * - pdf : Render as pdf
5075 * - csv : Render as csv
5076 * - print : Render in print format
5077 * - save : save the report and display the new report
5078 * - copy : save the report as a new instance and display that.
5079 * - group : go to the add to group screen.
5081 * Potentially chart variations could also be included but the complexity
5082 * is that we might print a bar chart as a pdf.
5084 protected function setOutputMode() {
5085 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
5088 CRM_Core_DAO
::$_nullObject,
5090 CRM_Utils_Array
::value('task', $this->_params
)
5092 // if contacts are added to group
5093 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
5094 $this->_outputMode
= 'group';
5096 if (isset($this->_params
['task'])) {
5097 unset($this->_params
['task']);
5102 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5105 * @param $columnName
5107 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5108 // add new column with date value for the datetime field
5109 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5110 CRM_Core_DAO
::executeQuery($tempQuery);
5111 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5112 CRM_Core_DAO
::executeQuery($updateQuery);
5113 $this->_selectClauses
[] = "{$columnName}_date";
5114 $this->_select
.= ", {$columnName}_date";
5115 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5116 unset($this->_sections
["{$columnName}"]);
5117 $this->assign('sections', $this->_sections
);
5121 * Get an array of the columns that have been selected for display.
5125 public function getSelectColumns() {
5126 $selectColumns = [];
5127 foreach ($this->_columns
as $tableName => $table) {
5128 if (array_key_exists('fields', $table)) {
5129 foreach ($table['fields'] as $fieldName => $field) {
5130 if (!empty($field['required']) ||
5131 !empty($this->_params
['fields'][$fieldName])
5134 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5139 return $selectColumns;
5143 * Add location tables to the query if they are used for filtering.
5145 * This is for when we are running the query separately for filtering and retrieving display fields.
5147 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5148 if ($this->isTableFiltered('civicrm_email')) {
5150 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5151 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5152 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5154 if ($this->isTableFiltered('civicrm_phone')) {
5156 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5157 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5158 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5160 if ($this->isTableFiltered('civicrm_address')) {
5162 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5163 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5164 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5169 * Set the base table for the FROM clause.
5171 * Sets up the from clause, allowing for the possibility it might be a
5172 * temp table pre-filtered by groups if a group filter is in use.
5174 * @param string $baseTable
5175 * @param string $field
5176 * @param null $tableAlias
5178 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5180 $tableAlias = $this->_aliases
[$baseTable];
5182 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5183 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5184 $this->_from
.= " {$this->_aclFrom} ";
5188 * Join the temp table contacting contacts who are members of the filtered groups.
5190 * If we are using an IN filter we use an inner join, otherwise a left join.
5192 * @param string $baseTable
5193 * @param string $field
5194 * @param string $tableAlias
5196 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5197 if ($this->groupTempTable
) {
5198 if ($this->_params
['gid_op'] == 'in') {
5199 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5200 ON group_temp_table.id = $tableAlias.{$field} ";
5204 LEFT JOIN $this->groupTempTable group_temp_table
5205 ON $tableAlias.{$field} = group_temp_table.id ";
5211 * Get all labels for fields that are used in a group concat.
5213 * @param string $options
5214 * comma separated option values.
5215 * @param string $baoName
5216 * The BAO name for the field.
5217 * @param string $fieldName
5218 * The name of the field for which labels should be retrieved.
5222 public function getLabels($options, $baoName, $fieldName) {
5223 $types = explode(',', $options);
5225 foreach ($types as $value) {
5226 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5228 return implode(', ', array_filter($labels));
5232 * Add statistics columns.
5234 * If a group by is in play then add columns for the statistics fields.
5236 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5237 * column header field.
5239 * @param array $field
5240 * @param string $tableName
5241 * @param string $fieldName
5242 * @param array $select
5246 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5247 foreach ($field['statistics'] as $stat => $label) {
5248 $alias = "{$tableName}_{$fieldName}_{$stat}";
5249 switch (strtolower($stat)) {
5252 $select[] = "$stat({$field['dbAlias']}) as $alias";
5253 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5254 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5255 $this->_statFields
[$label] = $alias;
5256 $this->_selectAliases
[] = $alias;
5260 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5261 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5262 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5263 $this->_statFields
[$label] = $alias;
5264 $this->_selectAliases
[] = $alias;
5267 case 'count_distinct':
5268 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5269 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5270 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5271 $this->_statFields
[$label] = $alias;
5272 $this->_selectAliases
[] = $alias;
5276 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5277 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5278 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5279 $this->_statFields
[$label] = $alias;
5280 $this->_selectAliases
[] = $alias;
5288 * Add a basic field to the select clause.
5290 * @param string $tableName
5291 * @param string $fieldName
5292 * @param array $field
5293 * @param string $select
5296 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5297 $alias = "{$tableName}_{$fieldName}";
5298 $select[] = "{$field['dbAlias']} as $alias";
5299 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
5300 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
5301 $this->_selectAliases
[] = $alias;
5308 * @param array $table
5309 * @param string $tableName
5314 protected function setTableAlias($table, $tableName) {
5315 if (!isset($table['alias'])) {
5316 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5320 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5323 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5324 return $this->_aliases
[$tableName];
5328 * Function to add columns to reports.
5330 * This is ported from extended reports, which also adds join filters to the options.
5332 * @param string $type
5333 * @param array $options
5334 * - prefix - A string to prepend to the table name
5335 * - prefix_label A string to prepend to the fields
5336 * - fields (bool) - should the fields for this table be made available
5337 * - group_by (bool) - should the group bys for this table be made available.
5338 * - order_by (bool) - should the group bys for this table be made available.
5339 * - filters (bool) - should the filters for this table by made available.
5340 * - fields_defaults (array) array of fields that should be displayed by default.
5341 * - filters_defaults (array) array of fields that should be filtered by default.
5342 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5343 * - join_fields (array) fields available from join (requires additional custom code).
5344 * - group_by_defaults (array) array of group bys that should be applied by default.
5345 * - order_by_defaults (array) array of order bys that should be applied by default.
5346 * - custom_fields (array) array of entity types for custom fields (not usually required).
5347 * - contact_type (string) optional restriction on contact type for some tables.
5348 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5352 protected function getColumns($type, $options = []) {
5355 'prefix_label' => '',
5357 'group_bys' => FALSE,
5358 'order_bys' => TRUE,
5360 'join_filters' => FALSE,
5361 'fields_defaults' => [],
5362 'filters_defaults' => [],
5363 'group_bys_defaults' => [],
5364 'order_bys_defaults' => [],
5366 $options = array_merge($defaultOptions, $options);
5368 $fn = 'get' . $type . 'Columns';
5369 return $this->$fn($options);
5373 * Get columns for contact table.
5375 * @param array $options
5379 protected function getContactColumns($options = []) {
5381 'custom_fields' => ['Individual', 'Contact', 'Organization'],
5382 'fields_defaults' => ['display_name', 'id'],
5383 'order_bys_defaults' => ['sort_name ASC'],
5384 'contact_type' => NULL,
5387 $options = array_merge($defaultOptions, $options);
5389 $tableAlias = $options['prefix'] . 'contact';
5392 $options['prefix'] . 'display_name' => [
5393 'name' => 'display_name',
5394 'title' => $options['prefix_label'] . ts('Contact Name'),
5395 'is_fields' => TRUE,
5397 $options['prefix'] . 'sort_name' => [
5398 'name' => 'sort_name',
5399 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5400 'is_fields' => TRUE,
5401 'is_filters' => TRUE,
5402 'is_order_bys' => TRUE,
5404 $options['prefix'] . 'id' => [
5406 'title' => $options['prefix_label'] . ts('Contact ID'),
5407 'alter_display' => 'alterContactID',
5408 'type' => CRM_Utils_Type
::T_INT
,
5409 'is_order_bys' => TRUE,
5410 'is_group_bys' => TRUE,
5411 'is_fields' => TRUE,
5412 'is_filters' => TRUE,
5414 $options['prefix'] . 'external_identifier' => [
5415 'name' => 'external_identifier',
5416 'title' => $options['prefix_label'] . ts('External ID'),
5417 'type' => CRM_Utils_Type
::T_INT
,
5418 'is_fields' => TRUE,
5420 $options['prefix'] . 'contact_type' => [
5421 'title' => $options['prefix_label'] . ts('Contact Type'),
5422 'name' => 'contact_type',
5423 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5424 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5425 'is_fields' => TRUE,
5426 'is_filters' => TRUE,
5427 'is_group_bys' => TRUE,
5429 $options['prefix'] . 'contact_sub_type' => [
5430 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5431 'name' => 'contact_sub_type',
5432 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5433 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5434 'is_fields' => TRUE,
5435 'is_filters' => TRUE,
5436 'is_group_bys' => TRUE,
5438 $options['prefix'] . 'is_deleted' => [
5439 'title' => $options['prefix_label'] . ts('Is deleted'),
5440 'name' => 'is_deleted',
5441 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5442 'is_fields' => FALSE,
5443 'is_filters' => TRUE,
5444 'is_group_bys' => FALSE,
5446 $options['prefix'] . 'external_identifier' => [
5447 'title' => $options['prefix_label'] . ts('Contact identifier from external system'),
5448 'name' => 'external_identifier',
5449 'is_fields' => TRUE,
5450 'is_filters' => FALSE,
5451 'is_group_bys' => FALSE,
5452 'is_order_bys' => TRUE,
5454 $options['prefix'] . 'preferred_language' => [
5455 'title' => $options['prefix_label'] . ts('Preferred Language'),
5456 'name' => 'preferred_language',
5457 'is_fields' => TRUE,
5458 'is_filters' => TRUE,
5459 'is_group_bys' => TRUE,
5460 'is_order_bys' => TRUE,
5464 'postal_greeting_display' => 'Postal Greeting',
5465 'email_greeting_display' => 'Email Greeting',
5466 'addressee_display' => 'Addressee',
5467 ] as $field => $title) {
5468 $spec[$options['prefix'] . $field] = [
5469 'title' => $options['prefix_label'] . ts($title),
5471 'is_fields' => TRUE,
5472 'is_filters' => FALSE,
5473 'is_group_bys' => FALSE,
5476 foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'is_opt_out'] as $field) {
5477 $spec[$options['prefix'] . $field] = [
5479 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5480 'is_fields' => TRUE,
5481 'is_filters' => TRUE,
5482 'is_group_bys' => FALSE,
5485 $individualFields = [
5486 $options['prefix'] . 'first_name' => [
5487 'name' => 'first_name',
5488 'title' => $options['prefix_label'] . ts('First Name'),
5489 'is_fields' => TRUE,
5490 'is_filters' => TRUE,
5491 'is_order_bys' => TRUE,
5493 $options['prefix'] . 'middle_name' => [
5494 'name' => 'middle_name',
5495 'title' => $options['prefix_label'] . ts('Middle Name'),
5496 'is_fields' => TRUE,
5498 $options['prefix'] . 'last_name' => [
5499 'name' => 'last_name',
5500 'title' => $options['prefix_label'] . ts('Last Name'),
5501 'default_order' => 'ASC',
5502 'is_fields' => TRUE,
5504 $options['prefix'] . 'nick_name' => [
5505 'name' => 'nick_name',
5506 'title' => $options['prefix_label'] . ts('Nick Name'),
5507 'is_fields' => TRUE,
5509 $options['prefix'] . 'prefix_id' => [
5510 'name' => 'prefix_id',
5511 'title' => $options['prefix_label'] . ts('Prefix'),
5512 'options' => CRM_Contact_BAO_Contact
::buildOptions('prefix_id'),
5513 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5514 'is_fields' => TRUE,
5515 'is_filters' => TRUE,
5517 $options['prefix'] . 'suffix_id' => [
5518 'name' => 'suffix_id',
5519 'title' => $options['prefix_label'] . ts('Suffix'),
5520 'options' => CRM_Contact_BAO_Contact
::buildOptions('suffix_id'),
5521 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5522 'is_fields' => TRUE,
5523 'is_filters' => TRUE,
5525 $options['prefix'] . 'gender_id' => [
5526 'name' => 'gender_id',
5527 'title' => $options['prefix_label'] . ts('Gender'),
5528 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5529 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5530 'is_fields' => TRUE,
5531 'is_filters' => TRUE,
5534 'title' => $options['prefix_label'] . ts('Birth Date'),
5535 'operatorType' => CRM_Report_Form
::OP_DATE
,
5536 'type' => CRM_Utils_Type
::T_DATE
,
5537 'is_fields' => TRUE,
5538 'is_filters' => TRUE,
5541 'title' => $options['prefix_label'] . ts('Age'),
5542 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5543 'type' => CRM_Utils_Type
::T_INT
,
5544 'is_fields' => TRUE,
5546 $options['prefix'] . 'is_deceased' => [
5547 'title' => $options['prefix_label'] . ts('Is deceased'),
5548 'name' => 'is_deceased',
5549 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5550 'is_fields' => FALSE,
5551 'is_filters' => TRUE,
5552 'is_group_bys' => FALSE,
5554 $options['prefix'] . 'job_title' => [
5555 'name' => 'job_title',
5556 'is_fields' => TRUE,
5557 'is_filters' => FALSE,
5558 'is_group_bys' => FALSE,
5560 $options['prefix'] . 'employer_id' => [
5561 'title' => $options['prefix_label'] . ts('Current Employer'),
5562 'type' => CRM_Utils_Type
::T_INT
,
5563 'name' => 'employer_id',
5564 'is_fields' => TRUE,
5565 'is_filters' => FALSE,
5566 'is_group_bys' => TRUE,
5569 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5570 $spec = array_merge($spec, $individualFields);
5573 if (!empty($options['custom_fields'])) {
5574 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = [
5575 'extends' => $options['custom_fields'],
5576 'title' => $options['prefix_label'],
5577 'filters' => $options['filters'],
5578 'prefix' => $options['prefix'],
5579 'prefix_label' => $options['prefix_label'],
5583 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5587 * Get address columns to add to array.
5589 * @param array $options
5590 * - prefix Prefix to add to table (in case of more than one instance of the table)
5591 * - prefix_label Label to give columns from this address table instance
5592 * - group_bys enable these fields for group by - default false
5593 * - order_bys enable these fields for order by
5594 * - filters enable these fields for filtering
5596 * @return array address columns definition
5598 protected function getAddressColumns($options = []) {
5601 'prefix_label' => '',
5603 'group_bys' => FALSE,
5604 'order_bys' => TRUE,
5606 'join_filters' => FALSE,
5607 'fields_defaults' => [],
5608 'filters_defaults' => [],
5609 'group_bys_defaults' => [],
5610 'order_bys_defaults' => [],
5613 $options = array_merge($defaultOptions, $options);
5614 $defaults = $this->getDefaultsFromOptions($options);
5615 $tableAlias = $options['prefix'] . 'address';
5618 $options['prefix'] . 'name' => [
5619 'title' => ts($options['prefix_label'] . 'Address Name'),
5621 'is_fields' => TRUE,
5623 $options['prefix'] . 'street_number' => [
5624 'name' => 'street_number',
5625 'title' => ts($options['prefix_label'] . 'Street Number'),
5627 'is_fields' => TRUE,
5629 $options['prefix'] . 'odd_street_number' => [
5630 'title' => ts('Odd / Even Street Number'),
5631 'name' => 'odd_street_number',
5632 'type' => CRM_Utils_Type
::T_INT
,
5633 'no_display' => TRUE,
5635 'dbAlias' => '(address_civireport.street_number % 2)',
5636 'is_fields' => TRUE,
5637 'is_order_bys' => TRUE,
5639 $options['prefix'] . 'street_name' => [
5640 'name' => 'street_name',
5641 'title' => ts($options['prefix_label'] . 'Street Name'),
5643 'is_fields' => TRUE,
5644 'is_filters' => TRUE,
5645 'operator' => 'like',
5646 'is_order_bys' => TRUE,
5648 $options['prefix'] . 'street_address' => [
5649 'title' => ts($options['prefix_label'] . 'Street Address'),
5650 'name' => 'street_address',
5651 'is_fields' => TRUE,
5652 'is_filters' => TRUE,
5653 'is_group_bys' => TRUE,
5655 $options['prefix'] . 'supplemental_address_1' => [
5656 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 1'),
5657 'name' => 'supplemental_address_1',
5658 'is_fields' => TRUE,
5660 $options['prefix'] . 'supplemental_address_2' => [
5661 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 2'),
5662 'name' => 'supplemental_address_2',
5663 'is_fields' => TRUE,
5665 $options['prefix'] . 'supplemental_address_3' => [
5666 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 3'),
5667 'name' => 'supplemental_address_3',
5668 'is_fields' => TRUE,
5670 $options['prefix'] . 'street_number' => [
5671 'name' => 'street_number',
5672 'title' => ts($options['prefix_label'] . 'Street Number'),
5674 'is_order_bys' => TRUE,
5675 'is_filters' => TRUE,
5676 'is_fields' => TRUE,
5678 $options['prefix'] . 'street_unit' => [
5679 'name' => 'street_unit',
5680 'title' => ts($options['prefix_label'] . 'Street Unit'),
5682 'is_fields' => TRUE,
5684 $options['prefix'] . 'city' => [
5685 'title' => ts($options['prefix_label'] . 'City'),
5687 'operator' => 'like',
5688 'is_fields' => TRUE,
5689 'is_filters' => TRUE,
5690 'is_group_bys' => TRUE,
5691 'is_order_bys' => TRUE,
5693 $options['prefix'] . 'postal_code' => [
5694 'title' => ts($options['prefix_label'] . 'Postal Code'),
5695 'name' => 'postal_code',
5697 'is_fields' => TRUE,
5698 'is_filters' => TRUE,
5699 'is_group_bys' => TRUE,
5700 'is_order_bys' => TRUE,
5702 $options['prefix'] . 'postal_code_suffix' => [
5703 'title' => ts($options['prefix_label'] . 'Postal Code Suffix'),
5704 'name' => 'postal_code',
5706 'is_fields' => TRUE,
5707 'is_filters' => TRUE,
5708 'is_group_bys' => TRUE,
5709 'is_order_bys' => TRUE,
5711 $options['prefix'] . 'county_id' => [
5712 'title' => ts($options['prefix_label'] . 'County'),
5713 'alter_display' => 'alterCountyID',
5714 'name' => 'county_id',
5715 'type' => CRM_Utils_Type
::T_INT
,
5716 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5717 'options' => CRM_Core_PseudoConstant
::county(),
5718 'is_fields' => TRUE,
5719 'is_filters' => TRUE,
5720 'is_group_bys' => TRUE,
5722 $options['prefix'] . 'state_province_id' => [
5723 'title' => ts($options['prefix_label'] . 'State/Province'),
5724 'alter_display' => 'alterStateProvinceID',
5725 'name' => 'state_province_id',
5726 'type' => CRM_Utils_Type
::T_INT
,
5727 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5728 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5729 'is_fields' => TRUE,
5730 'is_filters' => TRUE,
5731 'is_group_bys' => TRUE,
5733 $options['prefix'] . 'country_id' => [
5734 'title' => ts($options['prefix_label'] . 'Country'),
5735 'alter_display' => 'alterCountryID',
5736 'name' => 'country_id',
5737 'is_fields' => TRUE,
5738 'is_filters' => TRUE,
5739 'is_group_bys' => TRUE,
5740 'type' => CRM_Utils_Type
::T_INT
,
5741 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5742 'options' => CRM_Core_PseudoConstant
::country(),
5744 $options['prefix'] . 'location_type_id' => [
5745 'name' => 'is_primary',
5746 'title' => ts($options['prefix_label'] . 'Location Type'),
5747 'type' => CRM_Utils_Type
::T_INT
,
5748 'is_fields' => TRUE,
5749 'alter_display' => 'alterLocationTypeID',
5751 $options['prefix'] . 'id' => [
5752 'title' => ts($options['prefix_label'] . 'ID'),
5754 'is_fields' => TRUE,
5756 $options['prefix'] . 'is_primary' => [
5757 'name' => 'is_primary',
5758 'title' => ts($options['prefix_label'] . 'Primary Address?'),
5759 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5760 'is_fields' => TRUE,
5763 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5767 * Build the columns.
5769 * The normal report class needs you to remember to do a few things that are often erratic
5771 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5772 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5773 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5774 * means any saved filters / fields on saved report instances. This will mean that matching names from
5775 * different tables may be ambigious, but it will smooth any code transition.
5776 * - note that it assumes the value being passed in is the actual table field name
5778 * 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
5779 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5781 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5782 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5783 * the core classes can start to move towards that.
5785 * @param array $specs
5786 * @param string $tableName
5787 * @param string $daoName
5788 * @param string $tableAlias
5789 * @param array $defaults
5790 * @param array $options
5794 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = [], $options = []) {
5796 $tableAlias = str_replace('civicrm_', '', $tableName);
5798 $types = ['filters', 'group_bys', 'order_bys', 'join_filters'];
5799 $columns = [$tableName => array_fill_keys($types, [])];
5800 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5801 $columns[$tableName]['dao'] = $daoName;
5802 $columns[$tableName]['alias'] = $tableAlias;
5804 foreach ($specs as $specName => $spec) {
5805 if (empty($spec['name'])) {
5806 $spec['name'] = $specName;
5809 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5810 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5811 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5812 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5813 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5816 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5817 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5820 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5821 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5824 foreach ($types as $type) {
5825 if ($options[$type] && !empty($spec['is_' . $type])) {
5826 $columns[$tableName][$type][$fieldAlias] = $spec;
5827 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5828 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5837 * Store group bys into array - so we can check elsewhere what is grouped.
5839 protected function storeGroupByArray() {
5841 if (!CRM_Utils_Array
::value('group_bys', $this->_params
)
5842 ||
!is_array($this->_params
['group_bys'])) {
5843 $this->_params
['group_bys'] = [];
5846 foreach ($this->_columns
as $tableName => $table) {
5847 $table = $this->_columns
[$tableName];
5848 if (array_key_exists('group_bys', $table)) {
5849 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5850 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5851 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5852 if (!empty($field['chart'])) {
5853 $this->assign('chartSupported', TRUE);
5856 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5857 !empty($this->_params
['group_bys_freq'][$fieldName])
5860 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5862 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5865 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
5868 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_{$this->_params['group_bys_freq'][$fieldName]} FROM {$field['dbAlias']})";
5873 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5874 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5889 protected function getDefaultsFromOptions($options) {
5891 'fields_defaults' => $options['fields_defaults'],
5892 'filters_defaults' => $options['filters_defaults'],
5893 'group_bys_defaults' => $options['group_bys_defaults'],
5894 'order_bys_defaults' => $options['order_bys_defaults'],
5900 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5902 * Full group by mode dictates that a field must either be in the group by function or
5903 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5906 * @param string $tableName
5907 * @param string $fieldName
5908 * @param string $field
5911 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5912 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5913 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5914 $label = CRM_Utils_Array
::value('title', $field);
5915 $alias = "{$tableName}_{$fieldName}";
5916 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5917 $this->_selectAliases
[] = $alias;
5918 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5919 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5921 return "({$field['dbAlias']}) as $alias";
5927 * Generate clause for the selected filter.
5929 * @param array $field
5930 * Field specification
5931 * @param string $fieldName
5935 * Relevant where clause.
5937 protected function generateFilterClause($field, $fieldName) {
5938 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
5939 if (CRM_Utils_Array
::value('operatorType', $field) ==
5940 CRM_Report_Form
::OP_MONTH
5942 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5943 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
5944 if (is_array($value) && !empty($value)) {
5945 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
5950 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
5951 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
5952 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
5953 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
5954 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
5955 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
5959 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5961 return $this->whereClause($field,
5963 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
5964 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
5965 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)