3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 public $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
156 * Has the report been optimised for group filtering.
158 * The functionality for group filtering has been improved but not
159 * all reports have been adjusted to take care of it.
161 * This property exists to highlight the reports which are still using the
162 * slow method & allow group filtering to still work for them until they
165 * In order to protect extensions we have to default to TRUE - but I have
166 * separately marked every class with a groupFilter in the hope that will trigger
167 * people to fix them as they touch them.
173 protected $groupFilterNotOptimised = TRUE;
180 public $_navigation = array();
182 public $_drilldownReport = array();
185 * Array of tabs to display on report.
187 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
189 * $this->tabs['OrderBy'] = array(
190 * 'title' => ts('Sorting'),
191 * 'tpl' => 'OrderBy',
192 * 'div_label' => 'order-by',
197 protected $tabs = array();
200 * Should we add paging.
204 protected $addPaging = TRUE;
206 protected $isForceGroupBy = FALSE;
208 protected $groupConcatTested = FALSE;
211 * An attribute for checkbox/radio form field layout
215 protected $_fourColumnAttribute = array(
216 '</td><td width="25%">',
217 '</td><td width="25%">',
218 '</td><td width="25%">',
222 protected $_force = 1;
224 protected $_params = NULL;
225 protected $_formValues = NULL;
226 protected $_instanceValues = NULL;
228 protected $_instanceForm = FALSE;
229 protected $_criteriaForm = FALSE;
231 protected $_instanceButtonName = NULL;
232 protected $_createNewButtonName = NULL;
233 protected $_printButtonName = NULL;
234 protected $_pdfButtonName = NULL;
235 protected $_csvButtonName = NULL;
236 protected $_groupButtonName = NULL;
237 protected $_chartButtonName = NULL;
238 protected $_csvSupported = TRUE;
239 protected $_add2groupSupported = TRUE;
240 protected $_groups = NULL;
241 protected $_grandFlag = FALSE;
242 protected $_rowsFound = NULL;
243 protected $_selectAliases = array();
244 protected $_rollup = NULL;
247 * Table containing list of contact IDs within the group filter.
251 protected $groupTempTable = '';
256 protected $_aliases = array();
272 protected $_limit = NULL;
275 * This can be set to specify a limit to the number of rows
276 * Since it is currently envisaged as part of the api usage it is only being applied
277 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
278 * of the code (see limit() fn.
282 protected $_limitValue = NULL;
285 * This can be set to specify row offset
286 * See notes on _limitValue
289 protected $_offsetValue = NULL;
293 protected $_sections = NULL;
294 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
295 protected $_absoluteUrl = FALSE;
298 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
302 protected $_storeResultSet = FALSE;
305 * When _storeResultSet Flag is set use this var to store result set in form of array
309 protected $_resultSet = array();
312 * To what frequency group-by a date column
316 protected $_groupByDateFreq = array(
318 'YEARWEEK' => 'Week',
319 'QUARTER' => 'Quarter',
324 * Variables to hold the acl inner join and where clause
326 protected $_aclFrom = NULL;
327 protected $_aclWhere = NULL;
330 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
332 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
336 protected $_selectedTables = array();
339 * Array of DAO tables having columns included in WHERE or HAVING clause
343 protected $filteredTables;
346 * Output mode e.g 'print', 'csv', 'pdf'.
350 protected $_outputMode;
353 * Format of any chart in use.
355 * (it's unclear if this could be merged with outputMode at this stage)
361 public $_having = NULL;
362 public $_select = NULL;
363 public $_selectClauses = array();
364 public $_columnHeaders = array();
365 public $_orderBy = NULL;
366 public $_orderByFields = array();
367 public $_orderByArray = array();
369 * Array of clauses to group by.
373 protected $_groupByArray = array();
374 public $_groupBy = NULL;
375 public $_whereClauses = array();
376 public $_havingClauses = array();
379 * DashBoardRowCount Dashboard row count
382 public $_dashBoardRowCount;
385 * Is this being called without a form controller (ie. the report is being render outside the normal form
386 * - e.g the api is retrieving the rows
389 public $noController = FALSE;
392 * Variable to hold the currency alias
394 protected $_currencyColumn = NULL;
399 protected $_interval;
404 protected $_sendmail;
417 * @var string Report description.
419 public $_description;
422 * @var bool Is an address field selected.
423 * This was intended to determine if the address table should be joined in
424 * The isTableSelected function is now preferred for this purpose
426 protected $_addressField;
429 * @var bool Is an email field selected.
430 * This was intended to determine if the email table should be joined in
431 * The isTableSelected function is now preferred for this purpose
433 protected $_emailField;
436 * @var bool Is a phone field selected.
437 * This was intended to determine if the phone table should be joined in
438 * The isTableSelected function is now preferred for this purpose
440 protected $_phoneField;
443 * @var bool Create new report instance? (or update existing) on save.
445 protected $_createNew;
448 * When a grand total row has calculated the status we pop it off to here.
450 * This allows us to access it from the stats function and avoid recalculating.
452 protected $rollupRow = array();
455 * @var string Database attributes - character set and collation
457 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
460 * SQL being run in this report.
462 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
470 * An instruction not to add a Group By.
472 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
474 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
475 * such as in pivot charts when no row header is set
479 protected $noGroupBy = FALSE;
482 * SQL being run in this report as an array.
484 * The sql in the report is stored in this variable in order to be returned to api & test calls.
492 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
495 public $optimisedForOnlyFullGroupBy = TRUE;
499 public function __construct() {
500 parent
::__construct();
502 $this->addClass('crm-report-form');
504 if ($this->_tagFilter
) {
505 $this->buildTagFilter();
507 if ($this->_exposeContactID
) {
508 if (array_key_exists('civicrm_contact', $this->_columns
)) {
509 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
511 'title' => ts('Contact ID'),
517 if ($this->_groupFilter
) {
518 $this->buildGroupFilter();
521 // Get all custom groups
522 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
524 // Get the custom groupIds for which the user has VIEW permission
525 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
526 // and addCustomDataToColumns() will allow access to all custom groups.
527 $permCustomGroupIds = array();
528 if (!CRM_Core_Permission
::check('access all custom data')) {
529 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
530 // do not allow custom data for reports if user doesn't have
531 // permission to access custom data.
532 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
533 $this->_customGroupExtends
= array();
537 // merge custom data columns to _columns list, if any
538 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
540 // add / modify display columns, filters ..etc
541 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
543 //assign currencyColumn variable to tpl
544 $this->assign('currencyColumn', $this->_currencyColumn
);
548 * Shared pre-process function.
550 * If overriding preProcess function this should still be called.
554 public function preProcessCommon() {
555 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
557 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
559 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
561 $this->assign('section', $this->_section
);
562 CRM_Core_Region
::instance('page-header')->add(array(
563 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
565 if (!$this->noController
) {
566 $this->setID($this->get('instanceId'));
569 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
571 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
575 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
576 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
577 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
581 $this->assign('instanceId', $this->_id
);
582 $params = array('id' => $this->_id
);
583 $this->_instanceValues
= array();
584 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
586 $this->_instanceValues
588 if (empty($this->_instanceValues
)) {
589 CRM_Core_Error
::fatal("Report could not be loaded.");
591 $this->_title
= $this->_instanceValues
['title'];
592 if (!empty($this->_instanceValues
['permission']) &&
593 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
594 CRM_Core_Permission
::check('administer Reports')
597 CRM_Utils_System
::permissionDenied();
598 CRM_Utils_System
::civiExit();
601 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
603 $this->_formValues
= unserialize($formValues);
606 $this->_formValues
= NULL;
609 $this->setOutputMode();
611 if ($this->_outputMode
== 'copy') {
612 $this->_createNew
= TRUE;
613 $this->_params
= $this->_formValues
;
614 $this->_params
['view_mode'] = 'criteria';
615 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
616 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
617 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
619 // Do not pass go. Do not collect another chance to re-run the same query.
620 CRM_Report_Form_Instance
::postProcess($this);
623 // lets always do a force if reset is found in the url.
624 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
625 // in the comment line above these 2.
626 if (!empty($_REQUEST['reset'])
627 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
632 $this->assign('mode', 'instance');
634 elseif (!$this->noController
) {
635 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
636 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
637 if (($instanceCount > 0) && $optionValueID) {
638 $this->assign('instanceUrl',
639 CRM_Utils_System
::url('civicrm/report/list',
640 "reset=1&ovid=$optionValueID"
644 if ($optionValueID) {
645 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
649 $this->assign('mode', 'template');
652 // lets display the Report Settings section
653 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
655 // Do not display Report Settings section if administer Reports permission is absent OR
656 // if report instance is reserved and administer reserved reports absent
657 if (!CRM_Core_Permission
::check('administer Reports') ||
658 ($this->_instanceValues
['is_reserved'] &&
659 !CRM_Core_Permission
::check('administer reserved reports'))
661 $this->_instanceForm
= FALSE;
664 $this->assign('criteriaForm', FALSE);
665 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
666 if (CRM_Core_Permission
::check('administer Reports') ||
667 CRM_Core_Permission
::check('access Report Criteria')
669 if (!$this->_instanceValues
['is_reserved'] ||
670 CRM_Core_Permission
::check('administer reserved reports')
672 $this->assign('criteriaForm', TRUE);
673 $this->_criteriaForm
= TRUE;
677 // Special permissions check for private instance if it's not the current contact instance
679 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
680 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
681 if (!CRM_Core_Permission
::check('access all private reports')) {
682 $this->_instanceForm
= FALSE;
683 $this->assign('criteriaForm', FALSE);
687 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
688 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
689 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
690 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
696 public function addBreadCrumb() {
700 'title' => ts('Report Templates'),
701 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
705 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
709 * Pre process function.
711 * Called prior to build form.
713 public function preProcess() {
714 $this->preProcessCommon();
717 $this->addBreadCrumb();
720 foreach ($this->_columns
as $tableName => $table) {
721 $this->setTableAlias($table, $tableName);
723 $expFields = array();
724 // higher preference to bao object
725 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
728 if (method_exists($daoOrBaoName, 'exportableFields')) {
729 $expFields = $daoOrBaoName::exportableFields();
732 $expFields = $daoOrBaoName::export();
736 $doNotCopy = array('required', 'default');
738 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
739 foreach ($fieldGroups as $fieldGrp) {
740 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
741 foreach ($table[$fieldGrp] as $fieldName => $field) {
742 // $name is the field name used to reference the BAO/DAO export fields array
743 $name = isset($field['name']) ?
$field['name'] : $fieldName;
745 // Sometimes the field name key in the BAO/DAO export fields array is
746 // different from the actual database field name.
747 // Unset $field['name'] so that actual database field name can be obtained
748 // from the BAO/DAO export fields array.
749 unset($field['name']);
751 if (array_key_exists($name, $expFields)) {
752 foreach ($doNotCopy as $dnc) {
753 // unset the values we don't want to be copied.
754 unset($expFields[$name][$dnc]);
757 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
760 foreach ($expFields[$name] as $property => $val) {
761 if (!array_key_exists($property, $field)) {
762 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
769 if (!empty($field['no_repeat'])) {
770 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
772 if (!empty($field['no_display'])) {
773 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
776 // set alias = table-name, unless already set
777 $alias = isset($field['alias']) ?
$field['alias'] : (
778 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
780 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
782 // set name = fieldName, unless already set
783 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
784 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
787 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
788 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
791 // set dbAlias = alias.name, unless already set
792 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
793 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
795 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
798 // a few auto fills for filters
799 if ($fieldGrp == 'filters') {
800 // fill operator types
801 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
802 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
803 case CRM_Utils_Type
::T_MONEY
:
804 case CRM_Utils_Type
::T_FLOAT
:
805 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
808 case CRM_Utils_Type
::T_INT
:
809 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
812 case CRM_Utils_Type
::T_DATE
:
813 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
816 case CRM_Utils_Type
::T_BOOLEAN
:
817 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
818 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
819 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
830 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
832 // with multiple options operator-type is generally multi-select
833 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
834 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
836 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
843 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
844 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
847 $this->_columns
[$tableName]['metadata'][$fieldName] = array_merge($this->_columns
[$tableName][$fieldGrp][$fieldName], $this->_columns
[$tableName]['metadata'][$fieldName]);
853 // copy filters to a separate handy variable
854 if (array_key_exists('filters', $table)) {
855 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
858 if (array_key_exists('group_bys', $table)) {
859 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
862 if (array_key_exists('fields', $table)) {
863 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
868 $this->setDefaultValues(FALSE);
871 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
872 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
873 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
874 CRM_Report_Utils_Get
::processChart($this->_defaults
);
877 $this->_formValues
= $this->_defaults
;
878 $this->postProcess();
883 * Set default values.
885 * @param bool $freeze
889 public function setDefaultValues($freeze = TRUE) {
890 $freezeGroup = array();
892 // FIXME: generalizing form field naming conventions would reduce
893 // Lots of lines below.
894 foreach ($this->_columns
as $tableName => $table) {
895 if (array_key_exists('fields', $table)) {
896 foreach ($table['fields'] as $fieldName => $field) {
897 if (empty($field['no_display'])) {
898 if (!empty($field['required'])) {
900 $this->_defaults
['fields'][$fieldName] = 1;
903 // find element object, so that we could use quickform's freeze method
904 // for required elements
905 $obj = $this->getElementFromGroup("fields", $fieldName);
907 $freezeGroup[] = $obj;
911 elseif (isset($field['default'])) {
912 $this->_defaults
['fields'][$fieldName] = $field['default'];
918 if (array_key_exists('group_bys', $table)) {
919 foreach ($table['group_bys'] as $fieldName => $field) {
920 if (isset($field['default'])) {
921 if (!empty($field['frequency'])) {
922 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
924 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
928 if (array_key_exists('filters', $table)) {
929 foreach ($table['filters'] as $fieldName => $field) {
930 if (isset($field['default'])) {
931 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
933 if (is_array($field['default'])) {
934 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
935 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
936 $this->_defaults
["{$fieldName}_relative"] = 0;
939 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
943 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
944 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
945 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
947 $this->_defaults
["{$fieldName}_value"] = $field['default'];
950 //assign default value as "in" for multiselect
951 //operator, To freeze the select element
952 if (CRM_Utils_Array
::value('operatorType', $field) ==
953 CRM_Report_Form
::OP_MULTISELECT
955 $this->_defaults
["{$fieldName}_op"] = 'in';
957 if (CRM_Utils_Array
::value('operatorType', $field) ==
958 CRM_Report_Form
::OP_ENTITYREF
960 $this->_defaults
["{$fieldName}_op"] = 'in';
962 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
963 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
965 $this->_defaults
["{$fieldName}_op"] = 'mhas';
967 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
968 $this->_defaults
["{$fieldName}_op"] = $op;
974 empty($this->_formValues
['order_bys']) &&
975 (array_key_exists('order_bys', $table) &&
976 is_array($table['order_bys']))
978 if (!array_key_exists('order_bys', $this->_defaults
)) {
979 $this->_defaults
['order_bys'] = array();
981 foreach ($table['order_bys'] as $fieldName => $field) {
982 if (!empty($field['default']) ||
!empty($field['default_order']) ||
983 CRM_Utils_Array
::value('default_is_section', $field) ||
984 !empty($field['default_weight'])
987 'column' => $fieldName,
988 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
989 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
992 if (!empty($field['default_weight'])) {
993 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
996 array_unshift($this->_defaults
['order_bys'], $order_by);
1002 foreach ($this->_options
as $fieldName => $field) {
1003 if (isset($field['default'])) {
1004 $this->_defaults
['options'][$fieldName] = $field['default'];
1009 if (!empty($this->_submitValues
)) {
1010 $this->preProcessOrderBy($this->_submitValues
);
1013 $this->preProcessOrderBy($this->_defaults
);
1016 // lets finish freezing task here itself
1017 if (!empty($freezeGroup)) {
1018 foreach ($freezeGroup as $elem) {
1023 if ($this->_formValues
) {
1024 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1027 if ($this->_instanceValues
) {
1028 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1031 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1033 return $this->_defaults
;
1037 * Get element from group.
1039 * @param string $group
1040 * @param string $grpFieldName
1044 public function getElementFromGroup($group, $grpFieldName) {
1045 $eleObj = $this->getElement($group);
1046 foreach ($eleObj->_elements
as $index => $obj) {
1047 if ($grpFieldName == $obj->_attributes
['name']) {
1055 * Setter for $_params.
1057 * @param array $params
1059 public function setParams($params) {
1060 $this->_params
= $params;
1066 * @param int $instanceID
1068 public function setID($instanceID) {
1069 $this->_id
= $instanceID;
1073 * Setter for $_force.
1075 * @param bool $isForce
1077 public function setForce($isForce) {
1078 $this->_force
= $isForce;
1082 * Setter for $_limitValue.
1084 * @param int $_limitValue
1086 public function setLimitValue($_limitValue) {
1087 $this->_limitValue
= $_limitValue;
1091 * Setter for $_offsetValue.
1093 * @param int $_offsetValue
1095 public function setOffsetValue($_offsetValue) {
1096 $this->_offsetValue
= $_offsetValue;
1100 * Setter for $addPaging.
1102 * @param bool $value
1104 public function setAddPaging($value) {
1105 $this->addPaging
= $value;
1109 * Getter for $_defaultValues.
1113 public function getDefaultValues() {
1114 return $this->_defaults
;
1118 * Add columns to report.
1120 public function addColumns() {
1123 foreach ($this->_columns
as $tableName => $table) {
1124 if (array_key_exists('fields', $table)) {
1125 foreach ($table['fields'] as $fieldName => $field) {
1127 if (empty($field['no_display'])) {
1128 foreach (array('table', 'field') as $var) {
1129 if (!empty($
{$var}['grouping'])) {
1130 if (!is_array($
{$var}['grouping'])) {
1131 $tableName = $
{$var}['grouping'];
1134 $tableName = array_keys($
{$var}['grouping']);
1135 $tableName = $tableName[0];
1136 $groupTitle = array_values($
{$var}['grouping']);
1137 $groupTitle = $groupTitle[0];
1142 if (!$groupTitle && isset($table['group_title'])) {
1143 $groupTitle = $table['group_title'];
1144 // Having a group_title is secret code for being a custom group
1145 // which cryptically translates to needing an accordion.
1146 // here we make that explicit.
1147 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1150 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1151 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1152 $colGroups[$tableName]['group_title'] = $groupTitle;
1154 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1160 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1161 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1163 if (!empty($colGroups)) {
1164 $this->tabs
['FieldSelection'] = array(
1165 'title' => ts('Columns'),
1166 'tpl' => 'FieldSelection',
1167 'div_label' => 'col-groups',
1170 // Note this assignment is only really required in buildForm. It is being 'over-called'
1171 // to reduce risk of being missed due to overridden functions.
1172 $this->assign('tabs', $this->tabs
);
1175 $this->assign('colGroups', $colGroups);
1179 * Add filters to report.
1181 public function addFilters() {
1182 $filters = $filterGroups = array();
1185 foreach ($this->_filters
as $table => $attributes) {
1186 if (isset($this->_columns
[$table]['group_title'])) {
1187 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1188 // which magically means to 'display in an accordian'
1189 // here we make this explicit.
1190 $filterGroups[$table] = array(
1191 'group_title' => $this->_columns
[$table]['group_title'],
1192 'use_accordian_for_field_selection' => TRUE,
1196 foreach ($attributes as $fieldName => $field) {
1197 // get ready with option value pair
1198 // @ 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
1200 $operations = $this->getOperationPair(
1201 CRM_Utils_Array
::value('operatorType', $field),
1204 $filters[$table][$fieldName] = $field;
1206 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1207 case CRM_Report_Form
::OP_MONTH
:
1208 if (!array_key_exists('options', $field) ||
1209 !is_array($field['options']) ||
empty($field['options'])
1211 // If there's no option list for this filter, define one.
1212 $field['options'] = array(
1214 2 => ts('February'),
1221 9 => ts('September'),
1222 10 => ts('October'),
1223 11 => ts('November'),
1224 12 => ts('December'),
1226 // Add this option list to this column _columns. This is
1227 // required so that filter statistics show properly.
1228 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1230 case CRM_Report_Form
::OP_MULTISELECT
:
1231 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1232 // assume a multi-select field
1233 if (!empty($field['options']) ||
1234 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1236 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1237 if (count($operations) <= 1) {
1240 if ($fieldName == 'state_province_id' ||
1241 $fieldName == 'county_id'
1243 $this->addChainSelect($fieldName . '_value', array(
1250 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1251 'style' => 'min-width:250px',
1252 'class' => 'crm-select2 huge',
1254 'placeholder' => ts('- select -'),
1260 case CRM_Report_Form
::OP_SELECT
:
1261 // assume a select field
1262 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1263 if (!empty($field['options'])) {
1264 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1268 case CRM_Report_Form
::OP_ENTITYREF
:
1269 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1270 $this->setEntityRefDefaults($field, $table);
1271 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1274 case CRM_Report_Form
::OP_DATE
:
1275 // build datetime fields
1276 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1280 case CRM_Report_Form
::OP_DATETIME
:
1281 // build datetime fields
1282 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1286 case CRM_Report_Form
::OP_INT
:
1287 case CRM_Report_Form
::OP_FLOAT
:
1288 // and a min value input box
1289 $this->add('text', "{$fieldName}_min", ts('Min'));
1290 // and a max value input box
1291 $this->add('text', "{$fieldName}_max", ts('Max'));
1293 // default type is string
1294 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1295 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1297 // we need text box for value input
1298 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1303 if (!empty($filters)) {
1304 $this->tabs
['Filters'] = array(
1305 'title' => ts('Filters'),
1307 'div_label' => 'set-filters',
1310 $this->assign('filters', $filters);
1311 $this->assign('filterGroups', $filterGroups);
1315 * Function to assign the tabs to the template in the correct order.
1317 * We want the tabs to wind up in this order (if not overridden).
1325 protected function assignTabs() {
1333 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1334 $order = array_merge($order, $this->tabs
);
1335 $this->assign('tabs', $order);
1339 * The intent is to add a tab for developers to view the sql.
1341 * Currently using dpm.
1343 * @param string $sql
1345 public function addToDeveloperTab($sql) {
1346 if (!CRM_Core_Permission
::check('view report sql')) {
1349 $this->tabs
['Developer'] = array(
1350 'title' => ts('Developer'),
1351 'tpl' => 'Developer',
1352 'div_label' => 'set-developer',
1355 $this->assignTabs();
1356 $this->sqlArray
[] = $sql;
1357 foreach ($this->sqlArray
as $sql) {
1358 foreach (array('LEFT JOIN') as $term) {
1359 $sql = str_replace($term, '<br>  ' . $term, $sql);
1361 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1362 $sql = str_replace($term, '<br><br>' . $term, $sql);
1364 $this->sqlFormattedArray
[] = $sql;
1365 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1370 * Add options defined in $this->_options to the report.
1372 public function addOptions() {
1373 if (!empty($this->_options
)) {
1374 // FIXME: For now lets build all elements as checkboxes.
1375 // Once we clear with the format we can build elements based on type
1377 foreach ($this->_options
as $fieldName => $field) {
1380 if ($field['type'] == 'select') {
1381 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1383 elseif ($field['type'] == 'checkbox') {
1384 $options[$field['title']] = $fieldName;
1385 $this->addCheckBox($fieldName, NULL,
1387 NULL, NULL, NULL, $this->_fourColumnAttribute
1392 if (!empty($this->_options
) &&
1394 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1396 $this->tabs
['ReportOptions'] = array(
1397 'title' => ts('Display Options'),
1398 'tpl' => 'ReportOptions',
1399 'div_label' => 'other-options',
1402 $this->assign('otherOptions', $this->_options
);
1406 * Add chart options to the report.
1408 public function addChartOptions() {
1409 if (!empty($this->_charts
)) {
1410 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1411 $this->assign('charts', $this->_charts
);
1412 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1417 * Add group by options to the report.
1419 public function addGroupBys() {
1420 $options = $freqElements = array();
1422 foreach ($this->_columns
as $tableName => $table) {
1423 if (array_key_exists('group_bys', $table)) {
1424 foreach ($table['group_bys'] as $fieldName => $field) {
1425 if (!empty($field) && empty($field['no_display'])) {
1426 $options[$field['title']] = $fieldName;
1427 if (!empty($field['frequency'])) {
1428 $freqElements[$field['title']] = $fieldName;
1434 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1435 NULL, NULL, NULL, $this->_fourColumnAttribute
1437 $this->assign('groupByElements', $options);
1438 if (!empty($options)) {
1439 $this->tabs
['GroupBy'] = array(
1440 'title' => ts('Grouping'),
1442 'div_label' => 'group-by-elements',
1446 foreach ($freqElements as $name) {
1447 $this->addElement('select', "group_bys_freq[$name]",
1448 ts('Frequency'), $this->_groupByDateFreq
1454 * Add data for order by tab.
1456 public function addOrderBys() {
1458 foreach ($this->_columns
as $tableName => $table) {
1460 // Report developer may define any column to order by; include these as order-by options.
1461 if (array_key_exists('order_bys', $table)) {
1462 foreach ($table['order_bys'] as $fieldName => $field) {
1463 if (!empty($field)) {
1464 $options[$fieldName] = $field['title'];
1469 // Add searchable custom fields as order-by options, if so requested
1470 // (These are already indexed, so allowing to order on them is cheap.)
1472 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1473 array_key_exists('extends', $table) && !empty($table['extends'])
1475 foreach ($table['fields'] as $fieldName => $field) {
1476 if (empty($field['no_display'])) {
1477 $options[$fieldName] = $field['title'];
1485 $this->assign('orderByOptions', $options);
1486 if (!empty($options)) {
1487 $this->tabs
['OrderBy'] = array(
1488 'title' => ts('Sorting'),
1490 'div_label' => 'order-by-elements',
1494 if (!empty($options)) {
1496 '-' => ' - none - ',
1498 for ($i = 1; $i <= 5; $i++
) {
1499 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1500 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1501 'ASC' => ts('Ascending'),
1502 'DESC' => ts('Descending'),
1504 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1505 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1511 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1513 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1514 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1517 public function buildInstanceAndButtons() {
1518 CRM_Report_Form_Instance
::buildForm($this);
1519 $this->_actionButtonName
= $this->getButtonName('submit');
1520 $this->addTaskMenu($this->getActions($this->_id
));
1522 $this->assign('instanceForm', $this->_instanceForm
);
1524 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1525 $permission = CRM_Core_Permission
::getPermission();
1526 if ($permission == CRM_Core_Permission
::EDIT
&&
1527 $this->_add2groupSupported
1529 $this->addElement('select', 'groups', ts('Group'),
1530 array('' => ts('Add Contacts to Group')) +
1531 CRM_Core_PseudoConstant
::nestedGroup(),
1532 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1534 $this->assign('group', TRUE);
1537 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1539 $this->addChartOptions();
1540 $showResultsLabel = $this->getResultsLabel();
1541 $this->addButtons(array(
1544 'name' => $showResultsLabel,
1545 'isDefault' => TRUE,
1552 * Has this form been submitted already?
1556 public function resultsDisplayed() {
1557 $buttonName = $this->controller
->getButtonName();
1558 return ($buttonName ||
$this->_outputMode
);
1562 * Get the actions for this report instance.
1564 * @param int $instanceId
1568 protected function getActions($instanceId) {
1569 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1570 if (empty($instanceId)) {
1571 $actions['report_instance.save'] = array(
1572 'title' => ts('Create Report'),
1574 'is_confirm' => TRUE,
1575 'confirm_title' => ts('Create Report'),
1576 'confirm_refresh_fields' => json_encode(array(
1577 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1578 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1584 if (!$this->_csvSupported
) {
1585 unset($actions['report_instance.csv']);
1592 * Main build form function.
1594 public function buildQuickForm() {
1595 $this->addColumns();
1597 $this->addFilters();
1599 $this->addOptions();
1601 $this->addGroupBys();
1603 $this->addOrderBys();
1605 $this->buildInstanceAndButtons();
1607 // Add form rule for report.
1608 if (is_callable(array(
1612 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1614 $this->assignTabs();
1618 * A form rule function for custom data.
1620 * The rule ensures that fields selected in group_by if any) should only be the ones
1621 * present in display/select fields criteria;
1622 * note: works if and only if any custom field selected in group_by.
1624 * @param array $fields
1625 * @param array $ignoreFields
1629 public function customDataFormRule($fields, $ignoreFields = array()) {
1631 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1632 !empty($fields['group_bys'])
1634 foreach ($this->_columns
as $tableName => $table) {
1635 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1636 substr($tableName, 0, 12) == 'custom_value') &&
1637 !empty($this->_columns
[$tableName]['fields'])
1639 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1640 if (array_key_exists($fieldName, $fields['group_bys']) &&
1641 !array_key_exists($fieldName, $fields['fields'])
1643 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1645 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1646 foreach ($fields['fields'] as $fld => $val) {
1647 if (!array_key_exists($fld, $fields['group_bys']) &&
1648 !in_array($fld, $ignoreFields)
1650 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1662 * Get operators to display on form.
1664 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1666 * @param string $type
1667 * @param string $fieldName
1671 public function getOperationPair($type = "string", $fieldName = NULL) {
1672 // FIXME: At some point we should move these key-val pairs
1673 // to option_group and option_value table.
1675 case CRM_Report_Form
::OP_INT
:
1676 case CRM_Report_Form
::OP_FLOAT
:
1679 'lte' => ts('Is less than or equal to'),
1680 'gte' => ts('Is greater than or equal to'),
1681 'bw' => ts('Is between'),
1682 'eq' => ts('Is equal to'),
1683 'lt' => ts('Is less than'),
1684 'gt' => ts('Is greater than'),
1685 'neq' => ts('Is not equal to'),
1686 'nbw' => ts('Is not between'),
1687 'nll' => ts('Is empty (Null)'),
1688 'nnll' => ts('Is not empty (Null)'),
1692 case CRM_Report_Form
::OP_SELECT
:
1694 'eq' => ts('Is equal to'),
1698 case CRM_Report_Form
::OP_MONTH
:
1699 case CRM_Report_Form
::OP_MULTISELECT
:
1700 case CRM_Report_Form
::OP_ENTITYREF
:
1703 'in' => ts('Is one of'),
1704 'notin' => ts('Is not one of'),
1708 case CRM_Report_Form
::OP_DATE
:
1711 'nll' => ts('Is empty (Null)'),
1712 'nnll' => ts('Is not empty (Null)'),
1716 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1717 // use this operator for the values, concatenated with separator. For e.g if
1718 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1720 'mhas' => ts('Is one of'),
1721 'mnot' => ts('Is not one of'),
1728 'has' => ts('Contains'),
1729 'sw' => ts('Starts with'),
1730 'ew' => ts('Ends with'),
1731 'nhas' => ts('Does not contain'),
1732 'eq' => ts('Is equal to'),
1733 'neq' => ts('Is not equal to'),
1734 'nll' => ts('Is empty (Null)'),
1735 'nnll' => ts('Is not empty (Null)'),
1742 * Build the tag filter field to display on the filters tab.
1744 public function buildTagFilter() {
1745 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1746 if (!empty($contactTags)) {
1747 $this->_columns
['civicrm_tag'] = array(
1748 'dao' => 'CRM_Core_DAO_Tag',
1752 'title' => ts('Tag'),
1753 'type' => CRM_Utils_Type
::T_INT
,
1755 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1756 'options' => $contactTags,
1764 * Adds group filters to _columns (called from _Construct).
1766 public function buildGroupFilter() {
1767 $this->_columns
['civicrm_group']['filters'] = array(
1769 'name' => 'group_id',
1770 'title' => ts('Group'),
1771 'type' => CRM_Utils_Type
::T_INT
,
1772 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1774 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1777 if (empty($this->_columns
['civicrm_group']['dao'])) {
1778 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1780 if (empty($this->_columns
['civicrm_group']['alias'])) {
1781 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1786 * Get SQL operator from form text version.
1788 * @param string $operator
1792 public function getSQLOperator($operator = "like") {
1793 switch ($operator) {
1826 return 'IS NOT NULL';
1835 * Generate where clause.
1837 * This can be overridden in reports for special treatment of a field
1839 * @param array $field Field specifications
1840 * @param string $op Query operator (not an exact match to sql)
1841 * @param mixed $value
1845 * @return null|string
1847 public function whereClause(&$field, $op, $value, $min, $max) {
1849 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1851 // CRM-18010: Ensure type of each report filters
1853 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1860 if (($min !== NULL && strlen($min) > 0) ||
1861 ($max !== NULL && strlen($max) > 0)
1865 $min = CRM_Utils_Type
::escape($min, $type);
1867 $clauses[] = "( {$field['dbAlias']} >= $min )";
1870 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1874 $max = CRM_Utils_Type
::escape($max, $type);
1876 $clauses[] = "( {$field['dbAlias']} <= $max )";
1879 $clauses[] = "( {$field['dbAlias']} > $max )";
1883 if (!empty($clauses)) {
1885 $clause = implode(' AND ', $clauses);
1888 $clause = '(' . implode('OR', $clauses) . ')';
1896 if ($value !== NULL && strlen($value) > 0) {
1897 $value = CRM_Utils_Type
::escape($value, $type);
1898 if (strpos($value, '%') === FALSE) {
1899 $value = "'%{$value}%'";
1902 $value = "'{$value}'";
1904 $sqlOP = $this->getSQLOperator($op);
1905 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1911 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1912 $value = explode(',', $value);
1914 if ($value !== NULL && is_array($value) && count($value) > 0) {
1915 $sqlOP = $this->getSQLOperator($op);
1916 if (CRM_Utils_Array
::value('type', $field) ==
1917 CRM_Utils_Type
::T_STRING
1919 //cycle through selections and escape values
1920 foreach ($value as $key => $selection) {
1921 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1924 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1928 // for numerical values
1929 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1932 if ($op == 'notin') {
1933 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1936 $clause = "( " . $clause . " )";
1943 // multiple has or multiple not
1944 if ($value !== NULL && count($value) > 0) {
1945 $value = CRM_Utils_Type
::escapeAll($value, $type);
1946 $operator = $op == 'mnot' ?
'NOT' : '';
1947 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1948 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1954 if ($value !== NULL && strlen($value) > 0) {
1955 $value = CRM_Utils_Type
::escape($value, $type);
1956 if (strpos($value, '%') === FALSE) {
1958 $value = "'{$value}%'";
1961 $value = "'%{$value}'";
1965 $value = "'{$value}'";
1967 $sqlOP = $this->getSQLOperator($op);
1968 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1974 $sqlOP = $this->getSQLOperator($op);
1975 $clause = "( {$field['dbAlias']} $sqlOP )";
1981 //CRM-18457: some custom field passes value in array format against binary operator
1982 if (is_array($value) && count($value)) {
1987 if ($value !== NULL && $value !== '') {
1988 if (isset($field['clause'])) {
1989 // FIXME: we not doing escape here. Better solution is to use two
1990 // different types - data-type and filter-type
1991 $clause = $field['clause'];
1993 elseif (!is_array($value)) {
1994 $value = CRM_Utils_Type
::escape($value, $type);
1995 $sqlOP = $this->getSQLOperator($op);
1996 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1997 $value = "'{$value}'";
1999 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2005 if (!empty($field['group']) && $clause) {
2006 $clause = $this->whereGroupClause($field, $value, $op);
2008 elseif (!empty($field['tag']) && $clause) {
2009 // not using left join in query because if any contact
2010 // belongs to more than one tag, results duplicate
2012 $clause = $this->whereTagClause($field, $value, $op);
2014 elseif (!empty($field['membership_org']) && $clause) {
2015 $clause = $this->whereMembershipOrgClause($value, $op);
2017 elseif (!empty($field['membership_type']) && $clause) {
2018 $clause = $this->whereMembershipTypeClause($value, $op);
2024 * Get SQL where clause for a date field.
2026 * @param string $fieldName
2027 * @param string $relative
2028 * @param string $from
2030 * @param string $type
2031 * @param string $fromTime
2032 * @param string $toTime
2034 * @return null|string
2036 public function dateClause(
2038 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2041 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2042 $sqlOP = $this->getSQLOperator($relative);
2043 return "( {$fieldName} {$sqlOP} )";
2046 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2049 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2050 $clauses[] = "( {$fieldName} >= $from )";
2054 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2055 $clauses[] = "( {$fieldName} <= {$to} )";
2058 if (!empty($clauses)) {
2059 return implode(' AND ', $clauses);
2066 * Get values for from and to for date ranges.
2070 * @param bool $relative
2071 * @param string $from
2073 * @param string $fromTime
2074 * @param string $toTime
2078 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2079 if (empty($toTime)) {
2080 // odd legacy behaviour to treat NULL as 'end of the day'
2081 // recommend updating reports to call CRM_Utils_Date::getFromTo
2082 //directly (default on the function is the actual default there).
2085 return CRM_Utils_Date
::getFromTo($relative, $from, $to, $fromTime, $toTime);
2089 * Alter display of rows.
2091 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2092 * such as rendering contacts as links.
2094 * @param array $rows
2095 * Rows generated by SQL, with an array for each row.
2097 public function alterDisplay(&$rows) {
2101 * Alter the way in which custom data fields are displayed.
2103 * @param array $rows
2105 public function alterCustomDataDisplay(&$rows) {
2106 // custom code to alter rows having custom values
2107 if (empty($this->_customGroupExtends
)) {
2111 $customFields = array();
2112 $customFieldIds = array();
2113 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2114 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2115 $customFieldIds[$fieldAlias] = $fieldId;
2118 if (empty($customFieldIds)) {
2122 // skip for type date and ContactReference since date format is already handled
2124 SELECT cg.table_name, cf.id
2125 FROM civicrm_custom_field cf
2126 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2127 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2128 cg.is_active = 1 AND
2129 cf.is_active = 1 AND
2130 cf.is_searchable = 1 AND
2131 cf.data_type NOT IN ('ContactReference', 'Date') AND
2132 cf.id IN (" . implode(",", $customFieldIds) . ")";
2134 $dao = CRM_Core_DAO
::executeQuery($query);
2135 while ($dao->fetch()) {
2136 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2140 $entryFound = FALSE;
2141 foreach ($rows as $rowNum => $row) {
2142 foreach ($row as $tableCol => $val) {
2143 if (array_key_exists($tableCol, $customFields)) {
2144 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2149 // skip looking further in rows, if first row itself doesn't
2150 // have the column we need
2158 * Remove duplicate rows.
2160 * @param array $rows
2162 public function removeDuplicates(&$rows) {
2163 if (empty($this->_noRepeats
)) {
2166 $checkList = array();
2168 foreach ($rows as $key => $list) {
2169 foreach ($list as $colName => $colVal) {
2170 if (array_key_exists($colName, $checkList) &&
2171 $checkList[$colName] == $colVal
2173 $rows[$key][$colName] = "";
2175 if (in_array($colName, $this->_noRepeats
)) {
2176 $checkList[$colName] = $colVal;
2183 * Fix subtotal display.
2186 * @param array $fields
2187 * @param bool $subtotal
2189 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2190 foreach ($row as $colName => $colVal) {
2191 if (in_array($colName, $fields)) {
2193 elseif (isset($this->_columnHeaders
[$colName])) {
2195 $row[$colName] = 'Subtotal';
2199 unset($row[$colName]);
2206 * Calculate grant total.
2208 * @param array $rows
2212 public function grandTotal(&$rows) {
2213 if (!$this->_rollup ||
count($rows) == 1) {
2217 $this->moveSummaryColumnsToTheRightHandSide();
2219 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2223 $this->rollupRow
= array_pop($rows);
2225 foreach ($this->_columnHeaders
as $fld => $val) {
2226 if (!in_array($fld, $this->_statFields
)) {
2227 if (!$this->_grandFlag
) {
2228 $this->rollupRow
[$fld] = ts('Grand Total');
2229 $this->_grandFlag
= TRUE;
2232 $this->rollupRow
[$fld] = "";
2237 $this->assign('grandStat', $this->rollupRow
);
2242 * Format display output.
2244 * @param array $rows
2245 * @param bool $pager
2247 public function formatDisplay(&$rows, $pager = TRUE) {
2248 // set pager based on if any limit was applied in the query.
2253 // allow building charts if any
2254 if (!empty($this->_params
['charts']) && !empty($rows)) {
2255 $this->buildChart($rows);
2256 $this->assign('chartEnabled', TRUE);
2257 $this->_chartId
= "{$this->_params['charts']}_" .
2258 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2260 $this->assign('chartId', $this->_chartId
);
2263 // unset columns not to be displayed.
2264 foreach ($this->_columnHeaders
as $key => $value) {
2265 if (!empty($value['no_display'])) {
2266 unset($this->_columnHeaders
[$key]);
2270 // unset columns not to be displayed.
2271 if (!empty($rows)) {
2272 foreach ($this->_noDisplay
as $noDisplayField) {
2273 foreach ($rows as $rowNum => $row) {
2274 unset($this->_columnHeaders
[$noDisplayField]);
2279 // build array of section totals
2280 $this->sectionTotals();
2282 // process grand-total row
2283 $this->grandTotal($rows);
2285 // Find alter display functions.
2286 $firstRow = reset($rows);
2288 $selectedFields = array_keys($firstRow);
2289 $alterFunctions = $alterMap = $alterSpecs = array();
2290 foreach ($this->_columns
as $tableName => $table) {
2291 if (array_key_exists('metadata', $table)) {
2292 foreach ($table['metadata'] as $field => $specs) {
2293 if (in_array($tableName . '_' . $field, $selectedFields)) {
2294 if (array_key_exists('alter_display', $specs)) {
2295 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2296 $alterMap[$tableName . '_' . $field] = $field;
2297 $alterSpecs[$tableName . '_' . $field] = NULL;
2299 // Add any alters that can be intuited from the field specs.
2300 // So far only boolean but a lot more could be.
2301 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2302 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2303 $alterMap[$tableName . '_' . $field] = $field;
2304 $alterSpecs[$tableName . '_' . $field] = NULL;
2311 // Run the alter display functions
2312 foreach ($rows as $index => & $row) {
2313 foreach ($row as $selectedField => $value) {
2314 if (array_key_exists($selectedField, $alterFunctions)) {
2315 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2321 // use this method for formatting rows for display purpose.
2322 $this->alterDisplay($rows);
2323 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2325 // use this method for formatting custom rows for display purpose.
2326 $this->alterCustomDataDisplay($rows);
2332 * @param $selectedfield
2333 * @param $criteriaFieldName
2337 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2338 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2339 $row[$selectedfield . '_link'] = $url;
2340 $row[$selectedfield . '_hover'] = ts("%1 for this state.", array(
2344 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2345 if (!is_array($states)) {
2353 * @param $selectedField
2354 * @param $criteriaFieldName
2358 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2359 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2360 $row[$selectedField . '_link'] = $url;
2361 $row[$selectedField . '_hover'] = ts("%1 for this country.", array(
2364 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2365 if (!is_array($countries)) {
2373 * @param $selectedfield
2374 * @param $criteriaFieldName
2378 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2379 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2380 $row[$selectedfield . '_link'] = $url;
2381 $row[$selectedfield . '_hover'] = ts("%1 for this county.", array(
2384 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2385 if (!is_array($counties)) {
2393 * @param $selectedfield
2394 * @param $criteriaFieldName
2398 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2399 $values = $this->getLocationTypeOptions();
2400 return CRM_Utils_Array
::value($value, $values);
2410 protected function alterContactID($value, &$row, $fieldname) {
2411 $nameField = substr($fieldname, 0, -2) . 'name';
2412 static $first = TRUE;
2413 static $viewContactList = FALSE;
2415 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2418 if (!$viewContactList) {
2421 if (array_key_exists($nameField, $row)) {
2422 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2425 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2435 protected function alterBoolean($value) {
2436 $options = array(0 => ts('No'), 1 => ts('Yes'));
2437 if (isset($options[$value])) {
2438 return $options[$value];
2446 * @param array $rows
2448 public function buildChart(&$rows) {
2449 // override this method for building charts.
2452 // select() method below has been added recently (v3.3), and many of the report templates might
2453 // still be having their own select() method. We should fix them as and when encountered and move
2454 // towards generalizing the select() method below.
2457 * Generate the SELECT clause and set class variable $_select.
2459 public function select() {
2460 $select = $this->_selectAliases
= array();
2461 $this->storeGroupByArray();
2463 foreach ($this->_columns
as $tableName => $table) {
2464 if (array_key_exists('fields', $table)) {
2465 foreach ($table['fields'] as $fieldName => $field) {
2466 if ($tableName == 'civicrm_address') {
2467 // deprecated, use $this->isTableSelected.
2468 $this->_addressField
= TRUE;
2470 if ($tableName == 'civicrm_email') {
2471 $this->_emailField
= TRUE;
2473 if ($tableName == 'civicrm_phone') {
2474 $this->_phoneField
= TRUE;
2477 if (!empty($field['required']) ||
2478 !empty($this->_params
['fields'][$fieldName])
2481 // 1. In many cases we want select clause to be built in slightly different way
2482 // for a particular field of a particular type.
2483 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2485 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2486 if ($selectClause) {
2487 $select[] = $selectClause;
2491 // include statistics columns only if set
2492 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2493 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2497 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2498 if ($selectClause) {
2499 $select[] = $selectClause;
2502 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2509 // select for group bys
2510 if (array_key_exists('group_bys', $table)) {
2511 foreach ($table['group_bys'] as $fieldName => $field) {
2513 if ($tableName == 'civicrm_address') {
2514 $this->_addressField
= TRUE;
2516 if ($tableName == 'civicrm_email') {
2517 $this->_emailField
= TRUE;
2519 if ($tableName == 'civicrm_phone') {
2520 $this->_phoneField
= TRUE;
2522 // 1. In many cases we want select clause to be built in slightly different way
2523 // for a particular field of a particular type.
2524 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2526 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2527 if ($selectClause) {
2528 $select[] = $selectClause;
2532 if (!empty($this->_params
['group_bys']) &&
2533 !empty($this->_params
['group_bys'][$fieldName]) &&
2534 !empty($this->_params
['group_bys_freq'])
2536 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2538 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2539 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2540 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2541 $field['title'] = 'Week';
2545 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2546 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2547 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2548 $field['title'] = 'Year';
2552 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2553 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2554 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2555 $field['title'] = 'Month';
2559 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2560 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2561 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2562 $field['title'] = 'Quarter';
2565 // for graphs and charts -
2566 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2567 $this->_interval
= $field['title'];
2568 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2569 = $field['title'] . ' Beginning';
2570 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2571 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2573 // just to make sure these values are transferred to rows.
2574 // since we 'll need them for calculation purpose,
2575 // e.g making subtotals look nicer or graphs
2576 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2577 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2584 if (empty($select)) {
2585 // CRM-21412 Do not give fatal error on report when no fields selected
2589 $this->_selectClauses
= $select;
2590 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2594 * Build select clause for a single field.
2596 * @param string $tableName
2597 * @param string $tableKey
2598 * @param string $fieldName
2599 * @param string $field
2603 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2604 if (!empty($field['pseudofield'])) {
2605 $alias = "{$tableName}_{$fieldName}";
2606 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2607 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2608 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = CRM_Utils_Array
::value('dbAlias', $field);
2609 $this->_selectAliases
[] = $alias;
2610 return ' 1 as ' . $alias;
2616 * Build where clause.
2618 public function where() {
2619 $this->storeWhereHavingClauseArray();
2621 if (empty($this->_whereClauses
)) {
2622 $this->_where
= "WHERE ( 1 ) ";
2623 $this->_having
= "";
2626 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2629 if ($this->_aclWhere
) {
2630 $this->_where
.= " AND {$this->_aclWhere} ";
2633 if (!empty($this->_havingClauses
)) {
2634 // use this clause to construct group by clause.
2635 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2640 * Store Where clauses into an array.
2642 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2643 * temp table that may not be part of the final where clause or added
2644 * in other functions
2646 public function storeWhereHavingClauseArray() {
2647 foreach ($this->_columns
as $tableName => $table) {
2648 if (array_key_exists('filters', $table)) {
2649 foreach ($table['filters'] as $fieldName => $field) {
2650 // respect pseudofield to filter spec so fields can be marked as
2651 // not to be handled here
2652 if (!empty($field['pseudofield'])) {
2656 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2657 if (CRM_Utils_Array
::value('operatorType', $field) ==
2658 CRM_Report_Form
::OP_MONTH
2660 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2661 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2662 if (is_array($value) && !empty($value)) {
2664 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2669 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2670 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2671 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2672 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2673 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2674 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2678 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2680 $clause = $this->whereClause($field,
2682 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2683 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2684 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2689 if (!empty($clause)) {
2690 if (!empty($field['having'])) {
2691 $this->_havingClauses
[] = $clause;
2694 $this->_whereClauses
[] = $clause;
2706 public function processReportMode() {
2707 $this->setOutputMode();
2710 = CRM_Utils_Request
::retrieve(
2713 CRM_Core_DAO
::$_nullObject
2716 $this->_absoluteUrl
= FALSE;
2718 $this->assign('printOnly', FALSE);
2720 if ($this->_outputMode
== 'print' ||
2721 ($this->_sendmail
&& !$this->_outputMode
)
2723 $this->assign('printOnly', TRUE);
2725 $this->addPaging
= FALSE;
2726 $this->assign('outputMode', 'print');
2727 $this->_outputMode
= 'print';
2728 if ($this->_sendmail
) {
2729 $this->_absoluteUrl
= TRUE;
2732 elseif ($this->_outputMode
== 'pdf') {
2734 $this->addPaging
= FALSE;
2735 $this->_absoluteUrl
= TRUE;
2737 elseif ($this->_outputMode
== 'csv') {
2739 $this->_absoluteUrl
= TRUE;
2740 $this->addPaging
= FALSE;
2742 elseif ($this->_outputMode
== 'group') {
2743 $this->assign('outputMode', 'group');
2745 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2746 $this->assign('outputMode', 'create_report');
2748 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2749 $this->_createNew
= TRUE;
2752 $this->assign('outputMode', $this->_outputMode
);
2753 $this->assign('printOnly', $printOnly);
2754 // Get today's date to include in printed reports
2756 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2757 $this->assign('reportDate', $reportDate);
2762 * Post Processing function for Form.
2764 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2765 * This function is not accessed when the api calls the report.
2767 public function beginPostProcess() {
2768 $this->setParams($this->controller
->exportValues($this->_name
));
2769 if (empty($this->_params
) &&
2772 $this->setParams($this->_formValues
);
2775 // hack to fix params when submitted from dashboard, CRM-8532
2776 // fields array is missing because form building etc is skipped
2777 // in dashboard mode for report
2778 //@todo - this could be done in the dashboard no we have a setter
2779 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2780 $this->setParams($this->_formValues
);
2783 $this->processReportMode();
2785 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2786 $this->_createNew
= ($this->_outputMode
== 'copy');
2787 CRM_Report_Form_Instance
::postProcess($this);
2789 if ($this->_outputMode
== 'delete') {
2790 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2793 $this->_formValues
= $this->_params
;
2795 $this->beginPostProcessCommon();
2799 * BeginPostProcess function run in both report mode and non-report mode (api).
2801 public function beginPostProcessCommon() {
2805 * Build the report query.
2807 * @param bool $applyLimit
2811 public function buildQuery($applyLimit = TRUE) {
2812 $this->buildGroupTempTable();
2815 $this->customDataFrom();
2816 $this->buildPermissionClause();
2821 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
2822 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
2824 $clause = "{$field['dbAlias']} as {$alias}";
2826 $this->_select
.= ", $clause ";
2829 if ($applyLimit && empty($this->_params
['charts'])) {
2832 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2834 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2835 $this->addToDeveloperTab($sql);
2840 * Build group by clause.
2842 public function groupBy() {
2843 $this->storeGroupByArray();
2845 if (!empty($this->_groupByArray
)) {
2846 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2851 * Build order by clause.
2853 public function orderBy() {
2854 $this->_orderBy
= "";
2855 $this->_sections
= array();
2856 $this->storeOrderByArray();
2857 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2858 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2860 $this->assign('sections', $this->_sections
);
2864 * Extract order by fields and store as an array.
2866 * In some cases other functions want to know which fields are selected for ordering by
2867 * Separating this into a separate function allows it to be called separately from constructing
2868 * the order by clause
2870 public function storeOrderByArray() {
2871 $orderBys = array();
2873 if (!empty($this->_params
['order_bys']) &&
2874 is_array($this->_params
['order_bys']) &&
2875 !empty($this->_params
['order_bys'])
2878 // Process order_bys in user-specified order
2879 foreach ($this->_params
['order_bys'] as $orderBy) {
2880 $orderByField = array();
2881 foreach ($this->_columns
as $tableName => $table) {
2882 if (array_key_exists('order_bys', $table)) {
2883 // For DAO columns defined in $this->_columns
2884 $fields = $table['order_bys'];
2886 elseif (array_key_exists('extends', $table)) {
2887 // For custom fields referenced in $this->_customGroupExtends
2888 $fields = CRM_Utils_Array
::value('fields', $table, array());
2893 if (!empty($fields) && is_array($fields)) {
2894 foreach ($fields as $fieldName => $field) {
2895 if ($fieldName == $orderBy['column']) {
2896 $orderByField = array_merge($field, $orderBy);
2897 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2904 if (!empty($orderByField)) {
2905 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2906 if ($this->groupConcatTested
) {
2907 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
2910 // Not sure when this is preferable to using tplField (which has
2911 // definitely been tested to work in cases then this does not.
2912 // in caution not switching unless report has been tested for
2913 // group concat functionality.
2914 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2917 // Record any section headers for assignment to the template
2918 if (!empty($orderBy['section'])) {
2919 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2920 $this->_sections
[$orderByField['tplField']] = $orderByField;
2926 $this->_orderByArray
= $orderBys;
2928 $this->assign('sections', $this->_sections
);
2932 * Determine unselected columns.
2936 public function unselectedOrderByColumns() {
2937 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
2941 * Determine unselected columns.
2945 public function unselectedSectionColumns() {
2946 if (is_array($this->_sections
)) {
2947 return array_diff_key($this->_sections
, $this->getSelectColumns());
2955 * Build output rows.
2957 * @param string $sql
2958 * @param array $rows
2960 public function buildRows($sql, &$rows) {
2961 if (!$this->optimisedForOnlyFullGroupBy
) {
2962 CRM_Core_DAO
::disableFullGroupByMode();
2964 $dao = CRM_Core_DAO
::executeQuery($sql);
2965 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
2966 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
2968 CRM_Core_DAO
::reenableFullGroupByMode();
2969 if (!is_array($rows)) {
2973 // use this method to modify $this->_columnHeaders
2974 $this->modifyColumnHeaders();
2976 $unselectedSectionColumns = $this->unselectedSectionColumns();
2978 while ($dao->fetch()) {
2980 foreach ($this->_columnHeaders
as $key => $value) {
2981 if (property_exists($dao, $key)) {
2982 $row[$key] = $dao->$key;
2986 // section headers not selected for display need to be added to row
2987 foreach ($unselectedSectionColumns as $key => $values) {
2988 if (property_exists($dao, $key)) {
2989 $row[$key] = $dao->$key;
2998 * Calculate section totals.
3000 * When "order by" fields are marked as sections, this assigns to the template
3001 * an array of total counts for each section. This data is used by the Smarty
3002 * plugin {sectionTotal}.
3004 public function sectionTotals() {
3006 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3007 if (empty($this->_selectAliases
)) {
3011 if (!empty($this->_sections
)) {
3012 // build the query with no LIMIT clause
3013 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3014 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3016 // pull section aliases out of $this->_sections
3017 $sectionAliases = array_keys($this->_sections
);
3020 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3021 $ifnulls[] = "ifnull($alias, '') as $alias";
3023 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3024 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3026 // Group (un-limited) report by all aliases and get counts. This might
3027 // be done more efficiently when the contents of $sql are known, ie. by
3028 // overriding this method in the report class.
3030 $query = $this->_select
.
3031 ", count(*) as ct from ($sql) as subquery group by " .
3032 implode(", ", $sectionAliases);
3034 // initialize array of total counts
3036 $dao = CRM_Core_DAO
::executeQuery($query);
3037 while ($dao->fetch()) {
3039 // let $this->_alterDisplay translate any integer ids to human-readable values.
3040 $rows[0] = $dao->toArray();
3041 $this->alterDisplay($rows);
3044 // add totals for all permutations of section values
3047 $aliasCount = count($sectionAliases);
3048 foreach ($sectionAliases as $alias) {
3049 $values[] = $row[$alias];
3050 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3051 if ($i == $aliasCount) {
3052 // the last alias is the lowest-level section header; use count as-is
3053 $totals[$key] = $dao->ct
;
3056 // other aliases are higher level; roll count into their total
3057 $totals[$key] +
= $dao->ct
;
3061 $this->assign('sectionTotals', $totals);
3066 * Modify column headers.
3068 public function modifyColumnHeaders() {
3069 // use this method to modify $this->_columnHeaders
3073 * Move totals columns to the right edge of the table.
3075 * It seems like a more logical layout to have any totals columns on the far right regardless of
3076 * the location of the rest of their table.
3078 public function moveSummaryColumnsToTheRightHandSide() {
3079 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3080 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3084 * Assign rows to the template.
3086 * @param array $rows
3088 public function doTemplateAssignment(&$rows) {
3089 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
3090 $this->assign_by_ref('rows', $rows);
3091 $this->assign('statistics', $this->statistics($rows));
3095 * Build report statistics.
3097 * Override this method to build your own statistics.
3099 * @param array $rows
3103 public function statistics(&$rows) {
3104 $statistics = array();
3106 $count = count($rows);
3107 // Why do we increment the count for rollup seems to artificially inflate the count.
3108 // It seems perhaps intentional to include the summary row in the count of results - although
3109 // this just seems odd.
3110 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3114 $this->countStat($statistics, $count);
3116 $this->groupByStat($statistics);
3118 $this->filterStat($statistics);
3124 * Add count statistics.
3126 * @param array $statistics
3129 public function countStat(&$statistics, $count) {
3130 $statistics['counts']['rowCount'] = array(
3131 'title' => ts('Row(s) Listed'),
3135 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3136 $statistics['counts']['rowsFound'] = array(
3137 'title' => ts('Total Row(s)'),
3138 'value' => $this->_rowsFound
,
3144 * Add group by statistics.
3146 * @param array $statistics
3148 public function groupByStat(&$statistics) {
3149 if (!empty($this->_params
['group_bys']) &&
3150 is_array($this->_params
['group_bys']) &&
3151 !empty($this->_params
['group_bys'])
3153 foreach ($this->_columns
as $tableName => $table) {
3154 if (array_key_exists('group_bys', $table)) {
3155 foreach ($table['group_bys'] as $fieldName => $field) {
3156 if (!empty($this->_params
['group_bys'][$fieldName])) {
3157 $combinations[] = $field['title'];
3162 $statistics['groups'][] = array(
3163 'title' => ts('Grouping(s)'),
3164 'value' => implode(' & ', $combinations),
3170 * Filter statistics.
3172 * @param array $statistics
3174 public function filterStat(&$statistics) {
3175 foreach ($this->_columns
as $tableName => $table) {
3176 if (array_key_exists('filters', $table)) {
3177 foreach ($table['filters'] as $fieldName => $field) {
3178 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3179 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3180 CRM_Utils_Array
::value('operatorType', $field) !=
3181 CRM_Report_Form
::OP_MONTH
3185 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3186 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3187 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3188 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3189 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3191 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3192 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3194 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3195 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3198 $statistics['filters'][] = array(
3199 'title' => $field['title'],
3200 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3203 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3204 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3206 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3207 $statistics['filters'][] = array(
3208 'title' => $field['title'],
3209 'value' => $pair[$rel],
3214 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3217 $pair = $this->getOperationPair(
3218 CRM_Utils_Array
::value('operatorType', $field),
3221 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3222 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3223 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3224 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3225 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3227 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3228 $this->setEntityRefDefaults($field, $tableName);
3229 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3230 array('id' => $val) +
3231 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3233 foreach ($result['values'] as $v) {
3234 $values[] = $v['label'];
3236 $value = "{$pair[$op]} " . implode(', ', $values);
3238 elseif ($op == 'nll' ||
$op == 'nnll') {
3239 $value = $pair[$op];
3241 elseif (is_array($val) && (!empty($val))) {
3242 $options = CRM_Utils_Array
::value('options', $field, array());
3243 foreach ($val as $key => $valIds) {
3244 if (isset($options[$valIds])) {
3245 $val[$key] = $options[$valIds];
3248 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3249 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3250 $val = implode(', ', $val);
3251 $value = "{$pair[$op]} " . $val;
3253 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3254 isset($field['options']) &&
3255 is_array($field['options']) && !empty($field['options'])
3257 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3258 CRM_Utils_Array
::value($val, $field['options'], $val);
3261 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3264 if ($value && empty($field['no_display'])) {
3265 $statistics['filters'][] = array(
3266 'title' => CRM_Utils_Array
::value('title', $field),
3277 * End post processing.
3279 * @param array|null $rows
3281 public function endPostProcess(&$rows = NULL) {
3282 $this->assign('report_class', get_class($this));
3283 if ($this->_storeResultSet
) {
3284 $this->_resultSet
= $rows;
3287 if ($this->_outputMode
== 'print' ||
3288 $this->_outputMode
== 'pdf' ||
3292 $content = $this->compileContent();
3293 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3297 if ($this->_sendmail
) {
3298 $config = CRM_Core_Config
::singleton();
3299 $attachments = array();
3301 if ($this->_outputMode
== 'csv') {
3303 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3304 ": {$url}</p>" . '<p>' .
3305 ts('The report is attached as a CSV file.') . '</p>' .
3306 $this->_formValues
['report_footer'];
3308 $csvFullFilename = $config->templateCompileDir
.
3309 CRM_Utils_File
::makeFileName('CiviReport.csv');
3310 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3311 file_put_contents($csvFullFilename, $csvContent);
3312 $attachments[] = array(
3313 'fullPath' => $csvFullFilename,
3314 'mime_type' => 'text/csv',
3315 'cleanName' => 'CiviReport.csv',
3318 if ($this->_outputMode
== 'pdf') {
3319 // generate PDF content
3320 $pdfFullFilename = $config->templateCompileDir
.
3321 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3322 file_put_contents($pdfFullFilename,
3323 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3324 TRUE, array('orientation' => 'landscape')
3327 // generate Email Content
3329 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3330 ": {$url}</p>" . '<p>' .
3331 ts('The report is attached as a PDF file.') . '</p>' .
3332 $this->_formValues
['report_footer'];
3334 $attachments[] = array(
3335 'fullPath' => $pdfFullFilename,
3336 'mime_type' => 'application/pdf',
3337 'cleanName' => 'CiviReport.pdf',
3341 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3342 $this->_outputMode
, $attachments
3345 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3348 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3352 elseif ($this->_outputMode
== 'print') {
3356 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3357 $config = CRM_Core_Config
::singleton();
3358 //get chart image name
3359 $chartImg = $this->_chartId
. '.png';
3360 //get image url path
3362 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3364 $uploadUrl .= $chartImg;
3365 //get image doc path to overwrite
3367 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3368 'openFlashChart/' . $chartImg;
3370 $chart = imagecreatefrompng($uploadUrl);
3371 //convert it into formatted png
3372 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3373 //overwrite with same image
3374 imagepng($chart, $uploadImg);
3376 imagedestroy($chart);
3378 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3380 CRM_Utils_System
::civiExit();
3382 elseif ($this->_outputMode
== 'csv') {
3383 CRM_Report_Utils_Report
::export2csv($this, $rows);
3385 elseif ($this->_outputMode
== 'group') {
3386 $group = $this->_params
['groups'];
3387 $this->add2group($group);
3392 * Set store result set indicator to TRUE.
3394 * @todo explain what this does
3396 public function storeResultSet() {
3397 $this->_storeResultSet
= TRUE;
3405 public function getResultSet() {
3406 return $this->_resultSet
;
3410 * Get the sql used to generate the report.
3414 public function getReportSql() {
3415 return $this->sqlArray
;
3419 * Use the form name to create the tpl file name.
3423 public function getTemplateFileName() {
3424 $defaultTpl = parent
::getTemplateFileName();
3425 $template = CRM_Core_Smarty
::singleton();
3426 if (!$template->template_exists($defaultTpl)) {
3427 $defaultTpl = 'CRM/Report/Form.tpl';
3433 * Compile the report content.
3435 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3439 public function compileContent() {
3440 $templateFile = $this->getHookedTemplateFileName();
3441 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3442 CRM_Core_Form
::$_template->fetch($templateFile) .
3443 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3448 * Post process function.
3450 public function postProcess() {
3451 // get ready with post process params
3452 $this->beginPostProcess();
3455 $sql = $this->buildQuery();
3457 // build array of result based on column headers. This method also allows
3458 // modifying column headers before using it to build result set i.e $rows.
3460 $this->buildRows($sql, $rows);
3462 // format result set.
3463 $this->formatDisplay($rows);
3465 // assign variables to templates
3466 $this->doTemplateAssignment($rows);
3468 // do print / pdf / instance stuff if needed
3469 $this->endPostProcess($rows);
3475 * @param int $rowCount
3479 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3480 // lets do the pager if in html mode
3481 $this->_limit
= NULL;
3483 // CRM-14115, over-ride row count if rowCount is specified in URL
3484 if ($this->_dashBoardRowCount
) {
3485 $rowCount = $this->_dashBoardRowCount
;
3487 if ($this->addPaging
) {
3488 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3490 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3492 // @todo all http vars should be extracted in the preProcess
3493 // - not randomly in the class
3494 if (!$pageId && !empty($_POST)) {
3495 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3496 $pageId = max((int) $_POST['crmPID_B'], 1);
3498 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3499 $pageId = max((int) $_POST['crmPID'], 1);
3501 unset($_POST['crmPID_B'], $_POST['crmPID']);
3504 $pageId = $pageId ?
$pageId : 1;
3505 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3506 $offset = ($pageId - 1) * $rowCount;
3508 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3509 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3511 $this->_limit
= " LIMIT $offset, $rowCount";
3512 return array($offset, $rowCount);
3514 if ($this->_limitValue
) {
3515 if ($this->_offsetValue
) {
3516 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3519 $this->_limit
= " LIMIT " . $this->_limitValue
;
3527 * @param int $rowCount
3529 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3530 // CRM-14115, over-ride row count if rowCount is specified in URL
3531 if ($this->_dashBoardRowCount
) {
3532 $rowCount = $this->_dashBoardRowCount
;
3535 if ($this->_limit
&& ($this->_limit
!= '')) {
3536 if (!$this->_rowsFound
) {
3537 $sql = "SELECT FOUND_ROWS();";
3538 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3541 'total' => $this->_rowsFound
,
3542 'rowCount' => $rowCount,
3543 'status' => ts('Records') . ' %%StatusMessage%%',
3544 'buttonBottom' => 'PagerBottomButton',
3545 'buttonTop' => 'PagerTopButton',
3547 if (!empty($this->controller
)) {
3548 // This happens when being called from the api Really we want the api to be able to
3549 // pass paging parameters, but at this stage just preventing test crashes.
3550 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3553 $pager = new CRM_Utils_Pager($params);
3554 $this->assign_by_ref('pager', $pager);
3555 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3560 * Build a group filter with contempt for large data sets.
3562 * This function has been retained as it takes time to migrate the reports over
3563 * to the new method which will not crash on large datasets.
3567 * @param string $field
3568 * @param mixed $value
3573 public function legacySlowGroupFilterClause($field, $value, $op) {
3574 $smartGroupQuery = "";
3576 $group = new CRM_Contact_DAO_Group();
3577 $group->is_active
= 1;
3579 $smartGroups = array();
3580 while ($group->fetch()) {
3581 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3582 $group->saved_search_id
3584 $smartGroups[] = $group->id
;
3588 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3590 $smartGroupQuery = '';
3591 if (!empty($smartGroups)) {
3592 $smartGroups = implode(',', $smartGroups);
3593 $smartGroupQuery = " UNION DISTINCT
3594 SELECT DISTINCT smartgroup_contact.contact_id
3595 FROM civicrm_group_contact_cache smartgroup_contact
3596 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3599 $sqlOp = $this->getSQLOperator($op);
3600 if (!is_array($value)) {
3601 $value = array($value);
3603 //include child groups if any
3604 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3606 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3608 $contactAlias = $this->_aliases
['civicrm_contact'];
3609 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3610 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3612 return " {$contactAlias}.id {$sqlOp} (
3613 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3614 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3615 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3616 {$smartGroupQuery} ) ";
3620 * Build where clause for groups.
3622 * @param string $field
3623 * @param mixed $value
3628 public function whereGroupClause($field, $value, $op) {
3629 if ($this->groupFilterNotOptimised
) {
3630 return $this->legacySlowGroupFilterClause($field, $value, $op);
3632 if ($op === 'notin') {
3633 return " group_temp_table.id IS NULL ";
3635 // We will have used an inner join instead.
3641 * Create a table of the contact ids included by the group filter.
3643 * This function is called by both the api (tests) and the UI.
3645 public function buildGroupTempTable() {
3646 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3649 $filteredGroups = (array) $this->_params
['gid_value'];
3651 $groups = civicrm_api3('Group', 'get', array(
3653 'id' => array('IN' => $filteredGroups),
3654 'saved_search_id' => array('>' => 0),
3657 $smartGroups = array_keys($groups['values']);
3660 SELECT DISTINCT group_contact.contact_id as id
3661 FROM civicrm_group_contact group_contact
3662 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3663 AND group_contact.status = 'Added' ";
3665 if (!empty($smartGroups)) {
3666 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3667 $smartGroups = implode(',', $smartGroups);
3670 SELECT smartgroup_contact.contact_id as id
3671 FROM civicrm_group_contact_cache smartgroup_contact
3672 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3675 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3676 $this->executeReportQuery("
3677 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3680 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3684 * Execute query and add it to the developer tab.
3686 * @param string $query
3687 * @param array $params
3689 * @return \CRM_Core_DAO|object
3691 protected function executeReportQuery($query, $params = array()) {
3692 $this->addToDeveloperTab($query);
3693 return CRM_Core_DAO
::executeQuery($query, $params);
3697 * Build where clause for tags.
3699 * @param string $field
3700 * @param mixed $value
3705 public function whereTagClause($field, $value, $op) {
3706 // not using left join in query because if any contact
3707 // belongs to more than one tag, results duplicate
3709 $sqlOp = $this->getSQLOperator($op);
3710 if (!is_array($value)) {
3711 $value = array($value);
3713 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3714 $entity_table = $this->_tagFilterTable
;
3715 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3716 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3717 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3718 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3722 * Generate membership organization clause.
3724 * @param mixed $value
3725 * @param string $op SQL Operator
3729 public function whereMembershipOrgClause($value, $op) {
3730 $sqlOp = $this->getSQLOperator($op);
3731 if (!is_array($value)) {
3732 $value = array($value);
3735 $tmp_membership_org_sql_list = implode(', ', $value);
3736 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3737 SELECT DISTINCT mem.contact_id
3738 FROM civicrm_membership mem
3739 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3740 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3741 WHERE mt.member_of_contact_id IN (" .
3742 $tmp_membership_org_sql_list . ")
3743 AND mt.is_active = '1'
3744 AND mem_status.is_current_member = '1'
3745 AND mem_status.is_active = '1' ) ";
3749 * Generate Membership Type SQL Clause.
3751 * @param mixed $value
3757 public function whereMembershipTypeClause($value, $op) {
3758 $sqlOp = $this->getSQLOperator($op);
3759 if (!is_array($value)) {
3760 $value = array($value);
3763 $tmp_membership_sql_list = implode(', ', $value);
3764 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3765 SELECT DISTINCT mem.contact_id
3766 FROM civicrm_membership mem
3767 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3768 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3769 WHERE mem.membership_type_id IN (" .
3770 $tmp_membership_sql_list . ")
3771 AND mt.is_active = '1'
3772 AND mem_status.is_current_member = '1'
3773 AND mem_status.is_active = '1' ) ";
3777 * Buld contact acl clause
3778 * @deprecated in favor of buildPermissionClause
3780 * @param string $tableAlias
3782 public function buildACLClause($tableAlias = 'contact_a') {
3783 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3787 * Build the permision clause for all entities in this report
3789 public function buildPermissionClause() {
3791 foreach ($this->selectedTables() as $tableName) {
3792 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3793 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3794 $tableAlias = $this->_columns
[$tableName]['alias'];
3795 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3796 foreach ($clauses as $field => $clause) {
3797 // Skip contact_id field if redundant
3798 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3799 $ret["$tableName.$field"] = $clause;
3804 // Override output from buildACLClause
3805 $this->_aclFrom
= NULL;
3806 $this->_aclWhere
= implode(' AND ', $ret);
3810 * Add custom data to the columns.
3812 * @param bool $addFields
3813 * @param array $permCustomGroupIds
3815 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3816 if (empty($this->_customGroupExtends
)) {
3819 if (!is_array($this->_customGroupExtends
)) {
3820 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3822 $customGroupWhere = '';
3823 if (!empty($permCustomGroupIds)) {
3824 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3828 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3829 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3830 FROM civicrm_custom_group cg
3831 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3832 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3834 cg.is_active = 1 AND
3835 cf.is_active = 1 AND
3836 cf.is_searchable = 1
3837 ORDER BY cg.weight, cf.weight";
3838 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3841 while ($customDAO->fetch()) {
3842 if ($customDAO->table_name
!= $curTable) {
3843 $curTable = $customDAO->table_name
;
3844 $curFields = $curFilters = array();
3847 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3848 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3849 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3850 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3852 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3853 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3854 $this->_columns
[$curTable][$colKey] = array();
3858 $fieldName = 'custom_' . $customDAO->cf_id
;
3861 // this makes aliasing work in favor
3862 $curFields[$fieldName] = array(
3863 'name' => $customDAO->column_name
,
3864 'title' => $customDAO->label
,
3865 'dataType' => $customDAO->data_type
,
3866 'htmlType' => $customDAO->html_type
,
3869 if ($this->_customGroupFilters
) {
3870 // this makes aliasing work in favor
3871 $curFilters[$fieldName] = array(
3872 'name' => $customDAO->column_name
,
3873 'title' => $customDAO->label
,
3874 'dataType' => $customDAO->data_type
,
3875 'htmlType' => $customDAO->html_type
,
3879 switch ($customDAO->data_type
) {
3882 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3883 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3884 // CRM-6946, show time part for datetime date fields
3885 if ($customDAO->time_format
) {
3886 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3891 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3892 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3893 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3897 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3898 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3902 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3903 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3904 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3908 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3909 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3913 case 'StateProvince':
3915 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3917 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3918 if ($options !== FALSE) {
3919 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3920 $curFilters[$fieldName]['options'] = $options;
3924 case 'ContactReference':
3925 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3926 $curFilters[$fieldName]['name'] = 'display_name';
3927 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3929 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3930 $curFields[$fieldName]['name'] = 'display_name';
3931 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3935 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3936 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3940 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3941 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3942 if ($options !== FALSE) {
3943 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3944 $curFilters[$fieldName]['options'] = $options;
3948 if (!array_key_exists('type', $curFields[$fieldName])) {
3949 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3953 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3955 if ($this->_customGroupFilters
) {
3956 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3958 if ($this->_customGroupGroupBy
) {
3959 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3965 * Build custom data from clause.
3967 * @param bool $joinsForFiltersOnly
3968 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3970 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3971 if (empty($this->_customGroupExtends
)) {
3974 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3975 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3976 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3977 $customTables = array();
3978 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3979 while ($customTablesDAO->fetch()) {
3980 $customTables[] = $customTablesDAO->table_name
;
3983 foreach ($this->_columns
as $table => $prop) {
3984 if (in_array($table, $customTables)) {
3985 $extendsTable = $mapper[$prop['extends']];
3986 // Check field is required for rendering the report.
3987 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3990 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3992 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3994 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3995 // handle for ContactReference
3996 if (array_key_exists('fields', $prop)) {
3997 foreach ($prop['fields'] as $fieldName => $field) {
3998 if (CRM_Utils_Array
::value('dataType', $field) ==
4001 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4003 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4012 * Check if the field is selected.
4014 * @param string $prop
4018 public function isFieldSelected($prop) {
4023 if (!empty($this->_params
['fields'])) {
4024 foreach (array_keys($prop['fields']) as $fieldAlias) {
4025 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4026 if ($customFieldId) {
4027 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4031 //might be survey response field.
4032 if (!empty($this->_params
['fields']['survey_response']) &&
4033 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4041 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4042 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4043 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4044 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4051 if (!empty($this->_params
['order_bys'])) {
4052 foreach (array_keys($prop['fields']) as $fieldAlias) {
4053 foreach ($this->_params
['order_bys'] as $orderBy) {
4054 if ($fieldAlias == $orderBy['column'] &&
4055 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4062 return $this->isFieldFiltered($prop);
4067 * Check if the field is used as a filter.
4069 * @param string $prop
4073 protected function isFieldFiltered($prop) {
4074 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4075 foreach ($prop['filters'] as $fieldAlias => $val) {
4084 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4085 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4086 ||
($attach != 'relative' &&
4087 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4093 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4094 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
4105 * Check for empty order_by configurations and remove them.
4107 * Also set template to hide them.
4109 * @param array $formValues
4111 public function preProcessOrderBy(&$formValues) {
4112 // Object to show/hide form elements
4113 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4115 $_showHide->addShow('optionField_1');
4117 // Cycle through order_by options; skip any empty ones, and hide them as well
4120 if (!empty($formValues['order_bys'])) {
4121 foreach ($formValues['order_bys'] as $order_by) {
4122 if ($order_by['column'] && $order_by['column'] != '-') {
4123 $_showHide->addShow('optionField_' . $n);
4124 $orderBys[$n] = $order_by;
4129 for ($i = $n; $i <= 5; $i++
) {
4131 $_showHide->addHide('optionField_' . $i);
4135 // overwrite order_by options with modified values
4136 if (!empty($orderBys)) {
4137 $formValues['order_bys'] = $orderBys;
4140 $formValues['order_bys'] = array(1 => array('column' => '-'));
4143 // assign show/hide data to template
4144 $_showHide->addToTemplate();
4148 * Check if table name has columns in SELECT clause.
4150 * @param string $tableName
4151 * Name of table (index of $this->_columns array).
4155 public function isTableSelected($tableName) {
4156 return in_array($tableName, $this->selectedTables());
4160 * Check if table name has columns in WHERE or HAVING clause.
4162 * @param string $tableName
4163 * Name of table (index of $this->_columns array).
4167 public function isTableFiltered($tableName) {
4168 // Cause the array to be generated if not previously done.
4169 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4170 $this->selectedTables();
4172 return in_array($tableName, $this->filteredTables
);
4176 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4178 * If the array is unset it will be built.
4183 public function selectedTables() {
4184 if (!$this->_selectedTables
) {
4185 $orderByColumns = array();
4186 if (array_key_exists('order_bys', $this->_params
) &&
4187 is_array($this->_params
['order_bys'])
4189 foreach ($this->_params
['order_bys'] as $orderBy) {
4190 $orderByColumns[] = $orderBy['column'];
4194 foreach ($this->_columns
as $tableName => $table) {
4195 if (array_key_exists('fields', $table)) {
4196 foreach ($table['fields'] as $fieldName => $field) {
4197 if (!empty($field['required']) ||
4198 !empty($this->_params
['fields'][$fieldName])
4200 $this->_selectedTables
[] = $tableName;
4205 if (array_key_exists('order_bys', $table)) {
4206 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4207 if (in_array($orderByName, $orderByColumns)) {
4208 $this->_selectedTables
[] = $tableName;
4213 if (array_key_exists('filters', $table)) {
4214 foreach ($table['filters'] as $filterName => $filter) {
4215 if (!empty($this->_params
["{$filterName}_value"])
4216 ||
!empty($this->_params
["{$filterName}_relative"])
4217 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4219 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4222 $this->_selectedTables
[] = $tableName;
4223 $this->filteredTables
[] = $tableName;
4230 return $this->_selectedTables
;
4234 * Add address fields.
4236 * @deprecated - use getAddressColumns which is a more accurate description
4237 * and also accepts an array of options rather than a long list
4239 * adding address fields to construct function in reports
4241 * @param bool $groupBy
4242 * Add GroupBy? Not appropriate for detail report.
4243 * @param bool $orderBy
4244 * Add GroupBy? Not appropriate for detail report.
4245 * @param bool $filters
4246 * @param array $defaults
4249 * address fields for construct clause
4251 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4252 $defaultAddressFields = array(
4253 'street_address' => ts('Street Address'),
4254 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4255 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4256 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4257 'street_number' => ts('Street Number'),
4258 'street_name' => ts('Street Name'),
4259 'street_unit' => ts('Street Unit'),
4260 'city' => ts('City'),
4261 'postal_code' => ts('Postal Code'),
4262 'postal_code_suffix' => ts('Postal Code Suffix'),
4263 'country_id' => ts('Country'),
4264 'state_province_id' => ts('State/Province'),
4265 'county_id' => ts('County'),
4267 $addressFields = array(
4268 'civicrm_address' => array(
4269 'dao' => 'CRM_Core_DAO_Address',
4271 'address_name' => array(
4272 'title' => ts('Address Name'),
4273 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4277 'grouping' => 'location-fields',
4280 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4281 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4282 'title' => $fieldLabel,
4283 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4287 $street_address_filters = $general_address_filters = array();
4289 // Address filter depends on whether street address parsing is enabled.
4291 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4294 if ($addressOptions['street_address_parsing']) {
4295 $street_address_filters = array(
4296 'street_number' => array(
4297 'title' => ts('Street Number'),
4298 'type' => CRM_Utils_Type
::T_INT
,
4299 'name' => 'street_number',
4301 'street_name' => array(
4302 'title' => ts('Street Name'),
4303 'name' => 'street_name',
4304 'type' => CRM_Utils_Type
::T_STRING
,
4309 $street_address_filters = array(
4310 'street_address' => array(
4311 'title' => ts('Street Address'),
4312 'type' => CRM_Utils_Type
::T_STRING
,
4313 'name' => 'street_address',
4317 $general_address_filters = array(
4318 'postal_code' => array(
4319 'title' => ts('Postal Code'),
4320 'type' => CRM_Utils_Type
::T_STRING
,
4321 'name' => 'postal_code',
4324 'title' => ts('City'),
4325 'type' => CRM_Utils_Type
::T_STRING
,
4328 'country_id' => array(
4329 'name' => 'country_id',
4330 'title' => ts('Country'),
4331 'type' => CRM_Utils_Type
::T_INT
,
4332 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4333 'options' => CRM_Core_PseudoConstant
::country(),
4335 'state_province_id' => array(
4336 'name' => 'state_province_id',
4337 'title' => ts('State/Province'),
4338 'type' => CRM_Utils_Type
::T_INT
,
4339 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4340 'options' => array(),
4342 'county_id' => array(
4343 'name' => 'county_id',
4344 'title' => ts('County'),
4345 'type' => CRM_Utils_Type
::T_INT
,
4346 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4347 'options' => array(),
4351 $addressFields['civicrm_address']['filters'] = array_merge(
4352 $street_address_filters,
4353 $general_address_filters);
4356 $addressFields['civicrm_address']['order_bys'] = array(
4357 'street_name' => array('title' => ts('Street Name')),
4358 'street_number' => array('title' => ts('Odd / Even Street Number')),
4359 'street_address' => NULL,
4361 'postal_code' => NULL,
4366 $addressFields['civicrm_address']['group_bys'] = array(
4367 'street_address' => NULL,
4369 'postal_code' => NULL,
4370 'state_province_id' => array(
4371 'title' => ts('State/Province'),
4373 'country_id' => array(
4374 'title' => ts('Country'),
4376 'county_id' => array(
4377 'title' => ts('County'),
4381 return $addressFields;
4385 * Do AlterDisplay processing on Address Fields.
4388 * @param array $rows
4389 * @param int $rowNum
4390 * @param string $baseUrl
4391 * @param string $linkText
4395 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4396 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4397 $entryFound = FALSE;
4399 if (array_key_exists('civicrm_address_country_id', $row)) {
4400 if ($value = $row['civicrm_address_country_id']) {
4401 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4403 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4404 "reset=1&force=1&{$criteriaQueryParams}&" .
4405 "country_id_op=in&country_id_value={$value}",
4406 $this->_absoluteUrl
, $this->_id
4408 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4409 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4410 array(1 => $linkText)
4417 if (array_key_exists('civicrm_address_county_id', $row)) {
4418 if ($value = $row['civicrm_address_county_id']) {
4419 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4421 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4422 "reset=1&force=1&{$criteriaQueryParams}&" .
4423 "county_id_op=in&county_id_value={$value}",
4424 $this->_absoluteUrl
, $this->_id
4426 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4427 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4428 array(1 => $linkText)
4434 // handle state province
4435 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4436 if ($value = $row['civicrm_address_state_province_id']) {
4437 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4439 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4440 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4441 $this->_absoluteUrl
, $this->_id
4443 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4444 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4445 array(1 => $linkText)
4456 * Do AlterDisplay processing on Address Fields.
4459 * @param array $rows
4460 * @param int $rowNum
4461 * @param string $baseUrl
4462 * @param string $linkText
4466 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4467 $entryFound = FALSE;
4468 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4469 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4470 $addLinks = array('gender_id' => 'Gender');
4471 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4472 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4473 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4474 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4475 $rowLabels = array();
4476 foreach ($rowValues as $rowValue) {
4478 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4481 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4482 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4483 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4489 $yesNoFields = array(
4490 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4492 foreach ($yesNoFields as $fieldName) {
4493 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4494 // Since these are essentially 'negative fields' it feels like it
4495 // makes sense to only highlight the exceptions hence no 'No'.
4496 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4504 * Adjusts dates passed in to YEAR() for fiscal year.
4506 * @param string $fieldName
4510 public function fiscalYearOffset($fieldName) {
4511 $config = CRM_Core_Config
::singleton();
4512 $fy = $config->fiscalYearStart
;
4513 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4514 ($fy['d'] == 1 && $fy['M'] == 1)
4516 return "YEAR( $fieldName )";
4518 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4519 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4523 * Add Address into From Table if required.
4525 * @deprecated use joinAddressFromContact
4526 * (left here in case extensions use it).
4528 public function addAddressFromClause() {
4529 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinAddressFromContact');
4530 // include address field if address column is to be included
4531 if ((isset($this->_addressField
) &&
4532 $this->_addressField
4534 $this->isTableSelected('civicrm_address')
4537 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4538 ON ({$this->_aliases['civicrm_contact']}.id =
4539 {$this->_aliases['civicrm_address']}.contact_id) AND
4540 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4545 * Add Phone into From Table if required.
4547 * @deprecated use joinPhoneFromContact
4548 * (left here in case extensions use it).
4550 public function addPhoneFromClause() {
4551 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinPhoneFromContact');
4552 // include address field if address column is to be included
4553 if ($this->isTableSelected('civicrm_phone')) {
4555 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4556 ON ({$this->_aliases['civicrm_contact']}.id =
4557 {$this->_aliases['civicrm_phone']}.contact_id) AND
4558 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4563 * Add Address into From Table if required.
4565 * Prefix will be added to both tables as
4566 * it is assumed you are using it to get address of a secondary contact.
4568 * @param string $prefix
4569 * @param array $extra Additional options.
4570 * Not currently used in core but may be used in override extensions.
4572 protected function joinAddressFromContact($prefix = '', $extra = array()) {
4573 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4574 $isJoinRequired = $this->_addressField
;
4575 foreach ($addressTables as $addressTable) {
4576 if ($this->isTableSelected($prefix . $addressTable)) {
4577 $isJoinRequired = TRUE;
4580 if ($isJoinRequired) {
4582 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4583 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4584 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id) AND
4585 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4590 * Add Country into From Table if required.
4592 * Prefix will be added to both tables as
4593 * it is assumed you are using it to get address of a secondary contact.
4595 * @param string $prefix
4596 * @param array $extra Additional options.
4597 * Not currently used in core but may be used in override extensions.
4599 protected function joinCountryFromAddress($prefix = '', $extra = array()) {
4600 // include country field if country column is to be included
4601 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4602 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4603 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4606 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4607 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id AND
4608 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4613 * Add Phone into From Table if required.
4615 * Prefix will be added to both tables as
4616 * it is assumed you are using it to get address of a secondary contact.
4618 * @param string $prefix
4619 * @param array $extra Additional options.
4620 * Not currently used in core but may be used in override extensions.
4622 protected function joinPhoneFromContact($prefix = '', $extra = array()) {
4623 // include phone field if phone column is to be included
4624 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4626 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4627 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id AND
4628 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4633 * Add Email into From Table if required.
4635 * Prefix will be added to both tables as
4636 * it is assumed you are using it to get address of a secondary contact.
4638 * @param string $prefix
4639 * @param array $extra Additional options.
4640 * Not currently used in core but may be used in override extensions.
4642 protected function joinEmailFromContact($prefix = '', $extra = array()) {
4643 // include email field if email column is to be included
4644 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4646 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4647 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id AND
4648 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1) ";
4653 * Add Financial Transaction into From Table if required.
4655 public function addFinancialTrxnFromClause() {
4656 if ($this->isTableSelected('civicrm_financial_trxn')) {
4658 LEFT JOIN civicrm_entity_financial_trxn eftcc
4659 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4660 eftcc.entity_table = 'civicrm_contribution')
4661 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4662 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4667 * Get phone columns to add to array.
4669 * @param array $options
4670 * - prefix Prefix to add to table (in case of more than one instance of the table)
4671 * - prefix_label Label to give columns from this phone table instance
4674 * phone columns definition
4676 public function getPhoneColumns($options = array()) {
4677 $defaultOptions = array(
4679 'prefix_label' => '',
4682 $options = array_merge($defaultOptions, $options);
4685 $options['prefix'] . 'civicrm_phone' => array(
4686 'dao' => 'CRM_Core_DAO_Phone',
4688 $options['prefix'] . 'phone' => array(
4689 'title' => $options['prefix_label'] . ts('Phone'),
4699 * Get a standard set of contact fields.
4703 public function getBasicContactFields() {
4705 'sort_name' => array(
4706 'title' => ts('Contact Name'),
4711 'no_display' => TRUE,
4714 'prefix_id' => array(
4715 'title' => ts('Contact Prefix'),
4717 'first_name' => array(
4718 'title' => ts('First Name'),
4720 'nick_name' => array(
4721 'title' => ts('Nick Name'),
4723 'middle_name' => array(
4724 'title' => ts('Middle Name'),
4726 'last_name' => array(
4727 'title' => ts('Last Name'),
4729 'suffix_id' => array(
4730 'title' => ts('Contact Suffix'),
4732 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4733 'email_greeting_display' => array('title' => ts('Email Greeting')),
4734 'addressee_display' => array('title' => ts('Addressee')),
4735 'contact_type' => array(
4736 'title' => ts('Contact Type'),
4738 'contact_sub_type' => array(
4739 'title' => ts('Contact Subtype'),
4741 'gender_id' => array(
4742 'title' => ts('Gender'),
4744 'birth_date' => array(
4745 'title' => ts('Birth Date'),
4748 'title' => ts('Age'),
4749 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4751 'job_title' => array(
4752 'title' => ts('Contact Job title'),
4754 'organization_name' => array(
4755 'title' => ts('Organization Name'),
4757 'external_identifier' => array(
4758 'title' => ts('Contact identifier from external system'),
4760 'do_not_email' => array(),
4761 'do_not_phone' => array(),
4762 'do_not_mail' => array(),
4763 'do_not_sms' => array(),
4764 'is_opt_out' => array(),
4765 'is_deceased' => array(),
4766 'preferred_language' => array(),
4771 * Get a standard set of contact filters.
4775 public function getBasicContactFilters() {
4777 'sort_name' => array(
4778 'title' => ts('Contact Name'),
4781 'title' => ts('Contact Source'),
4782 'type' => CRM_Utils_Type
::T_STRING
,
4785 'title' => ts('Contact ID'),
4786 'no_display' => TRUE,
4788 'gender_id' => array(
4789 'title' => ts('Gender'),
4790 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4791 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4793 'birth_date' => array(
4794 'title' => ts('Birth Date'),
4795 'operatorType' => CRM_Report_Form
::OP_DATE
,
4797 'contact_type' => array(
4798 'title' => ts('Contact Type'),
4800 'contact_sub_type' => array(
4801 'title' => ts('Contact Subtype'),
4803 'modified_date' => array(
4804 'title' => ts('Contact Modified'),
4805 'operatorType' => CRM_Report_Form
::OP_DATE
,
4806 'type' => CRM_Utils_Type
::T_DATE
,
4808 'is_deceased' => array(
4809 'title' => ts('Deceased'),
4810 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4813 'do_not_email' => array(
4814 'title' => ts('Do not email'),
4815 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4817 'do_not_phone' => array(
4818 'title' => ts('Do not phone'),
4819 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4821 'do_not_mail' => array(
4822 'title' => ts('Do not mail'),
4823 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4825 'do_not_sms' => array(
4826 'title' => ts('Do not SMS'),
4827 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4829 'is_opt_out' => array(
4830 'title' => ts('Do not bulk email'),
4831 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4833 'preferred_language' => array(
4834 'title' => ts('Preferred Language'),
4836 'is_deleted' => array(
4837 'no_display' => TRUE,
4839 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4845 * Add contact to group.
4847 * @param int $groupID
4849 public function add2group($groupID) {
4850 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4851 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4852 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4853 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4854 $sql = str_replace('WITH ROLLUP', '', $sql);
4855 $dao = CRM_Core_DAO
::executeQuery($sql);
4857 $contact_ids = array();
4858 // Add resulting contacts to group
4859 while ($dao->fetch()) {
4860 if ($dao->addtogroup_contact_id
) {
4861 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4865 if (!empty($contact_ids)) {
4866 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4867 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4870 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4876 * Show charts on print screen.
4878 public static function uploadChartImage() {
4879 // upload strictly for '.png' images
4880 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4881 if (preg_match('/\.png$/', $name)) {
4883 // Get the RAW .png from the input.
4884 $httpRawPostData = file_get_contents("php://input");
4886 // prepare the directory
4887 $config = CRM_Core_Config
::singleton();
4889 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4891 if (!file_exists($defaultPath)) {
4892 mkdir($defaultPath, 0777, TRUE);
4895 // full path to the saved image including filename
4896 $destination = $defaultPath . $name;
4899 $jfh = fopen($destination, 'w') or die("can't open file");
4900 fwrite($jfh, $httpRawPostData);
4902 CRM_Utils_System
::civiExit();
4907 * Apply common settings to entityRef fields.
4909 * @param array $field
4910 * @param string $table
4912 private function setEntityRefDefaults(&$field, $table) {
4913 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4914 $field['attributes'] +
= array(
4915 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4917 'placeholder' => ts('- select -'),
4922 * Add link fields to the row.
4924 * Function adds the _link & _hover fields to the row.
4927 * @param string $baseUrl
4928 * @param string $linkText
4929 * @param string $value
4930 * @param string $fieldName
4931 * @param string $tablePrefix
4932 * @param string $fieldLabel
4936 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4937 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4938 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4939 "reset=1&force=1&{$criteriaQueryParams}&" .
4940 $fieldName . "_op=in&{$fieldName}_value={$value}",
4941 $this->_absoluteUrl
, $this->_id
4943 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4944 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4945 array(1 => $linkText, 2 => $fieldLabel)
4950 * Get label for show results buttons.
4954 public function getResultsLabel() {
4955 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4956 return $showResultsLabel;
4960 * Determine the output mode from the url or input.
4963 * - pdf : Render as pdf
4964 * - csv : Render as csv
4965 * - print : Render in print format
4966 * - save : save the report and display the new report
4967 * - copy : save the report as a new instance and display that.
4968 * - group : go to the add to group screen.
4970 * Potentially chart variations could also be included but the complexity
4971 * is that we might print a bar chart as a pdf.
4973 protected function setOutputMode() {
4974 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4977 CRM_Core_DAO
::$_nullObject,
4979 CRM_Utils_Array
::value('task', $this->_params
)
4981 // if contacts are added to group
4982 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4983 $this->_outputMode
= 'group';
4985 if (isset($this->_params
['task'])) {
4986 unset($this->_params
['task']);
4991 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4994 * @param $columnName
4996 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4997 // add new column with date value for the datetime field
4998 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4999 CRM_Core_DAO
::executeQuery($tempQuery);
5000 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5001 CRM_Core_DAO
::executeQuery($updateQuery);
5002 $this->_selectClauses
[] = "{$columnName}_date";
5003 $this->_select
.= ", {$columnName}_date";
5004 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5005 unset($this->_sections
["{$columnName}"]);
5006 $this->assign('sections', $this->_sections
);
5010 * Get an array of the columns that have been selected for display.
5014 public function getSelectColumns() {
5015 $selectColumns = array();
5016 foreach ($this->_columns
as $tableName => $table) {
5017 if (array_key_exists('fields', $table)) {
5018 foreach ($table['fields'] as $fieldName => $field) {
5019 if (!empty($field['required']) ||
5020 !empty($this->_params
['fields'][$fieldName])
5023 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5028 return $selectColumns;
5032 * Add location tables to the query if they are used for filtering.
5034 * This is for when we are running the query separately for filtering and retrieving display fields.
5036 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5037 if ($this->isTableFiltered('civicrm_email')) {
5039 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5040 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5041 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5043 if ($this->isTableFiltered('civicrm_phone')) {
5045 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5046 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5047 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5049 if ($this->isTableFiltered('civicrm_address')) {
5051 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5052 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5053 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5058 * Set the base table for the FROM clause.
5060 * Sets up the from clause, allowing for the possibility it might be a
5061 * temp table pre-filtered by groups if a group filter is in use.
5063 * @param string $baseTable
5064 * @param string $field
5065 * @param null $tableAlias
5067 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5069 $tableAlias = $this->_aliases
[$baseTable];
5071 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5072 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5073 $this->_from
.= " {$this->_aclFrom} ";
5077 * Join the temp table contacting contacts who are members of the filtered groups.
5079 * If we are using an IN filter we use an inner join, otherwise a left join.
5081 * @param string $baseTable
5082 * @param string $field
5083 * @param string $tableAlias
5085 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5086 if ($this->groupTempTable
) {
5087 if ($this->_params
['gid_op'] == 'in') {
5088 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5089 ON group_temp_table.id = $tableAlias.{$field} ";
5093 LEFT JOIN $this->groupTempTable group_temp_table
5094 ON $tableAlias.{$field} = group_temp_table.id ";
5100 * Get all labels for fields that are used in a group concat.
5102 * @param string $options
5103 * comma separated option values.
5104 * @param string $baoName
5105 * The BAO name for the field.
5106 * @param string $fieldName
5107 * The name of the field for which labels should be retrieved.
5111 public function getLabels($options, $baoName, $fieldName) {
5112 $types = explode(',', $options);
5114 foreach ($types as $value) {
5115 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5117 return implode(', ', array_filter($labels));
5121 * Add statistics columns.
5123 * If a group by is in play then add columns for the statistics fields.
5125 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5126 * column header field.
5128 * @param array $field
5129 * @param string $tableName
5130 * @param string $fieldName
5131 * @param array $select
5135 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5136 foreach ($field['statistics'] as $stat => $label) {
5137 $alias = "{$tableName}_{$fieldName}_{$stat}";
5138 switch (strtolower($stat)) {
5141 $select[] = "$stat({$field['dbAlias']}) as $alias";
5142 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5143 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5144 $this->_statFields
[$label] = $alias;
5145 $this->_selectAliases
[] = $alias;
5149 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5150 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5151 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5152 $this->_statFields
[$label] = $alias;
5153 $this->_selectAliases
[] = $alias;
5156 case 'count_distinct':
5157 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5158 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5159 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5160 $this->_statFields
[$label] = $alias;
5161 $this->_selectAliases
[] = $alias;
5165 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5166 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5167 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5168 $this->_statFields
[$label] = $alias;
5169 $this->_selectAliases
[] = $alias;
5177 * Add a basic field to the select clause.
5179 * @param string $tableName
5180 * @param string $fieldName
5181 * @param array $field
5182 * @param string $select
5185 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5186 $alias = "{$tableName}_{$fieldName}";
5187 $select[] = "{$field['dbAlias']} as $alias";
5188 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
5189 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
5190 $this->_selectAliases
[] = $alias;
5197 * @param array $table
5198 * @param string $tableName
5203 protected function setTableAlias($table, $tableName) {
5204 if (!isset($table['alias'])) {
5205 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5209 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5212 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5213 return $this->_aliases
[$tableName];
5217 * Function to add columns to reports.
5219 * This is ported from extended reports, which also adds join filters to the options.
5221 * @param string $type
5222 * @param array $options
5223 * - prefix - A string to prepend to the table name
5224 * - prefix_label A string to prepend to the fields
5225 * - fields (bool) - should the fields for this table be made available
5226 * - group_by (bool) - should the group bys for this table be made available.
5227 * - order_by (bool) - should the group bys for this table be made available.
5228 * - filters (bool) - should the filters for this table by made available.
5229 * - fields_defaults (array) array of fields that should be displayed by default.
5230 * - filters_defaults (array) array of fields that should be filtered by default.
5231 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5232 * - join_fields (array) fields available from join (requires additional custom code).
5233 * - group_by_defaults (array) array of group bys that should be applied by default.
5234 * - order_by_defaults (array) array of order bys that should be applied by default.
5235 * - custom_fields (array) array of entity types for custom fields (not usually required).
5236 * - contact_type (string) optional restriction on contact type for some tables.
5237 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5241 protected function getColumns($type, $options = array()) {
5242 $defaultOptions = array(
5244 'prefix_label' => '',
5246 'group_bys' => FALSE,
5247 'order_bys' => TRUE,
5249 'join_filters' => FALSE,
5250 'fields_defaults' => array(),
5251 'filters_defaults' => array(),
5252 'group_bys_defaults' => array(),
5253 'order_bys_defaults' => array(),
5255 $options = array_merge($defaultOptions, $options);
5257 $fn = 'get' . $type . 'Columns';
5258 return $this->$fn($options);
5262 * Get columns for contact table.
5264 * @param array $options
5268 protected function getContactColumns($options = array()) {
5269 $defaultOptions = array(
5270 'custom_fields' => array('Individual', 'Contact', 'Organization'),
5271 'fields_defaults' => array('display_name', 'id'),
5272 'order_bys_defaults' => array('sort_name ASC'),
5273 'contact_type' => NULL,
5276 $options = array_merge($defaultOptions, $options);
5278 $tableAlias = $options['prefix'] . 'contact';
5281 $options['prefix'] . 'display_name' => array(
5282 'name' => 'display_name',
5283 'title' => $options['prefix_label'] . ts('Contact Name'),
5284 'is_fields' => TRUE,
5286 $options['prefix'] . 'sort_name' => array(
5287 'name' => 'sort_name',
5288 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5289 'is_fields' => TRUE,
5290 'is_filters' => TRUE,
5291 'is_order_bys' => TRUE,
5293 $options['prefix'] . 'id' => array(
5295 'title' => $options['prefix_label'] . ts('Contact ID'),
5296 'alter_display' => 'alterContactID',
5297 'type' => CRM_Utils_Type
::T_INT
,
5298 'is_order_bys' => TRUE,
5299 'is_group_bys' => TRUE,
5300 'is_fields' => TRUE,
5301 'is_filters' => TRUE,
5303 $options['prefix'] . 'external_identifier' => array(
5304 'name' => 'external_identifier',
5305 'title' => $options['prefix_label'] . ts('External ID'),
5306 'type' => CRM_Utils_Type
::T_INT
,
5307 'is_fields' => TRUE,
5309 $options['prefix'] . 'contact_type' => array(
5310 'title' => $options['prefix_label'] . ts('Contact Type'),
5311 'name' => 'contact_type',
5312 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5313 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5314 'is_fields' => TRUE,
5315 'is_filters' => TRUE,
5316 'is_group_bys' => TRUE,
5318 $options['prefix'] . 'contact_sub_type' => array(
5319 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5320 'name' => 'contact_sub_type',
5321 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5322 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5323 'is_fields' => TRUE,
5324 'is_filters' => TRUE,
5325 'is_group_bys' => TRUE,
5327 $options['prefix'] . 'is_deleted' => array(
5328 'title' => $options['prefix_label'] . ts('Is deleted'),
5329 'name' => 'is_deleted',
5330 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5331 'is_fields' => FALSE,
5332 'is_filters' => TRUE,
5333 'is_group_bys' => FALSE,
5336 $individualFields = array(
5337 $options['prefix'] . 'first_name' => array(
5338 'name' => 'first_name',
5339 'title' => $options['prefix_label'] . ts('First Name'),
5340 'is_fields' => TRUE,
5341 'is_filters' => TRUE,
5342 'is_order_bys' => TRUE,
5344 $options['prefix'] . 'middle_name' => array(
5345 'name' => 'middle_name',
5346 'title' => $options['prefix_label'] . ts('Middle Name'),
5347 'is_fields' => TRUE,
5349 $options['prefix'] . 'last_name' => array(
5350 'name' => 'last_name',
5351 'title' => $options['prefix_label'] . ts('Last Name'),
5352 'default_order' => 'ASC',
5353 'is_fields' => TRUE,
5355 $options['prefix'] . 'nick_name' => array(
5356 'name' => 'nick_name',
5357 'title' => $options['prefix_label'] . ts('Nick Name'),
5358 'is_fields' => TRUE,
5360 $options['prefix'] . 'gender_id' => array(
5361 'name' => 'gender_id',
5362 'title' => $options['prefix_label'] . ts('Gender'),
5363 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5364 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5365 'alter_display' => 'alterGenderID',
5366 'is_fields' => TRUE,
5367 'is_filters' => TRUE,
5369 'birth_date' => array(
5370 'title' => $options['prefix_label'] . ts('Birth Date'),
5371 'operatorType' => CRM_Report_Form
::OP_DATE
,
5372 'type' => CRM_Utils_Type
::T_DATE
,
5373 'is_fields' => TRUE,
5374 'is_filters' => TRUE,
5377 'title' => $options['prefix_label'] . ts('Age'),
5378 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '.birth_date, CURDATE())',
5379 'type' => CRM_Utils_Type
::T_INT
,
5380 'is_fields' => TRUE,
5382 $options['prefix'] . 'is_deceased' => array(
5383 'title' => $options['prefix_label'] . ts('Is deceased'),
5384 'name' => 'is_deceased',
5385 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5386 'is_fields' => FALSE,
5387 'is_filters' => TRUE,
5388 'is_group_bys' => FALSE,
5391 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5392 $spec = array_merge($spec, $individualFields);
5395 if (!empty($options['custom_fields'])) {
5396 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = array(
5397 'extends' => $options['custom_fields'],
5398 'title' => $options['prefix_label'],
5399 'filters' => $options['filters'],
5400 'prefix' => $options['prefix'],
5401 'prefix_label' => $options['prefix_label'],
5405 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5409 * Get address columns to add to array.
5411 * @param array $options
5412 * - prefix Prefix to add to table (in case of more than one instance of the table)
5413 * - prefix_label Label to give columns from this address table instance
5414 * - group_bys enable these fields for group by - default false
5415 * - order_bys enable these fields for order by
5416 * - filters enable these fields for filtering
5418 * @return array address columns definition
5420 protected function getAddressColumns($options = array()) {
5421 $defaultOptions = array(
5423 'prefix_label' => '',
5425 'group_bys' => FALSE,
5426 'order_bys' => TRUE,
5428 'join_filters' => FALSE,
5429 'fields_defaults' => array(),
5430 'filters_defaults' => array(),
5431 'group_bys_defaults' => array(),
5432 'order_bys_defaults' => array(),
5435 $options = array_merge($defaultOptions, $options);
5436 $defaults = $this->getDefaultsFromOptions($options);
5437 $tableAlias = $options['prefix'] . 'address';
5440 $options['prefix'] . 'name' => array(
5441 'title' => ts($options['prefix_label'] . 'Address Name'),
5443 'is_fields' => TRUE,
5445 $options['prefix'] . 'street_number' => array(
5446 'name' => 'street_number',
5447 'title' => ts($options['prefix_label'] . 'Street Number'),
5449 'is_fields' => TRUE,
5451 $options['prefix'] . 'street_name' => array(
5452 'name' => 'street_name',
5453 'title' => ts($options['prefix_label'] . 'Street Name'),
5455 'is_fields' => TRUE,
5456 'is_filters' => TRUE,
5457 'operator' => 'like',
5458 'is_order_bys' => TRUE,
5460 $options['prefix'] . 'street_address' => array(
5461 'title' => ts($options['prefix_label'] . 'Street Address'),
5462 'name' => 'street_address',
5463 'is_fields' => TRUE,
5464 'is_filters' => TRUE,
5465 'is_group_bys' => TRUE,
5467 $options['prefix'] . 'supplemental_address_1' => array(
5468 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 1'),
5469 'name' => 'supplemental_address_1',
5470 'is_fields' => TRUE,
5472 $options['prefix'] . 'supplemental_address_2' => array(
5473 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 2'),
5474 'name' => 'supplemental_address_2',
5475 'is_fields' => TRUE,
5477 $options['prefix'] . 'supplemental_address_3' => array(
5478 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 3'),
5479 'name' => 'supplemental_address_3',
5480 'is_fields' => TRUE,
5482 $options['prefix'] . 'street_number' => array(
5483 'name' => 'street_number',
5484 'title' => ts($options['prefix_label'] . 'Street Number'),
5486 'is_order_bys' => TRUE,
5487 'is_filters' => TRUE,
5488 'is_fields' => TRUE,
5490 $options['prefix'] . 'street_name' => array(
5491 'name' => 'street_name',
5492 'title' => ts($options['prefix_label'] . 'Street Name'),
5494 'is_fields' => TRUE,
5496 $options['prefix'] . 'street_unit' => array(
5497 'name' => 'street_unit',
5498 'title' => ts($options['prefix_label'] . 'Street Unit'),
5500 'is_fields' => TRUE,
5502 $options['prefix'] . 'city' => array(
5503 'title' => ts($options['prefix_label'] . 'City'),
5505 'operator' => 'like',
5506 'is_fields' => TRUE,
5507 'is_filters' => TRUE,
5508 'is_group_bys' => TRUE,
5509 'is_order_bys' => TRUE,
5511 $options['prefix'] . 'postal_code' => array(
5512 'title' => ts($options['prefix_label'] . 'Postal Code'),
5513 'name' => 'postal_code',
5515 'is_fields' => TRUE,
5516 'is_filters' => TRUE,
5517 'is_group_bys' => TRUE,
5518 'is_order_bys' => TRUE,
5520 $options['prefix'] . 'postal_code_suffix' => array(
5521 'title' => ts($options['prefix_label'] . 'Postal Code Suffix'),
5522 'name' => 'postal_code',
5524 'is_fields' => TRUE,
5525 'is_filters' => TRUE,
5526 'is_group_bys' => TRUE,
5527 'is_order_bys' => TRUE,
5529 $options['prefix'] . 'county_id' => array(
5530 'title' => ts($options['prefix_label'] . 'County'),
5531 'alter_display' => 'alterCountyID',
5532 'name' => 'county_id',
5533 'type' => CRM_Utils_Type
::T_INT
,
5534 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5535 'options' => CRM_Core_PseudoConstant
::county(),
5536 'is_fields' => TRUE,
5537 'is_filters' => TRUE,
5538 'is_group_bys' => TRUE,
5540 $options['prefix'] . 'state_province_id' => array(
5541 'title' => ts($options['prefix_label'] . 'State/Province'),
5542 'alter_display' => 'alterStateProvinceID',
5543 'name' => 'state_province_id',
5544 'type' => CRM_Utils_Type
::T_INT
,
5545 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5546 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5547 'is_fields' => TRUE,
5548 'is_filters' => TRUE,
5549 'is_group_bys' => TRUE,
5551 $options['prefix'] . 'country_id' => array(
5552 'title' => ts($options['prefix_label'] . 'Country'),
5553 'alter_display' => 'alterCountryID',
5554 'name' => 'country_id',
5555 'is_fields' => TRUE,
5556 'is_filters' => TRUE,
5557 'is_group_bys' => TRUE,
5558 'type' => CRM_Utils_Type
::T_INT
,
5559 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5560 'options' => CRM_Core_PseudoConstant
::country(),
5562 $options['prefix'] . 'location_type_id' => array(
5563 'name' => 'is_primary',
5564 'title' => ts($options['prefix_label'] . 'Location Type'),
5565 'type' => CRM_Utils_Type
::T_INT
,
5566 'is_fields' => TRUE,
5567 'alter_display' => 'alterLocationTypeID',
5569 $options['prefix'] . 'id' => array(
5570 'title' => ts($options['prefix_label'] . 'ID'),
5572 'is_fields' => TRUE,
5574 $options['prefix'] . 'is_primary' => array(
5575 'name' => 'is_primary',
5576 'title' => ts($options['prefix_label'] . 'Primary Address?'),
5577 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5578 'is_fields' => TRUE,
5581 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5585 * Build the columns.
5587 * The normal report class needs you to remember to do a few things that are often erratic
5589 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5590 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5591 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5592 * means any saved filters / fields on saved report instances. This will mean that matching names from
5593 * different tables may be ambigious, but it will smooth any code transition.
5594 * - note that it assumes the value being passed in is the actual table field name
5596 * 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
5597 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5599 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5600 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5601 * the core classes can start to move towards that.
5603 * @param array $specs
5604 * @param string $tableName
5605 * @param string $daoName
5606 * @param string $tableAlias
5607 * @param array $defaults
5608 * @param array $options
5612 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = array(), $options = array()) {
5614 $tableAlias = str_replace('civicrm_', '', $tableName);
5616 $types = array('filters', 'group_bys', 'order_bys', 'join_filters');
5617 $columns = array($tableName => array_fill_keys($types, array()));
5618 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5619 $columns[$tableName]['dao'] = $daoName;
5620 $columns[$tableName]['alias'] = $tableAlias;
5622 foreach ($specs as $specName => $spec) {
5623 if (empty($spec['name'])) {
5624 $spec['name'] = $specName;
5627 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5628 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5629 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5630 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5631 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5634 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5635 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5638 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5639 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5642 foreach ($types as $type) {
5643 if ($options[$type] && !empty($spec['is_' . $type])) {
5644 $columns[$tableName][$type][$fieldAlias] = $spec;
5645 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5646 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5655 * Store group bys into array - so we can check elsewhere what is grouped.
5657 protected function storeGroupByArray() {
5659 if (!CRM_Utils_Array
::value('group_bys', $this->_params
)
5660 ||
!is_array($this->_params
['group_bys'])) {
5661 $this->_params
['group_bys'] = [];
5664 foreach ($this->_columns
as $tableName => $table) {
5665 $table = $this->_columns
[$tableName];
5666 if (array_key_exists('group_bys', $table)) {
5667 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5668 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5669 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5670 if (!empty($field['chart'])) {
5671 $this->assign('chartSupported', TRUE);
5674 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5675 !empty($this->_params
['group_bys_freq'][$fieldName])
5678 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5680 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5683 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
5686 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_{$this->_params['group_bys_freq'][$fieldName]} FROM {$field['dbAlias']})";
5691 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5692 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5707 protected function getDefaultsFromOptions($options) {
5709 'fields_defaults' => $options['fields_defaults'],
5710 'filters_defaults' => $options['filters_defaults'],
5711 'group_bys_defaults' => $options['group_bys_defaults'],
5712 'order_bys_defaults' => $options['order_bys_defaults'],
5718 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5720 * Full group by mode dictates that a field must either be in the group by function or
5721 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5724 * @param string $tableName
5725 * @param string $fieldName
5726 * @param string $field
5729 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5730 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5731 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5732 $label = CRM_Utils_Array
::value('title', $field);
5733 $alias = "{$tableName}_{$fieldName}";
5734 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5735 $this->_selectAliases
[] = $alias;
5736 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5737 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5739 return "({$field['dbAlias']}) as $alias";