3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = 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 * Tables created for the report that need removal afterwards.
494 * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x']
497 protected $temporaryTables = [];
500 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
503 public $optimisedForOnlyFullGroupBy = TRUE;
507 public function __construct() {
508 parent
::__construct();
510 $this->addClass('crm-report-form');
512 if ($this->_tagFilter
) {
513 $this->buildTagFilter();
515 if ($this->_exposeContactID
) {
516 if (array_key_exists('civicrm_contact', $this->_columns
)) {
517 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
519 'title' => ts('Contact ID'),
525 if ($this->_groupFilter
) {
526 $this->buildGroupFilter();
529 // Get all custom groups
530 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
532 // Get the custom groupIds for which the user has VIEW permission
533 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
534 // and addCustomDataToColumns() will allow access to all custom groups.
535 $permCustomGroupIds = array();
536 if (!CRM_Core_Permission
::check('access all custom data')) {
537 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
538 // do not allow custom data for reports if user doesn't have
539 // permission to access custom data.
540 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
541 $this->_customGroupExtends
= array();
545 // merge custom data columns to _columns list, if any
546 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
548 // add / modify display columns, filters ..etc
549 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
551 //assign currencyColumn variable to tpl
552 $this->assign('currencyColumn', $this->_currencyColumn
);
556 * Shared pre-process function.
558 * If overriding preProcess function this should still be called.
562 public function preProcessCommon() {
563 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
565 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
567 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
569 $this->assign('section', $this->_section
);
570 CRM_Core_Region
::instance('page-header')->add(array(
571 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
573 if (!$this->noController
) {
574 $this->setID($this->get('instanceId'));
577 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
579 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
583 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
584 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
585 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
589 $this->assign('instanceId', $this->_id
);
590 $params = array('id' => $this->_id
);
591 $this->_instanceValues
= array();
592 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
594 $this->_instanceValues
596 if (empty($this->_instanceValues
)) {
597 CRM_Core_Error
::fatal("Report could not be loaded.");
599 $this->_title
= $this->_instanceValues
['title'];
600 if (!empty($this->_instanceValues
['permission']) &&
601 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
602 CRM_Core_Permission
::check('administer Reports')
605 CRM_Utils_System
::permissionDenied();
606 CRM_Utils_System
::civiExit();
609 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
611 $this->_formValues
= unserialize($formValues);
614 $this->_formValues
= NULL;
617 $this->setOutputMode();
619 if ($this->_outputMode
== 'copy') {
620 $this->_createNew
= TRUE;
621 $this->_params
= $this->_formValues
;
622 $this->_params
['view_mode'] = 'criteria';
623 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
624 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
625 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
627 // Do not pass go. Do not collect another chance to re-run the same query.
628 CRM_Report_Form_Instance
::postProcess($this);
631 // lets always do a force if reset is found in the url.
632 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
633 // in the comment line above these 2.
634 if (!empty($_REQUEST['reset'])
635 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
640 $this->assign('mode', 'instance');
642 elseif (!$this->noController
) {
643 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
644 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
645 if (($instanceCount > 0) && $optionValueID) {
646 $this->assign('instanceUrl',
647 CRM_Utils_System
::url('civicrm/report/list',
648 "reset=1&ovid=$optionValueID"
652 if ($optionValueID) {
653 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
657 $this->assign('mode', 'template');
660 // lets display the Report Settings section
661 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
663 // Do not display Report Settings section if administer Reports permission is absent OR
664 // if report instance is reserved and administer reserved reports absent
665 if (!CRM_Core_Permission
::check('administer Reports') ||
666 ($this->_instanceValues
['is_reserved'] &&
667 !CRM_Core_Permission
::check('administer reserved reports'))
669 $this->_instanceForm
= FALSE;
672 $this->assign('criteriaForm', FALSE);
673 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
674 if (CRM_Core_Permission
::check('administer Reports') ||
675 CRM_Core_Permission
::check('access Report Criteria')
677 if (!$this->_instanceValues
['is_reserved'] ||
678 CRM_Core_Permission
::check('administer reserved reports')
680 $this->assign('criteriaForm', TRUE);
681 $this->_criteriaForm
= TRUE;
685 // Special permissions check for private instance if it's not the current contact instance
687 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
688 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
689 if (!CRM_Core_Permission
::check('access all private reports')) {
690 $this->_instanceForm
= FALSE;
691 $this->assign('criteriaForm', FALSE);
695 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
696 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
697 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
698 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
704 public function addBreadCrumb() {
708 'title' => ts('Report Templates'),
709 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
713 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
717 * Pre process function.
719 * Called prior to build form.
721 public function preProcess() {
722 $this->preProcessCommon();
725 $this->addBreadCrumb();
728 foreach ($this->_columns
as $tableName => $table) {
729 $this->setTableAlias($table, $tableName);
731 $expFields = array();
732 // higher preference to bao object
733 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
736 if (method_exists($daoOrBaoName, 'exportableFields')) {
737 $expFields = $daoOrBaoName::exportableFields();
740 $expFields = $daoOrBaoName::export();
744 $doNotCopy = array('required', 'default');
746 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
747 foreach ($fieldGroups as $fieldGrp) {
748 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
749 foreach ($table[$fieldGrp] as $fieldName => $field) {
750 // $name is the field name used to reference the BAO/DAO export fields array
751 $name = isset($field['name']) ?
$field['name'] : $fieldName;
753 // Sometimes the field name key in the BAO/DAO export fields array is
754 // different from the actual database field name.
755 // Unset $field['name'] so that actual database field name can be obtained
756 // from the BAO/DAO export fields array.
757 unset($field['name']);
759 if (array_key_exists($name, $expFields)) {
760 foreach ($doNotCopy as $dnc) {
761 // unset the values we don't want to be copied.
762 unset($expFields[$name][$dnc]);
765 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
768 foreach ($expFields[$name] as $property => $val) {
769 if (!array_key_exists($property, $field)) {
770 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
777 if (!empty($field['no_repeat'])) {
778 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
780 if (!empty($field['no_display'])) {
781 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
784 // set alias = table-name, unless already set
785 $alias = isset($field['alias']) ?
$field['alias'] : (
786 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
788 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
790 // set name = fieldName, unless already set
791 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
792 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
795 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
796 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
799 // set dbAlias = alias.name, unless already set
800 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
801 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
803 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
806 // a few auto fills for filters
807 if ($fieldGrp == 'filters') {
808 // fill operator types
809 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
810 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
811 case CRM_Utils_Type
::T_MONEY
:
812 case CRM_Utils_Type
::T_FLOAT
:
813 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
816 case CRM_Utils_Type
::T_INT
:
817 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
820 case CRM_Utils_Type
::T_DATE
:
821 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
824 case CRM_Utils_Type
::T_BOOLEAN
:
825 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
826 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
827 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
838 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
840 // with multiple options operator-type is generally multi-select
841 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
842 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
844 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
851 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
852 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
855 $this->_columns
[$tableName]['metadata'][$fieldName] = array_merge($this->_columns
[$tableName][$fieldGrp][$fieldName], $this->_columns
[$tableName]['metadata'][$fieldName]);
861 // copy filters to a separate handy variable
862 if (array_key_exists('filters', $table)) {
863 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
866 if (array_key_exists('group_bys', $table)) {
867 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
870 if (array_key_exists('fields', $table)) {
871 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
876 $this->setDefaultValues(FALSE);
879 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
880 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
881 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
882 CRM_Report_Utils_Get
::processChart($this->_defaults
);
885 $this->_formValues
= $this->_defaults
;
886 $this->postProcess();
891 * Set default values.
893 * @param bool $freeze
897 public function setDefaultValues($freeze = TRUE) {
898 $freezeGroup = array();
900 // FIXME: generalizing form field naming conventions would reduce
901 // Lots of lines below.
902 foreach ($this->_columns
as $tableName => $table) {
903 if (array_key_exists('fields', $table)) {
904 foreach ($table['fields'] as $fieldName => $field) {
905 if (empty($field['no_display'])) {
906 if (!empty($field['required'])) {
908 $this->_defaults
['fields'][$fieldName] = 1;
911 // find element object, so that we could use quickform's freeze method
912 // for required elements
913 $obj = $this->getElementFromGroup("fields", $fieldName);
915 $freezeGroup[] = $obj;
919 elseif (isset($field['default'])) {
920 $this->_defaults
['fields'][$fieldName] = $field['default'];
926 if (array_key_exists('group_bys', $table)) {
927 foreach ($table['group_bys'] as $fieldName => $field) {
928 if (isset($field['default'])) {
929 if (!empty($field['frequency'])) {
930 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
932 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
936 if (array_key_exists('filters', $table)) {
937 foreach ($table['filters'] as $fieldName => $field) {
938 if (isset($field['default'])) {
939 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
941 if (is_array($field['default'])) {
942 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
943 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
944 $this->_defaults
["{$fieldName}_relative"] = 0;
947 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
951 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
952 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
953 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
955 $this->_defaults
["{$fieldName}_value"] = $field['default'];
958 //assign default value as "in" for multiselect
959 //operator, To freeze the select element
960 if (CRM_Utils_Array
::value('operatorType', $field) ==
961 CRM_Report_Form
::OP_MULTISELECT
963 $this->_defaults
["{$fieldName}_op"] = 'in';
965 if (CRM_Utils_Array
::value('operatorType', $field) ==
966 CRM_Report_Form
::OP_ENTITYREF
968 $this->_defaults
["{$fieldName}_op"] = 'in';
970 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
971 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
973 $this->_defaults
["{$fieldName}_op"] = 'mhas';
975 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
976 $this->_defaults
["{$fieldName}_op"] = $op;
982 empty($this->_formValues
['order_bys']) &&
983 (array_key_exists('order_bys', $table) &&
984 is_array($table['order_bys']))
986 if (!array_key_exists('order_bys', $this->_defaults
)) {
987 $this->_defaults
['order_bys'] = array();
989 foreach ($table['order_bys'] as $fieldName => $field) {
990 if (!empty($field['default']) ||
!empty($field['default_order']) ||
991 CRM_Utils_Array
::value('default_is_section', $field) ||
992 !empty($field['default_weight'])
995 'column' => $fieldName,
996 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
997 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
1000 if (!empty($field['default_weight'])) {
1001 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
1004 array_unshift($this->_defaults
['order_bys'], $order_by);
1010 foreach ($this->_options
as $fieldName => $field) {
1011 if (isset($field['default'])) {
1012 $this->_defaults
['options'][$fieldName] = $field['default'];
1017 if (!empty($this->_submitValues
)) {
1018 $this->preProcessOrderBy($this->_submitValues
);
1021 $this->preProcessOrderBy($this->_defaults
);
1024 // lets finish freezing task here itself
1025 if (!empty($freezeGroup)) {
1026 foreach ($freezeGroup as $elem) {
1031 if ($this->_formValues
) {
1032 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1035 if ($this->_instanceValues
) {
1036 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1039 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1041 return $this->_defaults
;
1045 * Get element from group.
1047 * @param string $group
1048 * @param string $grpFieldName
1052 public function getElementFromGroup($group, $grpFieldName) {
1053 $eleObj = $this->getElement($group);
1054 foreach ($eleObj->_elements
as $index => $obj) {
1055 if ($grpFieldName == $obj->_attributes
['name']) {
1063 * Setter for $_params.
1065 * @param array $params
1067 public function setParams($params) {
1068 $this->_params
= $params;
1072 * Getter for $_params.
1074 * @return void|array $params
1076 public function getParams() {
1077 return $this->_params
;
1083 * @param int $instanceID
1085 public function setID($instanceID) {
1086 $this->_id
= $instanceID;
1090 * Setter for $_force.
1092 * @param bool $isForce
1094 public function setForce($isForce) {
1095 $this->_force
= $isForce;
1099 * Setter for $_limitValue.
1101 * @param int $_limitValue
1103 public function setLimitValue($_limitValue) {
1104 $this->_limitValue
= $_limitValue;
1108 * Setter for $_offsetValue.
1110 * @param int $_offsetValue
1112 public function setOffsetValue($_offsetValue) {
1113 $this->_offsetValue
= $_offsetValue;
1117 * Setter for $addPaging.
1119 * @param bool $value
1121 public function setAddPaging($value) {
1122 $this->addPaging
= $value;
1126 * Getter for $_defaultValues.
1130 public function getDefaultValues() {
1131 return $this->_defaults
;
1135 * Remove any temporary tables.
1137 public function cleanUpTemporaryTables() {
1138 foreach ($this->temporaryTables
as $temporaryTable) {
1139 CRM_Core_DAO
::executeQuery('DROP ' . ($temporaryTable['temporary'] ?
'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']);
1144 * Create a temporary table.
1146 * This function creates a table AND adds the details to the developer tab & $this->>temporary tables.
1148 * @param string $identifier
1149 * This is the key that will be used for the table in the temporaryTables property.
1150 * @param string $sql
1151 * Sql select statement or column description (the latter requires the columns flag)
1152 * @param bool $isColumns
1153 * Is the sql describing columns to create (rather than using a select query).
1154 * @param bool $isMemory
1155 * Create a memory table rather than a normal INNODB table.
1159 public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) {
1160 $tempTable = CRM_Utils_SQL_TempTable
::build()->setUtf8();
1162 $tempTable->setMemory();
1165 $tempTable->createWithColumns($sql);
1168 $tempTable->createWithQuery($sql);
1170 $name = $tempTable->getName();
1171 // Developers may force tables to be durable to assist in debugging so lets check.
1172 $isNotTrueTemporary = $tempTable->isDurable();
1173 $this->addToDeveloperTab($tempTable->getCreateSql());
1174 $this->temporaryTables
[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name];
1179 * Add columns to report.
1181 public function addColumns() {
1184 foreach ($this->_columns
as $tableName => $table) {
1185 if (array_key_exists('fields', $table)) {
1186 foreach ($table['fields'] as $fieldName => $field) {
1188 if (empty($field['no_display'])) {
1189 foreach (array('table', 'field') as $var) {
1190 if (!empty($
{$var}['grouping'])) {
1191 if (!is_array($
{$var}['grouping'])) {
1192 $tableName = $
{$var}['grouping'];
1195 $tableName = array_keys($
{$var}['grouping']);
1196 $tableName = $tableName[0];
1197 $groupTitle = array_values($
{$var}['grouping']);
1198 $groupTitle = $groupTitle[0];
1203 if (!$groupTitle && isset($table['group_title'])) {
1204 $groupTitle = $table['group_title'];
1205 // Having a group_title is secret code for being a custom group
1206 // which cryptically translates to needing an accordion.
1207 // here we make that explicit.
1208 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1211 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1212 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1213 $colGroups[$tableName]['group_title'] = $groupTitle;
1215 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1221 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1222 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1224 if (!empty($colGroups)) {
1225 $this->tabs
['FieldSelection'] = array(
1226 'title' => ts('Columns'),
1227 'tpl' => 'FieldSelection',
1228 'div_label' => 'col-groups',
1231 // Note this assignment is only really required in buildForm. It is being 'over-called'
1232 // to reduce risk of being missed due to overridden functions.
1233 $this->assign('tabs', $this->tabs
);
1236 $this->assign('colGroups', $colGroups);
1240 * Add filters to report.
1242 public function addFilters() {
1243 $filters = $filterGroups = array();
1246 foreach ($this->_filters
as $table => $attributes) {
1247 if (isset($this->_columns
[$table]['group_title'])) {
1248 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1249 // which magically means to 'display in an accordian'
1250 // here we make this explicit.
1251 $filterGroups[$table] = array(
1252 'group_title' => $this->_columns
[$table]['group_title'],
1253 'use_accordian_for_field_selection' => TRUE,
1257 foreach ($attributes as $fieldName => $field) {
1258 // get ready with option value pair
1259 // @ 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
1261 $operations = $this->getOperationPair(
1262 CRM_Utils_Array
::value('operatorType', $field),
1265 $filters[$table][$fieldName] = $field;
1267 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1268 case CRM_Report_Form
::OP_MONTH
:
1269 if (!array_key_exists('options', $field) ||
1270 !is_array($field['options']) ||
empty($field['options'])
1272 // If there's no option list for this filter, define one.
1273 $field['options'] = array(
1275 2 => ts('February'),
1282 9 => ts('September'),
1283 10 => ts('October'),
1284 11 => ts('November'),
1285 12 => ts('December'),
1287 // Add this option list to this column _columns. This is
1288 // required so that filter statistics show properly.
1289 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1291 case CRM_Report_Form
::OP_MULTISELECT
:
1292 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1293 // assume a multi-select field
1294 if (!empty($field['options']) ||
1295 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1297 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1298 if (count($operations) <= 1) {
1301 if ($fieldName == 'state_province_id' ||
1302 $fieldName == 'county_id'
1304 $this->addChainSelect($fieldName . '_value', array(
1311 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1312 'style' => 'min-width:250px',
1313 'class' => 'crm-select2 huge',
1315 'placeholder' => ts('- select -'),
1321 case CRM_Report_Form
::OP_SELECT
:
1322 // assume a select field
1323 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1324 if (!empty($field['options'])) {
1325 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1329 case CRM_Report_Form
::OP_ENTITYREF
:
1330 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1331 $this->setEntityRefDefaults($field, $table);
1332 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1335 case CRM_Report_Form
::OP_DATE
:
1336 // build datetime fields
1337 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1341 case CRM_Report_Form
::OP_DATETIME
:
1342 // build datetime fields
1343 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1347 case CRM_Report_Form
::OP_INT
:
1348 case CRM_Report_Form
::OP_FLOAT
:
1349 // and a min value input box
1350 $this->add('text', "{$fieldName}_min", ts('Min'));
1351 // and a max value input box
1352 $this->add('text', "{$fieldName}_max", ts('Max'));
1354 // default type is string
1355 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1356 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1358 // we need text box for value input
1359 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1364 if (!empty($filters)) {
1365 $this->tabs
['Filters'] = array(
1366 'title' => ts('Filters'),
1368 'div_label' => 'set-filters',
1371 $this->assign('filters', $filters);
1372 $this->assign('filterGroups', $filterGroups);
1376 * Function to assign the tabs to the template in the correct order.
1378 * We want the tabs to wind up in this order (if not overridden).
1386 protected function assignTabs() {
1394 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1395 $order = array_merge($order, $this->tabs
);
1396 $this->assign('tabs', $order);
1400 * The intent is to add a tab for developers to view the sql.
1402 * Currently using dpm.
1404 * @param string $sql
1406 public function addToDeveloperTab($sql) {
1407 if (!CRM_Core_Permission
::check('view report sql')) {
1410 $ignored_output_modes = array('pdf', 'csv', 'print');
1411 if (in_array($this->_outputMode
, $ignored_output_modes)) {
1414 $this->tabs
['Developer'] = array(
1415 'title' => ts('Developer'),
1416 'tpl' => 'Developer',
1417 'div_label' => 'set-developer',
1420 $this->assignTabs();
1421 $this->sqlArray
[] = $sql;
1422 foreach ($this->sqlArray
as $sql) {
1423 foreach (array('LEFT JOIN') as $term) {
1424 $sql = str_replace($term, '<br> ' . $term, $sql);
1426 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1427 $sql = str_replace($term, '<br><br>' . $term, $sql);
1429 $this->sqlFormattedArray
[] = $sql;
1430 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1432 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL
::getSqlModes());
1437 * Add options defined in $this->_options to the report.
1439 public function addOptions() {
1440 if (!empty($this->_options
)) {
1441 // FIXME: For now lets build all elements as checkboxes.
1442 // Once we clear with the format we can build elements based on type
1444 foreach ($this->_options
as $fieldName => $field) {
1447 if ($field['type'] == 'select') {
1448 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1450 elseif ($field['type'] == 'checkbox') {
1451 $options[$field['title']] = $fieldName;
1452 $this->addCheckBox($fieldName, NULL,
1454 NULL, NULL, NULL, $this->_fourColumnAttribute
1459 if (!empty($this->_options
) &&
1461 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1463 $this->tabs
['ReportOptions'] = array(
1464 'title' => ts('Display Options'),
1465 'tpl' => 'ReportOptions',
1466 'div_label' => 'other-options',
1469 $this->assign('otherOptions', $this->_options
);
1473 * Add chart options to the report.
1475 public function addChartOptions() {
1476 if (!empty($this->_charts
)) {
1477 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1478 $this->assign('charts', $this->_charts
);
1479 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1484 * Add group by options to the report.
1486 public function addGroupBys() {
1487 $options = $freqElements = array();
1489 foreach ($this->_columns
as $tableName => $table) {
1490 if (array_key_exists('group_bys', $table)) {
1491 foreach ($table['group_bys'] as $fieldName => $field) {
1492 if (!empty($field) && empty($field['no_display'])) {
1493 $options[$field['title']] = $fieldName;
1494 if (!empty($field['frequency'])) {
1495 $freqElements[$field['title']] = $fieldName;
1501 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1502 NULL, NULL, NULL, $this->_fourColumnAttribute
1504 $this->assign('groupByElements', $options);
1505 if (!empty($options)) {
1506 $this->tabs
['GroupBy'] = array(
1507 'title' => ts('Grouping'),
1509 'div_label' => 'group-by-elements',
1513 foreach ($freqElements as $name) {
1514 $this->addElement('select', "group_bys_freq[$name]",
1515 ts('Frequency'), $this->_groupByDateFreq
1521 * Add data for order by tab.
1523 public function addOrderBys() {
1525 foreach ($this->_columns
as $tableName => $table) {
1527 // Report developer may define any column to order by; include these as order-by options.
1528 if (array_key_exists('order_bys', $table)) {
1529 foreach ($table['order_bys'] as $fieldName => $field) {
1530 if (!empty($field)) {
1531 $options[$fieldName] = $field['title'];
1536 // Add searchable custom fields as order-by options, if so requested
1537 // (These are already indexed, so allowing to order on them is cheap.)
1539 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1540 array_key_exists('extends', $table) && !empty($table['extends'])
1542 foreach ($table['fields'] as $fieldName => $field) {
1543 if (empty($field['no_display'])) {
1544 $options[$fieldName] = $field['title'];
1552 $this->assign('orderByOptions', $options);
1553 if (!empty($options)) {
1554 $this->tabs
['OrderBy'] = array(
1555 'title' => ts('Sorting'),
1557 'div_label' => 'order-by-elements',
1561 if (!empty($options)) {
1563 '-' => ' - none - ',
1565 for ($i = 1; $i <= 5; $i++
) {
1566 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1567 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1568 'ASC' => ts('Ascending'),
1569 'DESC' => ts('Descending'),
1571 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1572 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1578 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1580 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1581 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1584 public function buildInstanceAndButtons() {
1585 CRM_Report_Form_Instance
::buildForm($this);
1586 $this->_actionButtonName
= $this->getButtonName('submit');
1587 $this->addTaskMenu($this->getActions($this->_id
));
1589 $this->assign('instanceForm', $this->_instanceForm
);
1591 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1592 $permission = CRM_Core_Permission
::getPermission();
1593 if ($this->_instanceForm
&& $permission == CRM_Core_Permission
::EDIT
&&
1594 $this->_add2groupSupported
1596 $this->addElement('select', 'groups', ts('Group'),
1597 array('' => ts('Add Contacts to Group')) +
1598 CRM_Core_PseudoConstant
::nestedGroup(),
1599 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1601 $this->assign('group', TRUE);
1604 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1606 $this->addChartOptions();
1607 $showResultsLabel = $this->getResultsLabel();
1608 $this->addButtons(array(
1611 'name' => $showResultsLabel,
1612 'isDefault' => TRUE,
1619 * Has this form been submitted already?
1623 public function resultsDisplayed() {
1624 $buttonName = $this->controller
->getButtonName();
1625 return ($buttonName ||
$this->_outputMode
);
1629 * Get the actions for this report instance.
1631 * @param int $instanceId
1635 protected function getActions($instanceId) {
1636 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1637 if (empty($instanceId)) {
1638 $actions['report_instance.save'] = array(
1639 'title' => ts('Create Report'),
1641 'is_confirm' => TRUE,
1642 'confirm_title' => ts('Create Report'),
1643 'confirm_refresh_fields' => json_encode(array(
1644 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1645 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1649 unset($actions['report_instance.delete']);
1652 if (!$this->_csvSupported
) {
1653 unset($actions['report_instance.csv']);
1660 * Main build form function.
1662 public function buildQuickForm() {
1663 $this->addColumns();
1665 $this->addFilters();
1667 $this->addOptions();
1669 $this->addGroupBys();
1671 $this->addOrderBys();
1673 $this->buildInstanceAndButtons();
1675 // Add form rule for report.
1676 if (is_callable(array(
1680 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1682 $this->assignTabs();
1686 * A form rule function for custom data.
1688 * The rule ensures that fields selected in group_by if any) should only be the ones
1689 * present in display/select fields criteria;
1690 * note: works if and only if any custom field selected in group_by.
1692 * @param array $fields
1693 * @param array $ignoreFields
1697 public function customDataFormRule($fields, $ignoreFields = array()) {
1699 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1700 !empty($fields['group_bys'])
1702 foreach ($this->_columns
as $tableName => $table) {
1703 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1704 substr($tableName, 0, 12) == 'custom_value') &&
1705 !empty($this->_columns
[$tableName]['fields'])
1707 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1708 if (array_key_exists($fieldName, $fields['group_bys']) &&
1709 !array_key_exists($fieldName, $fields['fields'])
1711 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1713 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1714 foreach ($fields['fields'] as $fld => $val) {
1715 if (!array_key_exists($fld, $fields['group_bys']) &&
1716 !in_array($fld, $ignoreFields)
1718 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1730 * Get operators to display on form.
1732 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1734 * @param string $type
1735 * @param string $fieldName
1739 public function getOperationPair($type = "string", $fieldName = NULL) {
1740 // FIXME: At some point we should move these key-val pairs
1741 // to option_group and option_value table.
1743 case CRM_Report_Form
::OP_INT
:
1744 case CRM_Report_Form
::OP_FLOAT
:
1747 'lte' => ts('Is less than or equal to'),
1748 'gte' => ts('Is greater than or equal to'),
1749 'bw' => ts('Is between'),
1750 'eq' => ts('Is equal to'),
1751 'lt' => ts('Is less than'),
1752 'gt' => ts('Is greater than'),
1753 'neq' => ts('Is not equal to'),
1754 'nbw' => ts('Is not between'),
1755 'nll' => ts('Is empty (Null)'),
1756 'nnll' => ts('Is not empty (Null)'),
1760 case CRM_Report_Form
::OP_SELECT
:
1762 'eq' => ts('Is equal to'),
1766 case CRM_Report_Form
::OP_MONTH
:
1767 case CRM_Report_Form
::OP_MULTISELECT
:
1768 case CRM_Report_Form
::OP_ENTITYREF
:
1771 'in' => ts('Is one of'),
1772 'notin' => ts('Is not one of'),
1776 case CRM_Report_Form
::OP_DATE
:
1779 'nll' => ts('Is empty (Null)'),
1780 'nnll' => ts('Is not empty (Null)'),
1784 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1785 // use this operator for the values, concatenated with separator. For e.g if
1786 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1788 'mhas' => ts('Is one of'),
1789 'mnot' => ts('Is not one of'),
1796 'has' => ts('Contains'),
1797 'sw' => ts('Starts with'),
1798 'ew' => ts('Ends with'),
1799 'nhas' => ts('Does not contain'),
1800 'eq' => ts('Is equal to'),
1801 'neq' => ts('Is not equal to'),
1802 'nll' => ts('Is empty (Null)'),
1803 'nnll' => ts('Is not empty (Null)'),
1810 * Build the tag filter field to display on the filters tab.
1812 public function buildTagFilter() {
1813 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1814 if (!empty($contactTags)) {
1815 $this->_columns
['civicrm_tag'] = array(
1816 'dao' => 'CRM_Core_DAO_Tag',
1820 'title' => ts('Tag'),
1821 'type' => CRM_Utils_Type
::T_INT
,
1823 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1824 'options' => $contactTags,
1832 * Adds group filters to _columns (called from _Construct).
1834 public function buildGroupFilter() {
1835 $this->_columns
['civicrm_group']['filters'] = array(
1837 'name' => 'group_id',
1838 'title' => ts('Group'),
1839 'type' => CRM_Utils_Type
::T_INT
,
1840 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1842 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1845 if (empty($this->_columns
['civicrm_group']['dao'])) {
1846 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1848 if (empty($this->_columns
['civicrm_group']['alias'])) {
1849 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1854 * Get SQL operator from form text version.
1856 * @param string $operator
1860 public function getSQLOperator($operator = "like") {
1861 switch ($operator) {
1894 return 'IS NOT NULL';
1903 * Generate where clause.
1905 * This can be overridden in reports for special treatment of a field
1907 * @param array $field Field specifications
1908 * @param string $op Query operator (not an exact match to sql)
1909 * @param mixed $value
1913 * @return null|string
1915 public function whereClause(&$field, $op, $value, $min, $max) {
1917 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1919 // CRM-18010: Ensure type of each report filters
1921 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1928 if (($min !== NULL && strlen($min) > 0) ||
1929 ($max !== NULL && strlen($max) > 0)
1933 $min = CRM_Utils_Type
::escape($min, $type);
1935 $clauses[] = "( {$field['dbAlias']} >= $min )";
1938 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1942 $max = CRM_Utils_Type
::escape($max, $type);
1944 $clauses[] = "( {$field['dbAlias']} <= $max )";
1947 $clauses[] = "( {$field['dbAlias']} > $max )";
1951 if (!empty($clauses)) {
1953 $clause = implode(' AND ', $clauses);
1956 $clause = '(' . implode('OR', $clauses) . ')';
1964 if ($value !== NULL && strlen($value) > 0) {
1965 $value = CRM_Utils_Type
::escape($value, $type);
1966 if (strpos($value, '%') === FALSE) {
1967 $value = "'%{$value}%'";
1970 $value = "'{$value}'";
1972 $sqlOP = $this->getSQLOperator($op);
1973 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1979 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1980 $value = explode(',', $value);
1982 if ($value !== NULL && is_array($value) && count($value) > 0) {
1983 $sqlOP = $this->getSQLOperator($op);
1984 if (CRM_Utils_Array
::value('type', $field) ==
1985 CRM_Utils_Type
::T_STRING
1987 //cycle through selections and escape values
1988 foreach ($value as $key => $selection) {
1989 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1992 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1996 // for numerical values
1997 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
2000 if ($op == 'notin') {
2001 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
2004 $clause = "( " . $clause . " )";
2011 // multiple has or multiple not
2012 if ($value !== NULL && count($value) > 0) {
2013 $value = CRM_Utils_Type
::escapeAll($value, $type);
2014 $operator = $op == 'mnot' ?
'NOT' : '';
2015 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2016 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2022 if ($value !== NULL && strlen($value) > 0) {
2023 $value = CRM_Utils_Type
::escape($value, $type);
2024 if (strpos($value, '%') === FALSE) {
2026 $value = "'{$value}%'";
2029 $value = "'%{$value}'";
2033 $value = "'{$value}'";
2035 $sqlOP = $this->getSQLOperator($op);
2036 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2042 $sqlOP = $this->getSQLOperator($op);
2043 $clause = "( {$field['dbAlias']} $sqlOP )";
2049 //CRM-18457: some custom field passes value in array format against binary operator
2050 if (is_array($value) && count($value)) {
2055 if ($value !== NULL && $value !== '') {
2056 if (isset($field['clause'])) {
2057 // FIXME: we not doing escape here. Better solution is to use two
2058 // different types - data-type and filter-type
2059 $clause = $field['clause'];
2061 elseif (!is_array($value)) {
2062 $value = CRM_Utils_Type
::escape($value, $type);
2063 $sqlOP = $this->getSQLOperator($op);
2064 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
2065 $value = "'{$value}'";
2067 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2073 if (!empty($field['group']) && $clause) {
2074 $clause = $this->whereGroupClause($field, $value, $op);
2076 elseif (!empty($field['tag']) && $clause) {
2077 // not using left join in query because if any contact
2078 // belongs to more than one tag, results duplicate
2080 $clause = $this->whereTagClause($field, $value, $op);
2082 elseif (!empty($field['membership_org']) && $clause) {
2083 $clause = $this->whereMembershipOrgClause($value, $op);
2085 elseif (!empty($field['membership_type']) && $clause) {
2086 $clause = $this->whereMembershipTypeClause($value, $op);
2092 * Get SQL where clause for a date field.
2094 * @param string $fieldName
2095 * @param string $relative
2096 * @param string $from
2098 * @param string $type
2099 * @param string $fromTime
2100 * @param string $toTime
2102 * @return null|string
2104 public function dateClause(
2106 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2109 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2110 $sqlOP = $this->getSQLOperator($relative);
2111 return "( {$fieldName} {$sqlOP} )";
2114 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2117 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2118 $clauses[] = "( {$fieldName} >= $from )";
2122 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2123 $clauses[] = "( {$fieldName} <= {$to} )";
2126 if (!empty($clauses)) {
2127 return implode(' AND ', $clauses);
2134 * Get values for from and to for date ranges.
2138 * @param bool $relative
2139 * @param string $from
2141 * @param string $fromTime
2142 * @param string $toTime
2146 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2147 if (empty($toTime)) {
2148 // odd legacy behaviour to treat NULL as 'end of the day'
2149 // recommend updating reports to call CRM_Utils_Date::getFromTo
2150 //directly (default on the function is the actual default there).
2153 return CRM_Utils_Date
::getFromTo($relative, $from, $to, $fromTime, $toTime);
2157 * Alter display of rows.
2159 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2160 * such as rendering contacts as links.
2162 * @param array $rows
2163 * Rows generated by SQL, with an array for each row.
2165 public function alterDisplay(&$rows) {
2169 * Alter the way in which custom data fields are displayed.
2171 * @param array $rows
2173 public function alterCustomDataDisplay(&$rows) {
2174 // custom code to alter rows having custom values
2175 if (empty($this->_customGroupExtends
)) {
2179 $customFields = array();
2180 $customFieldIds = array();
2181 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2182 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2183 $customFieldIds[$fieldAlias] = $fieldId;
2186 if (empty($customFieldIds)) {
2190 // skip for type date and ContactReference since date format is already handled
2192 SELECT cg.table_name, cf.id
2193 FROM civicrm_custom_field cf
2194 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2195 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2196 cg.is_active = 1 AND
2197 cf.is_active = 1 AND
2198 cf.is_searchable = 1 AND
2199 cf.data_type NOT IN ('ContactReference', 'Date') AND
2200 cf.id IN (" . implode(",", $customFieldIds) . ")";
2202 $dao = CRM_Core_DAO
::executeQuery($query);
2203 while ($dao->fetch()) {
2204 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2208 $entryFound = FALSE;
2209 foreach ($rows as $rowNum => $row) {
2210 foreach ($row as $tableCol => $val) {
2211 if (array_key_exists($tableCol, $customFields)) {
2212 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2217 // skip looking further in rows, if first row itself doesn't
2218 // have the column we need
2226 * Remove duplicate rows.
2228 * @param array $rows
2230 public function removeDuplicates(&$rows) {
2231 if (empty($this->_noRepeats
)) {
2234 $checkList = array();
2236 foreach ($rows as $key => $list) {
2237 foreach ($list as $colName => $colVal) {
2238 if (array_key_exists($colName, $checkList) &&
2239 $checkList[$colName] == $colVal
2241 $rows[$key][$colName] = "";
2243 if (in_array($colName, $this->_noRepeats
)) {
2244 $checkList[$colName] = $colVal;
2251 * Fix subtotal display.
2254 * @param array $fields
2255 * @param bool $subtotal
2257 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2258 foreach ($row as $colName => $colVal) {
2259 if (in_array($colName, $fields)) {
2261 elseif (isset($this->_columnHeaders
[$colName])) {
2263 $row[$colName] = 'Subtotal';
2267 unset($row[$colName]);
2274 * Calculate grant total.
2276 * @param array $rows
2280 public function grandTotal(&$rows) {
2281 if (!$this->_rollup ||
count($rows) == 1) {
2285 $this->moveSummaryColumnsToTheRightHandSide();
2287 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2291 $this->rollupRow
= array_pop($rows);
2293 foreach ($this->_columnHeaders
as $fld => $val) {
2294 if (!in_array($fld, $this->_statFields
)) {
2295 if (!$this->_grandFlag
) {
2296 $this->rollupRow
[$fld] = ts('Grand Total');
2297 $this->_grandFlag
= TRUE;
2300 $this->rollupRow
[$fld] = "";
2305 $this->assign('grandStat', $this->rollupRow
);
2310 * Format display output.
2312 * @param array $rows
2313 * @param bool $pager
2315 public function formatDisplay(&$rows, $pager = TRUE) {
2316 // set pager based on if any limit was applied in the query.
2321 // allow building charts if any
2322 if (!empty($this->_params
['charts']) && !empty($rows)) {
2323 $this->buildChart($rows);
2324 $this->assign('chartEnabled', TRUE);
2325 $this->_chartId
= "{$this->_params['charts']}_" .
2326 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2328 $this->assign('chartId', $this->_chartId
);
2331 // unset columns not to be displayed.
2332 foreach ($this->_columnHeaders
as $key => $value) {
2333 if (!empty($value['no_display'])) {
2334 unset($this->_columnHeaders
[$key]);
2338 // unset columns not to be displayed.
2339 if (!empty($rows)) {
2340 foreach ($this->_noDisplay
as $noDisplayField) {
2341 foreach ($rows as $rowNum => $row) {
2342 unset($this->_columnHeaders
[$noDisplayField]);
2347 // build array of section totals
2348 $this->sectionTotals();
2350 // process grand-total row
2351 $this->grandTotal($rows);
2353 // Find alter display functions.
2354 $firstRow = reset($rows);
2356 $selectedFields = array_keys($firstRow);
2357 $alterFunctions = $alterMap = $alterSpecs = array();
2358 foreach ($this->_columns
as $tableName => $table) {
2359 if (array_key_exists('metadata', $table)) {
2360 foreach ($table['metadata'] as $field => $specs) {
2361 if (in_array($tableName . '_' . $field, $selectedFields)) {
2362 if (array_key_exists('alter_display', $specs)) {
2363 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2364 $alterMap[$tableName . '_' . $field] = $field;
2365 $alterSpecs[$tableName . '_' . $field] = NULL;
2367 // Add any alters that can be intuited from the field specs.
2368 // So far only boolean but a lot more could be.
2369 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2370 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2371 $alterMap[$tableName . '_' . $field] = $field;
2372 $alterSpecs[$tableName . '_' . $field] = NULL;
2379 // Run the alter display functions
2380 foreach ($rows as $index => & $row) {
2381 foreach ($row as $selectedField => $value) {
2382 if (array_key_exists($selectedField, $alterFunctions)) {
2383 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2389 // use this method for formatting rows for display purpose.
2390 $this->alterDisplay($rows);
2391 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2393 // use this method for formatting custom rows for display purpose.
2394 $this->alterCustomDataDisplay($rows);
2400 * @param $selectedfield
2401 * @param $criteriaFieldName
2405 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2406 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2407 $row[$selectedfield . '_link'] = $url;
2408 $row[$selectedfield . '_hover'] = ts("%1 for this state.", array(
2412 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2413 if (!is_array($states)) {
2421 * @param $selectedField
2422 * @param $criteriaFieldName
2426 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2427 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2428 $row[$selectedField . '_link'] = $url;
2429 $row[$selectedField . '_hover'] = ts("%1 for this country.", array(
2432 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2433 if (!is_array($countries)) {
2441 * @param $selectedfield
2442 * @param $criteriaFieldName
2446 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2447 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2448 $row[$selectedfield . '_link'] = $url;
2449 $row[$selectedfield . '_hover'] = ts("%1 for this county.", array(
2452 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2453 if (!is_array($counties)) {
2461 * @param $selectedfield
2462 * @param $criteriaFieldName
2466 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2467 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value);
2477 protected function alterContactID($value, &$row, $fieldname) {
2478 $nameField = substr($fieldname, 0, -2) . 'name';
2479 static $first = TRUE;
2480 static $viewContactList = FALSE;
2482 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2485 if (!$viewContactList) {
2488 if (array_key_exists($nameField, $row)) {
2489 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2492 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2502 protected function alterBoolean($value) {
2503 $options = array(0 => '', 1 => ts('Yes'));
2504 if (isset($options[$value])) {
2505 return $options[$value];
2513 * @param array $rows
2515 public function buildChart(&$rows) {
2516 // override this method for building charts.
2519 // select() method below has been added recently (v3.3), and many of the report templates might
2520 // still be having their own select() method. We should fix them as and when encountered and move
2521 // towards generalizing the select() method below.
2524 * Generate the SELECT clause and set class variable $_select.
2526 public function select() {
2527 $select = $this->_selectAliases
= array();
2528 $this->storeGroupByArray();
2530 foreach ($this->_columns
as $tableName => $table) {
2531 if (array_key_exists('fields', $table)) {
2532 foreach ($table['fields'] as $fieldName => $field) {
2533 if ($tableName == 'civicrm_address') {
2534 // deprecated, use $this->isTableSelected.
2535 $this->_addressField
= TRUE;
2537 if ($tableName == 'civicrm_email') {
2538 $this->_emailField
= TRUE;
2540 if ($tableName == 'civicrm_phone') {
2541 $this->_phoneField
= TRUE;
2544 if (!empty($field['required']) ||
2545 !empty($this->_params
['fields'][$fieldName])
2548 // 1. In many cases we want select clause to be built in slightly different way
2549 // for a particular field of a particular type.
2550 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2552 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2553 if ($selectClause) {
2554 $select[] = $selectClause;
2558 // include statistics columns only if set
2559 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2560 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2564 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2565 if ($selectClause) {
2566 $select[] = $selectClause;
2569 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2576 // select for group bys
2577 if (array_key_exists('group_bys', $table)) {
2578 foreach ($table['group_bys'] as $fieldName => $field) {
2580 if ($tableName == 'civicrm_address') {
2581 $this->_addressField
= TRUE;
2583 if ($tableName == 'civicrm_email') {
2584 $this->_emailField
= TRUE;
2586 if ($tableName == 'civicrm_phone') {
2587 $this->_phoneField
= TRUE;
2589 // 1. In many cases we want select clause to be built in slightly different way
2590 // for a particular field of a particular type.
2591 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2593 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2594 if ($selectClause) {
2595 $select[] = $selectClause;
2599 if (!empty($this->_params
['group_bys']) &&
2600 !empty($this->_params
['group_bys'][$fieldName]) &&
2601 !empty($this->_params
['group_bys_freq'])
2603 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2605 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2606 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2607 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2608 $field['title'] = 'Week';
2612 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2613 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2614 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2615 $field['title'] = 'Year';
2619 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2620 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2621 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2622 $field['title'] = 'Month';
2626 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2627 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2628 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2629 $field['title'] = 'Quarter';
2632 // for graphs and charts -
2633 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2634 $this->_interval
= $field['title'];
2635 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2636 = $field['title'] . ' Beginning';
2637 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2638 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2640 // just to make sure these values are transferred to rows.
2641 // since we 'll need them for calculation purpose,
2642 // e.g making subtotals look nicer or graphs
2643 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2644 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2651 if (empty($select)) {
2652 // CRM-21412 Do not give fatal error on report when no fields selected
2656 $this->_selectClauses
= $select;
2657 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2661 * Build select clause for a single field.
2663 * @param string $tableName
2664 * @param string $tableKey
2665 * @param string $fieldName
2666 * @param string $field
2670 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2671 if (!empty($field['pseudofield'])) {
2672 $alias = "{$tableName}_{$fieldName}";
2673 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2674 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2675 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = CRM_Utils_Array
::value('dbAlias', $field);
2676 $this->_selectAliases
[] = $alias;
2677 return ' 1 as ' . $alias;
2683 * Build where clause.
2685 public function where() {
2686 $this->storeWhereHavingClauseArray();
2688 if (empty($this->_whereClauses
)) {
2689 $this->_where
= "WHERE ( 1 ) ";
2690 $this->_having
= "";
2693 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2696 if ($this->_aclWhere
) {
2697 $this->_where
.= " AND {$this->_aclWhere} ";
2700 if (!empty($this->_havingClauses
)) {
2701 // use this clause to construct group by clause.
2702 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2707 * Store Where clauses into an array.
2709 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2710 * temp table that may not be part of the final where clause or added
2711 * in other functions
2713 public function storeWhereHavingClauseArray() {
2714 foreach ($this->_columns
as $tableName => $table) {
2715 if (array_key_exists('filters', $table)) {
2716 foreach ($table['filters'] as $fieldName => $field) {
2717 // respect pseudofield to filter spec so fields can be marked as
2718 // not to be handled here
2719 if (!empty($field['pseudofield'])) {
2722 $clause = $this->generateFilterClause($field, $fieldName);
2724 if (!empty($clause)) {
2725 if (!empty($field['having'])) {
2726 $this->_havingClauses
[] = $clause;
2729 $this->_whereClauses
[] = $clause;
2741 public function processReportMode() {
2742 $this->setOutputMode();
2745 = CRM_Utils_Request
::retrieve(
2748 CRM_Core_DAO
::$_nullObject
2751 $this->_absoluteUrl
= FALSE;
2753 $this->assign('printOnly', FALSE);
2755 if ($this->_outputMode
== 'print' ||
2756 ($this->_sendmail
&& !$this->_outputMode
)
2758 $this->assign('printOnly', TRUE);
2760 $this->addPaging
= FALSE;
2761 $this->assign('outputMode', 'print');
2762 $this->_outputMode
= 'print';
2763 if ($this->_sendmail
) {
2764 $this->_absoluteUrl
= TRUE;
2767 elseif ($this->_outputMode
== 'pdf') {
2769 $this->addPaging
= FALSE;
2770 $this->_absoluteUrl
= TRUE;
2772 elseif ($this->_outputMode
== 'csv') {
2774 $this->_absoluteUrl
= TRUE;
2775 $this->addPaging
= FALSE;
2777 elseif ($this->_outputMode
== 'group') {
2778 $this->assign('outputMode', 'group');
2780 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2781 $this->assign('outputMode', 'create_report');
2783 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2784 $this->_createNew
= TRUE;
2787 $this->assign('outputMode', $this->_outputMode
);
2788 $this->assign('printOnly', $printOnly);
2789 // Get today's date to include in printed reports
2791 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2792 $this->assign('reportDate', $reportDate);
2797 * Post Processing function for Form.
2799 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2800 * This function is not accessed when the api calls the report.
2802 public function beginPostProcess() {
2803 $this->setParams($this->controller
->exportValues($this->_name
));
2804 if (empty($this->_params
) &&
2807 $this->setParams($this->_formValues
);
2810 // hack to fix params when submitted from dashboard, CRM-8532
2811 // fields array is missing because form building etc is skipped
2812 // in dashboard mode for report
2813 //@todo - this could be done in the dashboard no we have a setter
2814 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2815 $this->setParams($this->_formValues
);
2818 $this->processReportMode();
2820 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2821 $this->_createNew
= ($this->_outputMode
== 'copy');
2822 CRM_Report_Form_Instance
::postProcess($this);
2824 if ($this->_outputMode
== 'delete') {
2825 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2828 $this->_formValues
= $this->_params
;
2830 $this->beginPostProcessCommon();
2834 * BeginPostProcess function run in both report mode and non-report mode (api).
2836 public function beginPostProcessCommon() {
2840 * Build the report query.
2842 * @param bool $applyLimit
2846 public function buildQuery($applyLimit = TRUE) {
2847 $this->buildGroupTempTable();
2850 $this->customDataFrom();
2851 $this->buildPermissionClause();
2856 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
2857 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
2859 $clause = "{$field['dbAlias']} as {$alias}";
2861 $this->_select
.= ", $clause ";
2864 if ($applyLimit && empty($this->_params
['charts'])) {
2867 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2869 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2870 $this->addToDeveloperTab($sql);
2875 * Build group by clause.
2877 public function groupBy() {
2878 $this->storeGroupByArray();
2880 if (!empty($this->_groupByArray
)) {
2881 if ($this->optimisedForOnlyFullGroupBy
) {
2882 // We should probably deprecate this code path. What happens here is that
2883 // the group by is amended to reflect the select columns. This often breaks the
2884 // results. Retrofitting group strict group by onto existing report classes
2886 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2889 $this->_groupBy
= ' GROUP BY ' . implode($this->_groupByArray
);
2895 * Build order by clause.
2897 public function orderBy() {
2898 $this->_orderBy
= "";
2899 $this->_sections
= array();
2900 $this->storeOrderByArray();
2901 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2902 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2904 $this->assign('sections', $this->_sections
);
2908 * Extract order by fields and store as an array.
2910 * In some cases other functions want to know which fields are selected for ordering by
2911 * Separating this into a separate function allows it to be called separately from constructing
2912 * the order by clause
2914 public function storeOrderByArray() {
2915 $orderBys = array();
2917 if (!empty($this->_params
['order_bys']) &&
2918 is_array($this->_params
['order_bys']) &&
2919 !empty($this->_params
['order_bys'])
2922 // Process order_bys in user-specified order
2923 foreach ($this->_params
['order_bys'] as $orderBy) {
2924 $orderByField = array();
2925 foreach ($this->_columns
as $tableName => $table) {
2926 if (array_key_exists('order_bys', $table)) {
2927 // For DAO columns defined in $this->_columns
2928 $fields = $table['order_bys'];
2930 elseif (array_key_exists('extends', $table)) {
2931 // For custom fields referenced in $this->_customGroupExtends
2932 $fields = CRM_Utils_Array
::value('fields', $table, array());
2937 if (!empty($fields) && is_array($fields)) {
2938 foreach ($fields as $fieldName => $field) {
2939 if ($fieldName == $orderBy['column']) {
2940 $orderByField = array_merge($field, $orderBy);
2941 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2948 if (!empty($orderByField)) {
2949 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2950 if ($this->groupConcatTested
) {
2951 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
2954 // Not sure when this is preferable to using tplField (which has
2955 // definitely been tested to work in cases then this does not.
2956 // in caution not switching unless report has been tested for
2957 // group concat functionality.
2958 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2961 // Record any section headers for assignment to the template
2962 if (!empty($orderBy['section'])) {
2963 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2964 $this->_sections
[$orderByField['tplField']] = $orderByField;
2970 $this->_orderByArray
= $orderBys;
2972 $this->assign('sections', $this->_sections
);
2976 * Determine unselected columns.
2980 public function unselectedOrderByColumns() {
2981 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
2985 * Determine unselected columns.
2989 public function unselectedSectionColumns() {
2990 if (is_array($this->_sections
)) {
2991 return array_diff_key($this->_sections
, $this->getSelectColumns());
2999 * Build output rows.
3001 * @param string $sql
3002 * @param array $rows
3004 public function buildRows($sql, &$rows) {
3005 if (!$this->optimisedForOnlyFullGroupBy
) {
3006 CRM_Core_DAO
::disableFullGroupByMode();
3008 $dao = CRM_Core_DAO
::executeQuery($sql);
3009 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
3010 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
3012 CRM_Core_DAO
::reenableFullGroupByMode();
3013 if (!is_array($rows)) {
3017 // use this method to modify $this->_columnHeaders
3018 $this->modifyColumnHeaders();
3020 $unselectedSectionColumns = $this->unselectedSectionColumns();
3022 while ($dao->fetch()) {
3024 foreach ($this->_columnHeaders
as $key => $value) {
3025 if (property_exists($dao, $key)) {
3026 $row[$key] = $dao->$key;
3030 // section headers not selected for display need to be added to row
3031 foreach ($unselectedSectionColumns as $key => $values) {
3032 if (property_exists($dao, $key)) {
3033 $row[$key] = $dao->$key;
3042 * Calculate section totals.
3044 * When "order by" fields are marked as sections, this assigns to the template
3045 * an array of total counts for each section. This data is used by the Smarty
3046 * plugin {sectionTotal}.
3048 public function sectionTotals() {
3050 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3051 if (empty($this->_selectAliases
)) {
3055 if (!empty($this->_sections
)) {
3056 // build the query with no LIMIT clause
3057 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3058 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3060 // pull section aliases out of $this->_sections
3061 $sectionAliases = array_keys($this->_sections
);
3064 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3065 $ifnulls[] = "ifnull($alias, '') as $alias";
3067 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3068 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3070 // Group (un-limited) report by all aliases and get counts. This might
3071 // be done more efficiently when the contents of $sql are known, ie. by
3072 // overriding this method in the report class.
3074 $query = $this->_select
.
3075 ", count(*) as ct from ($sql) as subquery group by " .
3076 implode(", ", $sectionAliases);
3078 // initialize array of total counts
3080 $dao = CRM_Core_DAO
::executeQuery($query);
3081 while ($dao->fetch()) {
3083 // let $this->_alterDisplay translate any integer ids to human-readable values.
3084 $rows[0] = $dao->toArray();
3085 $this->alterDisplay($rows);
3088 // add totals for all permutations of section values
3091 $aliasCount = count($sectionAliases);
3092 foreach ($sectionAliases as $alias) {
3093 $values[] = $row[$alias];
3094 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3095 if ($i == $aliasCount) {
3096 // the last alias is the lowest-level section header; use count as-is
3097 $totals[$key] = $dao->ct
;
3100 // other aliases are higher level; roll count into their total
3101 $totals[$key] +
= $dao->ct
;
3105 $this->assign('sectionTotals', $totals);
3110 * Modify column headers.
3112 public function modifyColumnHeaders() {
3113 // use this method to modify $this->_columnHeaders
3117 * Move totals columns to the right edge of the table.
3119 * It seems like a more logical layout to have any totals columns on the far right regardless of
3120 * the location of the rest of their table.
3122 public function moveSummaryColumnsToTheRightHandSide() {
3123 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3124 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3128 * Assign rows to the template.
3130 * @param array $rows
3132 public function doTemplateAssignment(&$rows) {
3133 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
3134 $this->assign_by_ref('rows', $rows);
3135 $this->assign('statistics', $this->statistics($rows));
3139 * Build report statistics.
3141 * Override this method to build your own statistics.
3143 * @param array $rows
3147 public function statistics(&$rows) {
3148 $statistics = array();
3150 $count = count($rows);
3151 // Why do we increment the count for rollup seems to artificially inflate the count.
3152 // It seems perhaps intentional to include the summary row in the count of results - although
3153 // this just seems odd.
3154 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3158 $this->countStat($statistics, $count);
3160 $this->groupByStat($statistics);
3162 $this->filterStat($statistics);
3168 * Add count statistics.
3170 * @param array $statistics
3173 public function countStat(&$statistics, $count) {
3174 $statistics['counts']['rowCount'] = array(
3175 'title' => ts('Row(s) Listed'),
3179 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3180 $statistics['counts']['rowsFound'] = array(
3181 'title' => ts('Total Row(s)'),
3182 'value' => $this->_rowsFound
,
3188 * Add group by statistics.
3190 * @param array $statistics
3192 public function groupByStat(&$statistics) {
3193 if (!empty($this->_params
['group_bys']) &&
3194 is_array($this->_params
['group_bys']) &&
3195 !empty($this->_params
['group_bys'])
3197 foreach ($this->_columns
as $tableName => $table) {
3198 if (array_key_exists('group_bys', $table)) {
3199 foreach ($table['group_bys'] as $fieldName => $field) {
3200 if (!empty($this->_params
['group_bys'][$fieldName])) {
3201 $combinations[] = $field['title'];
3206 $statistics['groups'][] = array(
3207 'title' => ts('Grouping(s)'),
3208 'value' => implode(' & ', $combinations),
3214 * Filter statistics.
3216 * @param array $statistics
3218 public function filterStat(&$statistics) {
3219 foreach ($this->_columns
as $tableName => $table) {
3220 if (array_key_exists('filters', $table)) {
3221 foreach ($table['filters'] as $fieldName => $field) {
3222 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3223 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3224 CRM_Utils_Array
::value('operatorType', $field) !=
3225 CRM_Report_Form
::OP_MONTH
3229 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3230 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3231 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3232 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3233 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3235 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3236 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3238 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3239 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3242 $statistics['filters'][] = array(
3243 'title' => $field['title'],
3244 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3247 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3248 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3250 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3251 $statistics['filters'][] = array(
3252 'title' => $field['title'],
3253 'value' => $pair[$rel],
3258 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3261 $pair = $this->getOperationPair(
3262 CRM_Utils_Array
::value('operatorType', $field),
3265 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3266 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3267 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3268 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3269 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3271 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3272 $this->setEntityRefDefaults($field, $tableName);
3273 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3274 array('id' => $val) +
3275 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3277 foreach ($result['values'] as $v) {
3278 $values[] = $v['label'];
3280 $value = "{$pair[$op]} " . implode(', ', $values);
3282 elseif ($op == 'nll' ||
$op == 'nnll') {
3283 $value = $pair[$op];
3285 elseif (is_array($val) && (!empty($val))) {
3286 $options = CRM_Utils_Array
::value('options', $field, array());
3287 foreach ($val as $key => $valIds) {
3288 if (isset($options[$valIds])) {
3289 $val[$key] = $options[$valIds];
3292 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3293 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3294 $val = implode(', ', $val);
3295 $value = "{$pair[$op]} " . $val;
3297 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3298 isset($field['options']) &&
3299 is_array($field['options']) && !empty($field['options'])
3301 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3302 CRM_Utils_Array
::value($val, $field['options'], $val);
3305 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3308 if ($value && empty($field['no_display'])) {
3309 $statistics['filters'][] = array(
3310 'title' => CRM_Utils_Array
::value('title', $field),
3321 * End post processing.
3323 * @param array|null $rows
3325 public function endPostProcess(&$rows = NULL) {
3326 $this->assign('report_class', get_class($this));
3327 if ($this->_storeResultSet
) {
3328 $this->_resultSet
= $rows;
3331 if ($this->_outputMode
== 'print' ||
3332 $this->_outputMode
== 'pdf' ||
3336 $content = $this->compileContent();
3337 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3341 if ($this->_sendmail
) {
3342 $config = CRM_Core_Config
::singleton();
3343 $attachments = array();
3345 if ($this->_outputMode
== 'csv') {
3347 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3348 ": {$url}</p>" . '<p>' .
3349 ts('The report is attached as a CSV file.') . '</p>' .
3350 $this->_formValues
['report_footer'];
3352 $csvFullFilename = $config->templateCompileDir
.
3353 CRM_Utils_File
::makeFileName('CiviReport.csv');
3354 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3355 file_put_contents($csvFullFilename, $csvContent);
3356 $attachments[] = array(
3357 'fullPath' => $csvFullFilename,
3358 'mime_type' => 'text/csv',
3359 'cleanName' => 'CiviReport.csv',
3362 if ($this->_outputMode
== 'pdf') {
3363 // generate PDF content
3364 $pdfFullFilename = $config->templateCompileDir
.
3365 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3366 file_put_contents($pdfFullFilename,
3367 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3368 TRUE, array('orientation' => 'landscape')
3371 // generate Email Content
3373 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3374 ": {$url}</p>" . '<p>' .
3375 ts('The report is attached as a PDF file.') . '</p>' .
3376 $this->_formValues
['report_footer'];
3378 $attachments[] = array(
3379 'fullPath' => $pdfFullFilename,
3380 'mime_type' => 'application/pdf',
3381 'cleanName' => 'CiviReport.pdf',
3385 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3386 $this->_outputMode
, $attachments
3389 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3392 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3396 elseif ($this->_outputMode
== 'print') {
3400 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3401 $config = CRM_Core_Config
::singleton();
3402 //get chart image name
3403 $chartImg = $this->_chartId
. '.png';
3404 //get image url path
3406 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3408 $uploadUrl .= $chartImg;
3409 //get image doc path to overwrite
3411 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3412 'openFlashChart/' . $chartImg;
3414 $chart = imagecreatefrompng($uploadUrl);
3415 //convert it into formatted png
3416 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3417 //overwrite with same image
3418 imagepng($chart, $uploadImg);
3420 imagedestroy($chart);
3422 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3424 CRM_Utils_System
::civiExit();
3426 elseif ($this->_outputMode
== 'csv') {
3427 CRM_Report_Utils_Report
::export2csv($this, $rows);
3429 elseif ($this->_outputMode
== 'group') {
3430 $group = $this->_params
['groups'];
3431 $this->add2group($group);
3436 * Set store result set indicator to TRUE.
3438 * @todo explain what this does
3440 public function storeResultSet() {
3441 $this->_storeResultSet
= TRUE;
3449 public function getResultSet() {
3450 return $this->_resultSet
;
3454 * Get the sql used to generate the report.
3458 public function getReportSql() {
3459 return $this->sqlArray
;
3463 * Use the form name to create the tpl file name.
3467 public function getTemplateFileName() {
3468 $defaultTpl = parent
::getTemplateFileName();
3469 $template = CRM_Core_Smarty
::singleton();
3470 if (!$template->template_exists($defaultTpl)) {
3471 $defaultTpl = 'CRM/Report/Form.tpl';
3477 * Compile the report content.
3479 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3483 public function compileContent() {
3484 $templateFile = $this->getHookedTemplateFileName();
3485 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3486 CRM_Core_Form
::$_template->fetch($templateFile) .
3487 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3492 * Post process function.
3494 public function postProcess() {
3495 // get ready with post process params
3496 $this->beginPostProcess();
3499 $sql = $this->buildQuery();
3501 // build array of result based on column headers. This method also allows
3502 // modifying column headers before using it to build result set i.e $rows.
3504 $this->buildRows($sql, $rows);
3506 // format result set.
3507 $this->formatDisplay($rows);
3509 // assign variables to templates
3510 $this->doTemplateAssignment($rows);
3512 // do print / pdf / instance stuff if needed
3513 $this->endPostProcess($rows);
3519 * @param int $rowCount
3523 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3524 // lets do the pager if in html mode
3525 $this->_limit
= NULL;
3527 // CRM-14115, over-ride row count if rowCount is specified in URL
3528 if ($this->_dashBoardRowCount
) {
3529 $rowCount = $this->_dashBoardRowCount
;
3531 if ($this->addPaging
) {
3532 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3534 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3536 // @todo all http vars should be extracted in the preProcess
3537 // - not randomly in the class
3538 if (!$pageId && !empty($_POST)) {
3539 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3540 $pageId = max((int) $_POST['crmPID_B'], 1);
3542 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3543 $pageId = max((int) $_POST['crmPID'], 1);
3545 unset($_POST['crmPID_B'], $_POST['crmPID']);
3548 $pageId = $pageId ?
$pageId : 1;
3549 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3550 $offset = ($pageId - 1) * $rowCount;
3552 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3553 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3555 $this->_limit
= " LIMIT $offset, $rowCount";
3556 return array($offset, $rowCount);
3558 if ($this->_limitValue
) {
3559 if ($this->_offsetValue
) {
3560 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3563 $this->_limit
= " LIMIT " . $this->_limitValue
;
3571 * @param int $rowCount
3573 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3574 // CRM-14115, over-ride row count if rowCount is specified in URL
3575 if ($this->_dashBoardRowCount
) {
3576 $rowCount = $this->_dashBoardRowCount
;
3579 if ($this->_limit
&& ($this->_limit
!= '')) {
3580 if (!$this->_rowsFound
) {
3581 $sql = "SELECT FOUND_ROWS();";
3582 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3585 'total' => $this->_rowsFound
,
3586 'rowCount' => $rowCount,
3587 'status' => ts('Records') . ' %%StatusMessage%%',
3588 'buttonBottom' => 'PagerBottomButton',
3589 'buttonTop' => 'PagerTopButton',
3591 if (!empty($this->controller
)) {
3592 // This happens when being called from the api Really we want the api to be able to
3593 // pass paging parameters, but at this stage just preventing test crashes.
3594 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3597 $pager = new CRM_Utils_Pager($params);
3598 $this->assign_by_ref('pager', $pager);
3599 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3604 * Build a group filter with contempt for large data sets.
3606 * This function has been retained as it takes time to migrate the reports over
3607 * to the new method which will not crash on large datasets.
3611 * @param string $field
3612 * @param mixed $value
3617 public function legacySlowGroupFilterClause($field, $value, $op) {
3618 $smartGroupQuery = "";
3620 $group = new CRM_Contact_DAO_Group();
3621 $group->is_active
= 1;
3623 $smartGroups = array();
3624 while ($group->fetch()) {
3625 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3626 $group->saved_search_id
3628 $smartGroups[] = $group->id
;
3632 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3634 $smartGroupQuery = '';
3635 if (!empty($smartGroups)) {
3636 $smartGroups = implode(',', $smartGroups);
3637 $smartGroupQuery = " UNION DISTINCT
3638 SELECT DISTINCT smartgroup_contact.contact_id
3639 FROM civicrm_group_contact_cache smartgroup_contact
3640 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3643 $sqlOp = $this->getSQLOperator($op);
3644 if (!is_array($value)) {
3645 $value = array($value);
3647 //include child groups if any
3648 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3650 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3652 $contactAlias = $this->_aliases
['civicrm_contact'];
3653 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3654 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3656 return " {$contactAlias}.id {$sqlOp} (
3657 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3658 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3659 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3660 {$smartGroupQuery} ) ";
3664 * Build where clause for groups.
3666 * @param string $field
3667 * @param mixed $value
3672 public function whereGroupClause($field, $value, $op) {
3673 if ($this->groupFilterNotOptimised
) {
3674 return $this->legacySlowGroupFilterClause($field, $value, $op);
3676 if ($op === 'notin') {
3677 return " group_temp_table.id IS NULL ";
3679 // We will have used an inner join instead.
3685 * Create a table of the contact ids included by the group filter.
3687 * This function is called by both the api (tests) and the UI.
3689 public function buildGroupTempTable() {
3690 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3693 $filteredGroups = (array) $this->_params
['gid_value'];
3695 $groups = civicrm_api3('Group', 'get', array(
3697 'id' => array('IN' => $filteredGroups),
3698 'saved_search_id' => array('>' => 0),
3701 $smartGroups = array_keys($groups['values']);
3704 SELECT DISTINCT group_contact.contact_id as id
3705 FROM civicrm_group_contact group_contact
3706 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3707 AND group_contact.status = 'Added' ";
3709 if (!empty($smartGroups)) {
3710 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3711 $smartGroups = implode(',', $smartGroups);
3714 SELECT smartgroup_contact.contact_id as id
3715 FROM civicrm_group_contact_cache smartgroup_contact
3716 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3719 $this->groupTempTable
= $this->createTemporaryTable('rptgrp', $query);
3720 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3724 * Execute query and add it to the developer tab.
3726 * @param string $query
3727 * @param array $params
3729 * @return \CRM_Core_DAO|object
3731 protected function executeReportQuery($query, $params = array()) {
3732 $this->addToDeveloperTab($query);
3733 return CRM_Core_DAO
::executeQuery($query, $params);
3737 * Build where clause for tags.
3739 * @param string $field
3740 * @param mixed $value
3745 public function whereTagClause($field, $value, $op) {
3746 // not using left join in query because if any contact
3747 // belongs to more than one tag, results duplicate
3749 $sqlOp = $this->getSQLOperator($op);
3750 if (!is_array($value)) {
3751 $value = array($value);
3753 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3754 $entity_table = $this->_tagFilterTable
;
3755 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3756 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3757 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3758 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3762 * Generate membership organization clause.
3764 * @param mixed $value
3765 * @param string $op SQL Operator
3769 public function whereMembershipOrgClause($value, $op) {
3770 $sqlOp = $this->getSQLOperator($op);
3771 if (!is_array($value)) {
3772 $value = array($value);
3775 $tmp_membership_org_sql_list = implode(', ', $value);
3776 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3777 SELECT DISTINCT mem.contact_id
3778 FROM civicrm_membership mem
3779 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3780 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3781 WHERE mt.member_of_contact_id IN (" .
3782 $tmp_membership_org_sql_list . ")
3783 AND mt.is_active = '1'
3784 AND mem_status.is_current_member = '1'
3785 AND mem_status.is_active = '1' ) ";
3789 * Generate Membership Type SQL Clause.
3791 * @param mixed $value
3797 public function whereMembershipTypeClause($value, $op) {
3798 $sqlOp = $this->getSQLOperator($op);
3799 if (!is_array($value)) {
3800 $value = array($value);
3803 $tmp_membership_sql_list = implode(', ', $value);
3804 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3805 SELECT DISTINCT mem.contact_id
3806 FROM civicrm_membership mem
3807 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3808 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3809 WHERE mem.membership_type_id IN (" .
3810 $tmp_membership_sql_list . ")
3811 AND mt.is_active = '1'
3812 AND mem_status.is_current_member = '1'
3813 AND mem_status.is_active = '1' ) ";
3817 * Buld contact acl clause
3818 * @deprecated in favor of buildPermissionClause
3820 * @param string $tableAlias
3822 public function buildACLClause($tableAlias = 'contact_a') {
3823 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3827 * Build the permision clause for all entities in this report
3829 public function buildPermissionClause() {
3831 foreach ($this->selectedTables() as $tableName) {
3832 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3833 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3834 $tableAlias = $this->_columns
[$tableName]['alias'];
3835 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3836 foreach ($clauses as $field => $clause) {
3837 // Skip contact_id field if redundant
3838 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3839 $ret["$tableName.$field"] = $clause;
3844 // Override output from buildACLClause
3845 $this->_aclFrom
= NULL;
3846 $this->_aclWhere
= implode(' AND ', $ret);
3850 * Add custom data to the columns.
3852 * @param bool $addFields
3853 * @param array $permCustomGroupIds
3855 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3856 if (empty($this->_customGroupExtends
)) {
3859 if (!is_array($this->_customGroupExtends
)) {
3860 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3862 $customGroupWhere = '';
3863 if (!empty($permCustomGroupIds)) {
3864 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3868 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3869 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3870 FROM civicrm_custom_group cg
3871 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3872 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3874 cg.is_active = 1 AND
3875 cf.is_active = 1 AND
3876 cf.is_searchable = 1
3877 ORDER BY cg.weight, cf.weight";
3878 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3881 while ($customDAO->fetch()) {
3882 if ($customDAO->table_name
!= $curTable) {
3883 $curTable = $customDAO->table_name
;
3884 $curFields = $curFilters = array();
3887 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3888 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3889 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3890 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3892 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3893 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3894 $this->_columns
[$curTable][$colKey] = array();
3898 $fieldName = 'custom_' . $customDAO->cf_id
;
3901 // this makes aliasing work in favor
3902 $curFields[$fieldName] = array(
3903 'name' => $customDAO->column_name
,
3904 'title' => $customDAO->label
,
3905 'dataType' => $customDAO->data_type
,
3906 'htmlType' => $customDAO->html_type
,
3909 if ($this->_customGroupFilters
) {
3910 // this makes aliasing work in favor
3911 $curFilters[$fieldName] = array(
3912 'name' => $customDAO->column_name
,
3913 'title' => $customDAO->label
,
3914 'dataType' => $customDAO->data_type
,
3915 'htmlType' => $customDAO->html_type
,
3919 switch ($customDAO->data_type
) {
3922 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3923 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3924 // CRM-6946, show time part for datetime date fields
3925 if ($customDAO->time_format
) {
3926 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3931 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3932 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3933 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3937 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3938 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3942 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3943 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3944 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3948 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3949 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3953 case 'StateProvince':
3955 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3957 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3958 if ((is_array($options) && count($options) != 0) ||
(!is_array($options) && $options !== FALSE)) {
3959 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3960 $curFilters[$fieldName]['options'] = $options;
3964 case 'ContactReference':
3965 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3966 $curFilters[$fieldName]['name'] = 'display_name';
3967 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3969 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3970 $curFields[$fieldName]['name'] = 'display_name';
3971 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3975 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3976 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3980 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3981 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3982 if ($options !== FALSE) {
3983 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3984 $curFilters[$fieldName]['options'] = $options;
3988 if (!array_key_exists('type', $curFields[$fieldName])) {
3989 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3993 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3995 if ($this->_customGroupFilters
) {
3996 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3998 if ($this->_customGroupGroupBy
) {
3999 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
4005 * Build custom data from clause.
4007 * @param bool $joinsForFiltersOnly
4008 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
4010 public function customDataFrom($joinsForFiltersOnly = FALSE) {
4011 if (empty($this->_customGroupExtends
)) {
4014 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
4015 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
4016 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
4017 $customTables = array();
4018 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
4019 while ($customTablesDAO->fetch()) {
4020 $customTables[] = $customTablesDAO->table_name
;
4023 foreach ($this->_columns
as $table => $prop) {
4024 if (in_array($table, $customTables)) {
4025 $extendsTable = $mapper[$prop['extends']];
4026 // Check field is required for rendering the report.
4027 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4030 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
4032 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
4034 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4035 // handle for ContactReference
4036 if (array_key_exists('fields', $prop)) {
4037 foreach ($prop['fields'] as $fieldName => $field) {
4038 if (CRM_Utils_Array
::value('dataType', $field) ==
4041 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4043 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4052 * Check if the field is selected.
4054 * @param string $prop
4058 public function isFieldSelected($prop) {
4063 if (!empty($this->_params
['fields'])) {
4064 foreach (array_keys($prop['fields']) as $fieldAlias) {
4065 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4066 if ($customFieldId) {
4067 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4071 //might be survey response field.
4072 if (!empty($this->_params
['fields']['survey_response']) &&
4073 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4081 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4082 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4083 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4084 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4091 if (!empty($this->_params
['order_bys'])) {
4092 foreach (array_keys($prop['fields']) as $fieldAlias) {
4093 foreach ($this->_params
['order_bys'] as $orderBy) {
4094 if ($fieldAlias == $orderBy['column'] &&
4095 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4102 return $this->isFieldFiltered($prop);
4107 * Check if the field is used as a filter.
4109 * @param string $prop
4113 protected function isFieldFiltered($prop) {
4114 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4115 foreach ($prop['filters'] as $fieldAlias => $val) {
4124 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4125 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4126 ||
($attach != 'relative' &&
4127 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4133 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4134 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
4145 * Check for empty order_by configurations and remove them.
4147 * Also set template to hide them.
4149 * @param array $formValues
4151 public function preProcessOrderBy(&$formValues) {
4152 // Object to show/hide form elements
4153 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4155 $_showHide->addShow('optionField_1');
4157 // Cycle through order_by options; skip any empty ones, and hide them as well
4160 if (!empty($formValues['order_bys'])) {
4161 foreach ($formValues['order_bys'] as $order_by) {
4162 if ($order_by['column'] && $order_by['column'] != '-') {
4163 $_showHide->addShow('optionField_' . $n);
4164 $orderBys[$n] = $order_by;
4169 for ($i = $n; $i <= 5; $i++
) {
4171 $_showHide->addHide('optionField_' . $i);
4175 // overwrite order_by options with modified values
4176 if (!empty($orderBys)) {
4177 $formValues['order_bys'] = $orderBys;
4180 $formValues['order_bys'] = array(1 => array('column' => '-'));
4183 // assign show/hide data to template
4184 $_showHide->addToTemplate();
4188 * Check if table name has columns in SELECT clause.
4190 * @param string $tableName
4191 * Name of table (index of $this->_columns array).
4195 public function isTableSelected($tableName) {
4196 return in_array($tableName, $this->selectedTables());
4200 * Check if table name has columns in WHERE or HAVING clause.
4202 * @param string $tableName
4203 * Name of table (index of $this->_columns array).
4207 public function isTableFiltered($tableName) {
4208 // Cause the array to be generated if not previously done.
4209 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4210 $this->selectedTables();
4212 return in_array($tableName, $this->filteredTables
);
4216 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4218 * If the array is unset it will be built.
4223 public function selectedTables() {
4224 if (!$this->_selectedTables
) {
4225 $orderByColumns = array();
4226 if (array_key_exists('order_bys', $this->_params
) &&
4227 is_array($this->_params
['order_bys'])
4229 foreach ($this->_params
['order_bys'] as $orderBy) {
4230 $orderByColumns[] = $orderBy['column'];
4234 foreach ($this->_columns
as $tableName => $table) {
4235 if (array_key_exists('fields', $table)) {
4236 foreach ($table['fields'] as $fieldName => $field) {
4237 if (!empty($field['required']) ||
4238 !empty($this->_params
['fields'][$fieldName])
4240 $this->_selectedTables
[] = $tableName;
4245 if (array_key_exists('order_bys', $table)) {
4246 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4247 if (in_array($orderByName, $orderByColumns)) {
4248 $this->_selectedTables
[] = $tableName;
4253 if (array_key_exists('filters', $table)) {
4254 foreach ($table['filters'] as $filterName => $filter) {
4255 if (!empty($this->_params
["{$filterName}_value"])
4256 ||
!empty($this->_params
["{$filterName}_relative"])
4257 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4259 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4262 $this->_selectedTables
[] = $tableName;
4263 $this->filteredTables
[] = $tableName;
4270 return $this->_selectedTables
;
4274 * Add campaign fields.
4276 * @param bool $groupBy
4277 * Add GroupBy? Not appropriate for detail report.
4278 * @param bool $orderBy
4279 * Add OrderBy? Not appropriate for detail report.
4280 * @param bool $filters
4283 public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) {
4284 // Check if CiviCampaign is a) enabled and b) has active campaigns
4285 $config = CRM_Core_Config
::singleton();
4286 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents
);
4287 if ($campaignEnabled) {
4288 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE);
4289 // If we have a campaign, build out the relevant elements
4290 if (!empty($getCampaigns['campaigns'])) {
4291 $this->campaigns
= $getCampaigns['campaigns'];
4292 asort($this->campaigns
);
4293 $this->_columns
[$entityTable]['fields']['campaign_id'] = array('title' => ts('Campaign'), 'default' => 'false');
4295 $this->_columns
[$entityTable]['filters']['campaign_id'] = array(
4296 'title' => ts('Campaign'),
4297 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4298 'options' => $this->campaigns
,
4299 'type' => CRM_Utils_Type
::T_INT
,
4304 $this->_columns
[$entityTable]['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
4308 $this->_columns
[$entityTable]['order_bys']['campaign_id'] = array('title' => ts('Campaign'));
4315 * Add address fields.
4317 * @deprecated - use getAddressColumns which is a more accurate description
4318 * and also accepts an array of options rather than a long list
4320 * adding address fields to construct function in reports
4322 * @param bool $groupBy
4323 * Add GroupBy? Not appropriate for detail report.
4324 * @param bool $orderBy
4325 * Add GroupBy? Not appropriate for detail report.
4326 * @param bool $filters
4327 * @param array $defaults
4330 * address fields for construct clause
4332 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4333 $defaultAddressFields = array(
4334 'street_address' => ts('Street Address'),
4335 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4336 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4337 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4338 'street_number' => ts('Street Number'),
4339 'street_name' => ts('Street Name'),
4340 'street_unit' => ts('Street Unit'),
4341 'city' => ts('City'),
4342 'postal_code' => ts('Postal Code'),
4343 'postal_code_suffix' => ts('Postal Code Suffix'),
4344 'country_id' => ts('Country'),
4345 'state_province_id' => ts('State/Province'),
4346 'county_id' => ts('County'),
4348 $addressFields = array(
4349 'civicrm_address' => array(
4350 'dao' => 'CRM_Core_DAO_Address',
4352 'address_name' => array(
4353 'title' => ts('Address Name'),
4354 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4358 'grouping' => 'location-fields',
4361 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4362 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4363 'title' => $fieldLabel,
4364 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4368 $street_address_filters = $general_address_filters = array();
4370 // Address filter depends on whether street address parsing is enabled.
4372 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4375 if ($addressOptions['street_address_parsing']) {
4376 $street_address_filters = array(
4377 'street_number' => array(
4378 'title' => ts('Street Number'),
4379 'type' => CRM_Utils_Type
::T_INT
,
4380 'name' => 'street_number',
4382 'street_name' => array(
4383 'title' => ts('Street Name'),
4384 'name' => 'street_name',
4385 'type' => CRM_Utils_Type
::T_STRING
,
4390 $street_address_filters = array(
4391 'street_address' => array(
4392 'title' => ts('Street Address'),
4393 'type' => CRM_Utils_Type
::T_STRING
,
4394 'name' => 'street_address',
4398 $general_address_filters = array(
4399 'postal_code' => array(
4400 'title' => ts('Postal Code'),
4401 'type' => CRM_Utils_Type
::T_STRING
,
4402 'name' => 'postal_code',
4405 'title' => ts('City'),
4406 'type' => CRM_Utils_Type
::T_STRING
,
4409 'country_id' => array(
4410 'name' => 'country_id',
4411 'title' => ts('Country'),
4412 'type' => CRM_Utils_Type
::T_INT
,
4413 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4414 'options' => CRM_Core_PseudoConstant
::country(),
4416 'state_province_id' => array(
4417 'name' => 'state_province_id',
4418 'title' => ts('State/Province'),
4419 'type' => CRM_Utils_Type
::T_INT
,
4420 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4421 'options' => array(),
4423 'county_id' => array(
4424 'name' => 'county_id',
4425 'title' => ts('County'),
4426 'type' => CRM_Utils_Type
::T_INT
,
4427 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4428 'options' => array(),
4432 $addressFields['civicrm_address']['filters'] = array_merge(
4433 $street_address_filters,
4434 $general_address_filters);
4437 $addressFields['civicrm_address']['order_bys'] = array(
4438 'street_name' => array('title' => ts('Street Name')),
4439 'street_number' => array('title' => ts('Odd / Even Street Number')),
4440 'street_address' => NULL,
4442 'postal_code' => NULL,
4447 $addressFields['civicrm_address']['group_bys'] = array(
4448 'street_address' => NULL,
4450 'postal_code' => NULL,
4451 'state_province_id' => array(
4452 'title' => ts('State/Province'),
4454 'country_id' => array(
4455 'title' => ts('Country'),
4457 'county_id' => array(
4458 'title' => ts('County'),
4462 return $addressFields;
4466 * Do AlterDisplay processing on Address Fields.
4467 * If there are multiple address field values then
4468 * on basis of provided separator the code values are translated into respective labels
4471 * @param array $rows
4472 * @param int $rowNum
4473 * @param string $baseUrl
4474 * @param string $linkText
4475 * @param string $separator
4479 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4480 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4481 $entryFound = FALSE;
4483 'civicrm_address_country_id' => 'country',
4484 'civicrm_address_county_id' => 'county',
4485 'civicrm_address_state_province_id' => 'stateProvince',
4487 foreach ($columnMap as $fieldName => $fnName) {
4488 if (array_key_exists($fieldName, $row)) {
4489 if ($values = $row[$fieldName]) {
4490 $values = (array) explode($separator, $values);
4491 $rows[$rowNum][$fieldName] = [];
4492 $addressField = $fnName == 'stateProvince' ?
'state' : $fnName;
4493 foreach ($values as $value) {
4494 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant
::$fnName($value);
4496 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4498 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4499 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4500 $criteriaQueryParams,
4501 str_replace('civicrm_address_', '', $fieldName),
4502 str_replace('civicrm_address_', '', $fieldName),
4503 implode(',', $values)
4504 ), $this->_absoluteUrl
, $this->_id
4506 $rows[$rowNum]["{$fieldName}_link"] = $url;
4507 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", array(1 => $linkText, 2 => $addressField));
4518 * Do AlterDisplay processing on Address Fields.
4521 * @param array $rows
4522 * @param int $rowNum
4523 * @param string $baseUrl
4524 * @param string $linkText
4528 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4529 $entryFound = FALSE;
4530 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4531 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4532 $addLinks = array('gender_id' => 'Gender');
4533 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4534 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4535 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4536 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4537 $rowLabels = array();
4538 foreach ($rowValues as $rowValue) {
4540 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4543 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4544 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4545 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4551 $yesNoFields = array(
4552 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4554 foreach ($yesNoFields as $fieldName) {
4555 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4556 // Since these are essentially 'negative fields' it feels like it
4557 // makes sense to only highlight the exceptions hence no 'No'.
4558 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4563 // Handle employer id
4564 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4565 $employerId = $row['civicrm_contact_employer_id'];
4567 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact
::displayName($employerId);
4568 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
4569 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4578 * Adjusts dates passed in to YEAR() for fiscal year.
4580 * @param string $fieldName
4584 public function fiscalYearOffset($fieldName) {
4585 $config = CRM_Core_Config
::singleton();
4586 $fy = $config->fiscalYearStart
;
4587 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4588 ($fy['d'] == 1 && $fy['M'] == 1)
4590 return "YEAR( $fieldName )";
4592 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4593 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4597 * Add Address into From Table if required.
4599 * @deprecated use joinAddressFromContact
4600 * (left here in case extensions use it).
4602 public function addAddressFromClause() {
4603 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinAddressFromContact');
4604 // include address field if address column is to be included
4605 if ((isset($this->_addressField
) &&
4606 $this->_addressField
4608 $this->isTableSelected('civicrm_address')
4611 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4612 ON ({$this->_aliases['civicrm_contact']}.id =
4613 {$this->_aliases['civicrm_address']}.contact_id) AND
4614 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4619 * Add Phone into From Table if required.
4621 * @deprecated use joinPhoneFromContact
4622 * (left here in case extensions use it).
4624 public function addPhoneFromClause() {
4625 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinPhoneFromContact');
4626 // include address field if address column is to be included
4627 if ($this->isTableSelected('civicrm_phone')) {
4629 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4630 ON ({$this->_aliases['civicrm_contact']}.id =
4631 {$this->_aliases['civicrm_phone']}.contact_id) AND
4632 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4637 * Add Address into From Table if required.
4639 * Prefix will be added to both tables as
4640 * it is assumed you are using it to get address of a secondary contact.
4642 * @param string $prefix
4643 * @param array $extra Additional options.
4644 * Not currently used in core but may be used in override extensions.
4646 protected function joinAddressFromContact($prefix = '', $extra = array()) {
4647 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4648 $isJoinRequired = $this->_addressField
;
4649 foreach ($addressTables as $addressTable) {
4650 if ($this->isTableSelected($prefix . $addressTable)) {
4651 $isJoinRequired = TRUE;
4654 if ($isJoinRequired) {
4656 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4657 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4658 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id) AND
4659 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4664 * Add Country into From Table if required.
4666 * Prefix will be added to both tables as
4667 * it is assumed you are using it to get address of a secondary contact.
4669 * @param string $prefix
4670 * @param array $extra Additional options.
4671 * Not currently used in core but may be used in override extensions.
4673 protected function joinCountryFromAddress($prefix = '', $extra = array()) {
4674 // include country field if country column is to be included
4675 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4676 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4677 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4680 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4681 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id AND
4682 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4687 * Add Phone into From Table if required.
4689 * Prefix will be added to both tables as
4690 * it is assumed you are using it to get address of a secondary contact.
4692 * @param string $prefix
4693 * @param array $extra Additional options.
4694 * Not currently used in core but may be used in override extensions.
4696 protected function joinPhoneFromContact($prefix = '', $extra = array()) {
4697 // include phone field if phone column is to be included
4698 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4700 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4701 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id AND
4702 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4707 * Add Email into From Table if required.
4709 * Prefix will be added to both tables as
4710 * it is assumed you are using it to get address of a secondary contact.
4712 * @param string $prefix
4713 * @param array $extra Additional options.
4714 * Not currently used in core but may be used in override extensions.
4716 protected function joinEmailFromContact($prefix = '', $extra = array()) {
4717 // include email field if email column is to be included
4718 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4720 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4721 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id AND
4722 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1) ";
4727 * Add Financial Transaction into From Table if required.
4729 public function addFinancialTrxnFromClause() {
4730 if ($this->isTableSelected('civicrm_financial_trxn')) {
4732 LEFT JOIN civicrm_entity_financial_trxn eftcc
4733 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4734 eftcc.entity_table = 'civicrm_contribution')
4735 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4736 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4741 * Get phone columns to add to array.
4743 * @param array $options
4744 * - prefix Prefix to add to table (in case of more than one instance of the table)
4745 * - prefix_label Label to give columns from this phone table instance
4748 * phone columns definition
4750 public function getPhoneColumns($options = array()) {
4751 $defaultOptions = array(
4753 'prefix_label' => '',
4756 $options = array_merge($defaultOptions, $options);
4759 $options['prefix'] . 'civicrm_phone' => array(
4760 'dao' => 'CRM_Core_DAO_Phone',
4762 $options['prefix'] . 'phone' => array(
4763 'title' => $options['prefix_label'] . ts('Phone'),
4773 * Get a standard set of contact fields.
4774 * @deprecated - use getColumns('Contact') instead
4777 public function getBasicContactFields() {
4779 'sort_name' => array(
4780 'title' => ts('Contact Name'),
4785 'no_display' => TRUE,
4788 'prefix_id' => array(
4789 'title' => ts('Contact Prefix'),
4791 'first_name' => array(
4792 'title' => ts('First Name'),
4794 'nick_name' => array(
4795 'title' => ts('Nick Name'),
4797 'middle_name' => array(
4798 'title' => ts('Middle Name'),
4800 'last_name' => array(
4801 'title' => ts('Last Name'),
4803 'suffix_id' => array(
4804 'title' => ts('Contact Suffix'),
4806 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4807 'email_greeting_display' => array('title' => ts('Email Greeting')),
4808 'addressee_display' => array('title' => ts('Addressee')),
4809 'contact_type' => array(
4810 'title' => ts('Contact Type'),
4812 'contact_sub_type' => array(
4813 'title' => ts('Contact Subtype'),
4815 'gender_id' => array(
4816 'title' => ts('Gender'),
4818 'birth_date' => array(
4819 'title' => ts('Birth Date'),
4822 'title' => ts('Age'),
4823 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4825 'job_title' => array(
4826 'title' => ts('Contact Job title'),
4828 'organization_name' => array(
4829 'title' => ts('Organization Name'),
4831 'external_identifier' => array(
4832 'title' => ts('Contact identifier from external system'),
4834 'do_not_email' => array(),
4835 'do_not_phone' => array(),
4836 'do_not_mail' => array(),
4837 'do_not_sms' => array(),
4838 'is_opt_out' => array(),
4839 'is_deceased' => array(),
4840 'preferred_language' => array(),
4841 'employer_id' => array(
4842 'title' => ts('Current Employer'),
4848 * Get a standard set of contact filters.
4850 * @param array $defaults
4854 public function getBasicContactFilters($defaults = array()) {
4856 'sort_name' => array(
4857 'title' => ts('Contact Name'),
4860 'title' => ts('Contact Source'),
4861 'type' => CRM_Utils_Type
::T_STRING
,
4864 'title' => ts('Contact ID'),
4865 'no_display' => TRUE,
4867 'gender_id' => array(
4868 'title' => ts('Gender'),
4869 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4870 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4872 'birth_date' => array(
4873 'title' => ts('Birth Date'),
4874 'operatorType' => CRM_Report_Form
::OP_DATE
,
4876 'contact_type' => array(
4877 'title' => ts('Contact Type'),
4879 'contact_sub_type' => array(
4880 'title' => ts('Contact Subtype'),
4882 'modified_date' => array(
4883 'title' => ts('Contact Modified'),
4884 'operatorType' => CRM_Report_Form
::OP_DATE
,
4885 'type' => CRM_Utils_Type
::T_DATE
,
4887 'is_deceased' => array(
4888 'title' => ts('Deceased'),
4889 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4890 'default' => CRM_Utils_Array
::value('deceased', $defaults, 0),
4892 'do_not_email' => array(
4893 'title' => ts('Do not email'),
4894 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4896 'do_not_phone' => array(
4897 'title' => ts('Do not phone'),
4898 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4900 'do_not_mail' => array(
4901 'title' => ts('Do not mail'),
4902 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4904 'do_not_sms' => array(
4905 'title' => ts('Do not SMS'),
4906 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4908 'is_opt_out' => array(
4909 'title' => ts('Do not bulk email'),
4910 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4912 'preferred_language' => array(
4913 'title' => ts('Preferred Language'),
4915 'is_deleted' => array(
4916 'no_display' => TRUE,
4918 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4924 * Add contact to group.
4926 * @param int $groupID
4928 public function add2group($groupID) {
4929 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4930 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4931 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4932 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4933 $sql = str_replace('WITH ROLLUP', '', $sql);
4934 $dao = CRM_Core_DAO
::executeQuery($sql);
4936 $contact_ids = array();
4937 // Add resulting contacts to group
4938 while ($dao->fetch()) {
4939 if ($dao->addtogroup_contact_id
) {
4940 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4944 if (!empty($contact_ids)) {
4945 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4946 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4949 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4955 * Show charts on print screen.
4957 public static function uploadChartImage() {
4958 // upload strictly for '.png' images
4959 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4960 if (preg_match('/\.png$/', $name)) {
4962 // Get the RAW .png from the input.
4963 $httpRawPostData = file_get_contents("php://input");
4965 // prepare the directory
4966 $config = CRM_Core_Config
::singleton();
4968 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4970 if (!file_exists($defaultPath)) {
4971 mkdir($defaultPath, 0777, TRUE);
4974 // full path to the saved image including filename
4975 $destination = $defaultPath . $name;
4978 $jfh = fopen($destination, 'w') or die("can't open file");
4979 fwrite($jfh, $httpRawPostData);
4981 CRM_Utils_System
::civiExit();
4986 * Apply common settings to entityRef fields.
4988 * @param array $field
4989 * @param string $table
4991 public function setEntityRefDefaults(&$field, $table) {
4992 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4993 $field['attributes'] +
= array(
4994 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4996 'placeholder' => ts('- select -'),
5001 * Add link fields to the row.
5003 * Function adds the _link & _hover fields to the row.
5006 * @param string $baseUrl
5007 * @param string $linkText
5008 * @param string $value
5009 * @param string $fieldName
5010 * @param string $tablePrefix
5011 * @param string $fieldLabel
5015 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
5016 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
5017 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
5018 "reset=1&force=1&{$criteriaQueryParams}&" .
5019 $fieldName . "_op=in&{$fieldName}_value={$value}",
5020 $this->_absoluteUrl
, $this->_id
5022 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
5023 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
5024 array(1 => $linkText, 2 => $fieldLabel)
5029 * Get label for show results buttons.
5033 public function getResultsLabel() {
5034 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
5035 return $showResultsLabel;
5039 * Determine the output mode from the url or input.
5042 * - pdf : Render as pdf
5043 * - csv : Render as csv
5044 * - print : Render in print format
5045 * - save : save the report and display the new report
5046 * - copy : save the report as a new instance and display that.
5047 * - group : go to the add to group screen.
5049 * Potentially chart variations could also be included but the complexity
5050 * is that we might print a bar chart as a pdf.
5052 protected function setOutputMode() {
5053 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
5056 CRM_Core_DAO
::$_nullObject,
5058 CRM_Utils_Array
::value('task', $this->_params
)
5060 // if contacts are added to group
5061 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
5062 $this->_outputMode
= 'group';
5064 if (isset($this->_params
['task'])) {
5065 unset($this->_params
['task']);
5070 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5073 * @param $columnName
5075 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5076 // add new column with date value for the datetime field
5077 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5078 CRM_Core_DAO
::executeQuery($tempQuery);
5079 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5080 CRM_Core_DAO
::executeQuery($updateQuery);
5081 $this->_selectClauses
[] = "{$columnName}_date";
5082 $this->_select
.= ", {$columnName}_date";
5083 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5084 unset($this->_sections
["{$columnName}"]);
5085 $this->assign('sections', $this->_sections
);
5089 * Get an array of the columns that have been selected for display.
5093 public function getSelectColumns() {
5094 $selectColumns = array();
5095 foreach ($this->_columns
as $tableName => $table) {
5096 if (array_key_exists('fields', $table)) {
5097 foreach ($table['fields'] as $fieldName => $field) {
5098 if (!empty($field['required']) ||
5099 !empty($this->_params
['fields'][$fieldName])
5102 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5107 return $selectColumns;
5111 * Add location tables to the query if they are used for filtering.
5113 * This is for when we are running the query separately for filtering and retrieving display fields.
5115 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5116 if ($this->isTableFiltered('civicrm_email')) {
5118 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5119 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5120 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5122 if ($this->isTableFiltered('civicrm_phone')) {
5124 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5125 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5126 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5128 if ($this->isTableFiltered('civicrm_address')) {
5130 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5131 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5132 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5137 * Set the base table for the FROM clause.
5139 * Sets up the from clause, allowing for the possibility it might be a
5140 * temp table pre-filtered by groups if a group filter is in use.
5142 * @param string $baseTable
5143 * @param string $field
5144 * @param null $tableAlias
5146 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5148 $tableAlias = $this->_aliases
[$baseTable];
5150 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5151 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5152 $this->_from
.= " {$this->_aclFrom} ";
5156 * Join the temp table contacting contacts who are members of the filtered groups.
5158 * If we are using an IN filter we use an inner join, otherwise a left join.
5160 * @param string $baseTable
5161 * @param string $field
5162 * @param string $tableAlias
5164 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5165 if ($this->groupTempTable
) {
5166 if ($this->_params
['gid_op'] == 'in') {
5167 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5168 ON group_temp_table.id = $tableAlias.{$field} ";
5172 LEFT JOIN $this->groupTempTable group_temp_table
5173 ON $tableAlias.{$field} = group_temp_table.id ";
5179 * Get all labels for fields that are used in a group concat.
5181 * @param string $options
5182 * comma separated option values.
5183 * @param string $baoName
5184 * The BAO name for the field.
5185 * @param string $fieldName
5186 * The name of the field for which labels should be retrieved.
5190 public function getLabels($options, $baoName, $fieldName) {
5191 $types = explode(',', $options);
5193 foreach ($types as $value) {
5194 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5196 return implode(', ', array_filter($labels));
5200 * Add statistics columns.
5202 * If a group by is in play then add columns for the statistics fields.
5204 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5205 * column header field.
5207 * @param array $field
5208 * @param string $tableName
5209 * @param string $fieldName
5210 * @param array $select
5214 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5215 foreach ($field['statistics'] as $stat => $label) {
5216 $alias = "{$tableName}_{$fieldName}_{$stat}";
5217 switch (strtolower($stat)) {
5220 $select[] = "$stat({$field['dbAlias']}) as $alias";
5221 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5222 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5223 $this->_statFields
[$label] = $alias;
5224 $this->_selectAliases
[] = $alias;
5228 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5229 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5230 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5231 $this->_statFields
[$label] = $alias;
5232 $this->_selectAliases
[] = $alias;
5235 case 'count_distinct':
5236 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5237 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5238 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5239 $this->_statFields
[$label] = $alias;
5240 $this->_selectAliases
[] = $alias;
5244 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5245 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5246 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5247 $this->_statFields
[$label] = $alias;
5248 $this->_selectAliases
[] = $alias;
5256 * Add a basic field to the select clause.
5258 * @param string $tableName
5259 * @param string $fieldName
5260 * @param array $field
5261 * @param string $select
5264 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5265 $alias = "{$tableName}_{$fieldName}";
5266 $select[] = "{$field['dbAlias']} as $alias";
5267 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
5268 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
5269 $this->_selectAliases
[] = $alias;
5276 * @param array $table
5277 * @param string $tableName
5282 protected function setTableAlias($table, $tableName) {
5283 if (!isset($table['alias'])) {
5284 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5288 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5291 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5292 return $this->_aliases
[$tableName];
5296 * Function to add columns to reports.
5298 * This is ported from extended reports, which also adds join filters to the options.
5300 * @param string $type
5301 * @param array $options
5302 * - prefix - A string to prepend to the table name
5303 * - prefix_label A string to prepend to the fields
5304 * - fields (bool) - should the fields for this table be made available
5305 * - group_by (bool) - should the group bys for this table be made available.
5306 * - order_by (bool) - should the group bys for this table be made available.
5307 * - filters (bool) - should the filters for this table by made available.
5308 * - fields_defaults (array) array of fields that should be displayed by default.
5309 * - filters_defaults (array) array of fields that should be filtered by default.
5310 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5311 * - join_fields (array) fields available from join (requires additional custom code).
5312 * - group_by_defaults (array) array of group bys that should be applied by default.
5313 * - order_by_defaults (array) array of order bys that should be applied by default.
5314 * - custom_fields (array) array of entity types for custom fields (not usually required).
5315 * - contact_type (string) optional restriction on contact type for some tables.
5316 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5320 protected function getColumns($type, $options = array()) {
5321 $defaultOptions = array(
5323 'prefix_label' => '',
5325 'group_bys' => FALSE,
5326 'order_bys' => TRUE,
5328 'join_filters' => FALSE,
5329 'fields_defaults' => array(),
5330 'filters_defaults' => array(),
5331 'group_bys_defaults' => array(),
5332 'order_bys_defaults' => array(),
5334 $options = array_merge($defaultOptions, $options);
5336 $fn = 'get' . $type . 'Columns';
5337 return $this->$fn($options);
5341 * Get columns for contact table.
5343 * @param array $options
5347 protected function getContactColumns($options = array()) {
5348 $defaultOptions = array(
5349 'custom_fields' => array('Individual', 'Contact', 'Organization'),
5350 'fields_defaults' => array('display_name', 'id'),
5351 'order_bys_defaults' => array('sort_name ASC'),
5352 'contact_type' => NULL,
5355 $options = array_merge($defaultOptions, $options);
5357 $tableAlias = $options['prefix'] . 'contact';
5360 $options['prefix'] . 'display_name' => array(
5361 'name' => 'display_name',
5362 'title' => $options['prefix_label'] . ts('Contact Name'),
5363 'is_fields' => TRUE,
5365 $options['prefix'] . 'sort_name' => array(
5366 'name' => 'sort_name',
5367 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5368 'is_fields' => TRUE,
5369 'is_filters' => TRUE,
5370 'is_order_bys' => TRUE,
5372 $options['prefix'] . 'id' => array(
5374 'title' => $options['prefix_label'] . ts('Contact ID'),
5375 'alter_display' => 'alterContactID',
5376 'type' => CRM_Utils_Type
::T_INT
,
5377 'is_order_bys' => TRUE,
5378 'is_group_bys' => TRUE,
5379 'is_fields' => TRUE,
5380 'is_filters' => TRUE,
5382 $options['prefix'] . 'external_identifier' => array(
5383 'name' => 'external_identifier',
5384 'title' => $options['prefix_label'] . ts('External ID'),
5385 'type' => CRM_Utils_Type
::T_INT
,
5386 'is_fields' => TRUE,
5388 $options['prefix'] . 'contact_type' => array(
5389 'title' => $options['prefix_label'] . ts('Contact Type'),
5390 'name' => 'contact_type',
5391 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5392 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5393 'is_fields' => TRUE,
5394 'is_filters' => TRUE,
5395 'is_group_bys' => TRUE,
5397 $options['prefix'] . 'contact_sub_type' => array(
5398 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5399 'name' => 'contact_sub_type',
5400 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5401 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5402 'is_fields' => TRUE,
5403 'is_filters' => TRUE,
5404 'is_group_bys' => TRUE,
5406 $options['prefix'] . 'is_deleted' => array(
5407 'title' => $options['prefix_label'] . ts('Is deleted'),
5408 'name' => 'is_deleted',
5409 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5410 'is_fields' => FALSE,
5411 'is_filters' => TRUE,
5412 'is_group_bys' => FALSE,
5414 $options['prefix'] . 'external_identifier' => array(
5415 'title' => $options['prefix_label'] . ts('Contact identifier from external system'),
5416 'name' => 'external_identifier',
5417 'is_fields' => TRUE,
5418 'is_filters' => FALSE,
5419 'is_group_bys' => FALSE,
5420 'is_order_bys' => TRUE,
5422 $options['prefix'] . 'preferred_language' => array(
5423 'title' => $options['prefix_label'] . ts('Preferred Language'),
5424 'name' => 'preferred_language',
5425 'is_fields' => TRUE,
5426 'is_filters' => TRUE,
5427 'is_group_bys' => TRUE,
5428 'is_order_bys' => TRUE,
5432 'postal_greeting_display' => 'Postal Greeting',
5433 'email_greeting_display' => 'Email Greeting',
5434 'addressee_display' => 'Addressee',
5435 ] as $field => $title) {
5436 $spec[$options['prefix'] . $field] = array(
5437 'title' => $options['prefix_label'] . ts($title),
5439 'is_fields' => TRUE,
5440 'is_filters' => FALSE,
5441 'is_group_bys' => FALSE,
5444 foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'is_opt_out'] as $field) {
5445 $spec[$options['prefix'] . $field] = [
5447 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5448 'is_fields' => TRUE,
5449 'is_filters' => TRUE,
5450 'is_group_bys' => FALSE,
5453 $individualFields = array(
5454 $options['prefix'] . 'first_name' => array(
5455 'name' => 'first_name',
5456 'title' => $options['prefix_label'] . ts('First Name'),
5457 'is_fields' => TRUE,
5458 'is_filters' => TRUE,
5459 'is_order_bys' => TRUE,
5461 $options['prefix'] . 'middle_name' => array(
5462 'name' => 'middle_name',
5463 'title' => $options['prefix_label'] . ts('Middle Name'),
5464 'is_fields' => TRUE,
5466 $options['prefix'] . 'last_name' => array(
5467 'name' => 'last_name',
5468 'title' => $options['prefix_label'] . ts('Last Name'),
5469 'default_order' => 'ASC',
5470 'is_fields' => TRUE,
5472 $options['prefix'] . 'nick_name' => array(
5473 'name' => 'nick_name',
5474 'title' => $options['prefix_label'] . ts('Nick Name'),
5475 'is_fields' => TRUE,
5477 $options['prefix'] . 'prefix_id' => array(
5478 'name' => 'prefix_id',
5479 'title' => $options['prefix_label'] . ts('Prefix'),
5480 'options' => CRM_Contact_BAO_Contact
::buildOptions('prefix_id'),
5481 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5482 'is_fields' => TRUE,
5483 'is_filters' => TRUE,
5485 $options['prefix'] . 'suffix_id' => array(
5486 'name' => 'suffix_id',
5487 'title' => $options['prefix_label'] . ts('Suffix'),
5488 'options' => CRM_Contact_BAO_Contact
::buildOptions('suffix_id'),
5489 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5490 'is_fields' => TRUE,
5491 'is_filters' => TRUE,
5493 $options['prefix'] . 'gender_id' => array(
5494 'name' => 'gender_id',
5495 'title' => $options['prefix_label'] . ts('Gender'),
5496 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5497 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5498 'is_fields' => TRUE,
5499 'is_filters' => TRUE,
5501 'birth_date' => array(
5502 'title' => $options['prefix_label'] . ts('Birth Date'),
5503 'operatorType' => CRM_Report_Form
::OP_DATE
,
5504 'type' => CRM_Utils_Type
::T_DATE
,
5505 'is_fields' => TRUE,
5506 'is_filters' => TRUE,
5509 'title' => $options['prefix_label'] . ts('Age'),
5510 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5511 'type' => CRM_Utils_Type
::T_INT
,
5512 'is_fields' => TRUE,
5514 $options['prefix'] . 'is_deceased' => array(
5515 'title' => $options['prefix_label'] . ts('Is deceased'),
5516 'name' => 'is_deceased',
5517 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5518 'is_fields' => FALSE,
5519 'is_filters' => TRUE,
5520 'is_group_bys' => FALSE,
5522 $options['prefix'] . 'job_title' => array(
5523 'name' => 'job_title',
5524 'is_fields' => TRUE,
5525 'is_filters' => FALSE,
5526 'is_group_bys' => FALSE,
5528 $options['prefix'] . 'employer_id' => array(
5529 'title' => $options['prefix_label'] . ts('Current Employer'),
5530 'type' => CRM_Utils_Type
::T_INT
,
5531 'name' => 'employer_id',
5532 'is_fields' => TRUE,
5533 'is_filters' => FALSE,
5534 'is_group_bys' => TRUE,
5537 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5538 $spec = array_merge($spec, $individualFields);
5541 if (!empty($options['custom_fields'])) {
5542 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = array(
5543 'extends' => $options['custom_fields'],
5544 'title' => $options['prefix_label'],
5545 'filters' => $options['filters'],
5546 'prefix' => $options['prefix'],
5547 'prefix_label' => $options['prefix_label'],
5551 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5555 * Get address columns to add to array.
5557 * @param array $options
5558 * - prefix Prefix to add to table (in case of more than one instance of the table)
5559 * - prefix_label Label to give columns from this address table instance
5560 * - group_bys enable these fields for group by - default false
5561 * - order_bys enable these fields for order by
5562 * - filters enable these fields for filtering
5564 * @return array address columns definition
5566 protected function getAddressColumns($options = array()) {
5567 $defaultOptions = array(
5569 'prefix_label' => '',
5571 'group_bys' => FALSE,
5572 'order_bys' => TRUE,
5574 'join_filters' => FALSE,
5575 'fields_defaults' => array(),
5576 'filters_defaults' => array(),
5577 'group_bys_defaults' => array(),
5578 'order_bys_defaults' => array(),
5581 $options = array_merge($defaultOptions, $options);
5582 $defaults = $this->getDefaultsFromOptions($options);
5583 $tableAlias = $options['prefix'] . 'address';
5586 $options['prefix'] . 'name' => array(
5587 'title' => ts($options['prefix_label'] . 'Address Name'),
5589 'is_fields' => TRUE,
5591 $options['prefix'] . 'street_number' => array(
5592 'name' => 'street_number',
5593 'title' => ts($options['prefix_label'] . 'Street Number'),
5595 'is_fields' => TRUE,
5597 $options['prefix'] . 'odd_street_number' => array(
5598 'title' => ts('Odd / Even Street Number'),
5599 'name' => 'odd_street_number',
5600 'type' => CRM_Utils_Type
::T_INT
,
5601 'no_display' => TRUE,
5603 'dbAlias' => '(address_civireport.street_number % 2)',
5604 'is_fields' => TRUE,
5605 'is_order_bys' => TRUE,
5607 $options['prefix'] . 'street_name' => array(
5608 'name' => 'street_name',
5609 'title' => ts($options['prefix_label'] . 'Street Name'),
5611 'is_fields' => TRUE,
5612 'is_filters' => TRUE,
5613 'operator' => 'like',
5614 'is_order_bys' => TRUE,
5616 $options['prefix'] . 'street_address' => array(
5617 'title' => ts($options['prefix_label'] . 'Street Address'),
5618 'name' => 'street_address',
5619 'is_fields' => TRUE,
5620 'is_filters' => TRUE,
5621 'is_group_bys' => TRUE,
5623 $options['prefix'] . 'supplemental_address_1' => array(
5624 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 1'),
5625 'name' => 'supplemental_address_1',
5626 'is_fields' => TRUE,
5628 $options['prefix'] . 'supplemental_address_2' => array(
5629 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 2'),
5630 'name' => 'supplemental_address_2',
5631 'is_fields' => TRUE,
5633 $options['prefix'] . 'supplemental_address_3' => array(
5634 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 3'),
5635 'name' => 'supplemental_address_3',
5636 'is_fields' => TRUE,
5638 $options['prefix'] . 'street_number' => array(
5639 'name' => 'street_number',
5640 'title' => ts($options['prefix_label'] . 'Street Number'),
5642 'is_order_bys' => TRUE,
5643 'is_filters' => TRUE,
5644 'is_fields' => TRUE,
5646 $options['prefix'] . 'street_unit' => array(
5647 'name' => 'street_unit',
5648 'title' => ts($options['prefix_label'] . 'Street Unit'),
5650 'is_fields' => TRUE,
5652 $options['prefix'] . 'city' => array(
5653 'title' => ts($options['prefix_label'] . 'City'),
5655 'operator' => 'like',
5656 'is_fields' => TRUE,
5657 'is_filters' => TRUE,
5658 'is_group_bys' => TRUE,
5659 'is_order_bys' => TRUE,
5661 $options['prefix'] . 'postal_code' => array(
5662 'title' => ts($options['prefix_label'] . 'Postal Code'),
5663 'name' => 'postal_code',
5665 'is_fields' => TRUE,
5666 'is_filters' => TRUE,
5667 'is_group_bys' => TRUE,
5668 'is_order_bys' => TRUE,
5670 $options['prefix'] . 'postal_code_suffix' => array(
5671 'title' => ts($options['prefix_label'] . 'Postal Code Suffix'),
5672 'name' => 'postal_code',
5674 'is_fields' => TRUE,
5675 'is_filters' => TRUE,
5676 'is_group_bys' => TRUE,
5677 'is_order_bys' => TRUE,
5679 $options['prefix'] . 'county_id' => array(
5680 'title' => ts($options['prefix_label'] . 'County'),
5681 'alter_display' => 'alterCountyID',
5682 'name' => 'county_id',
5683 'type' => CRM_Utils_Type
::T_INT
,
5684 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5685 'options' => CRM_Core_PseudoConstant
::county(),
5686 'is_fields' => TRUE,
5687 'is_filters' => TRUE,
5688 'is_group_bys' => TRUE,
5690 $options['prefix'] . 'state_province_id' => array(
5691 'title' => ts($options['prefix_label'] . 'State/Province'),
5692 'alter_display' => 'alterStateProvinceID',
5693 'name' => 'state_province_id',
5694 'type' => CRM_Utils_Type
::T_INT
,
5695 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5696 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5697 'is_fields' => TRUE,
5698 'is_filters' => TRUE,
5699 'is_group_bys' => TRUE,
5701 $options['prefix'] . 'country_id' => array(
5702 'title' => ts($options['prefix_label'] . 'Country'),
5703 'alter_display' => 'alterCountryID',
5704 'name' => 'country_id',
5705 'is_fields' => TRUE,
5706 'is_filters' => TRUE,
5707 'is_group_bys' => TRUE,
5708 'type' => CRM_Utils_Type
::T_INT
,
5709 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5710 'options' => CRM_Core_PseudoConstant
::country(),
5712 $options['prefix'] . 'location_type_id' => array(
5713 'name' => 'is_primary',
5714 'title' => ts($options['prefix_label'] . 'Location Type'),
5715 'type' => CRM_Utils_Type
::T_INT
,
5716 'is_fields' => TRUE,
5717 'alter_display' => 'alterLocationTypeID',
5719 $options['prefix'] . 'id' => array(
5720 'title' => ts($options['prefix_label'] . 'ID'),
5722 'is_fields' => TRUE,
5724 $options['prefix'] . 'is_primary' => array(
5725 'name' => 'is_primary',
5726 'title' => ts($options['prefix_label'] . 'Primary Address?'),
5727 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5728 'is_fields' => TRUE,
5731 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5735 * Build the columns.
5737 * The normal report class needs you to remember to do a few things that are often erratic
5739 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5740 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5741 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5742 * means any saved filters / fields on saved report instances. This will mean that matching names from
5743 * different tables may be ambigious, but it will smooth any code transition.
5744 * - note that it assumes the value being passed in is the actual table field name
5746 * 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
5747 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5749 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5750 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5751 * the core classes can start to move towards that.
5753 * @param array $specs
5754 * @param string $tableName
5755 * @param string $daoName
5756 * @param string $tableAlias
5757 * @param array $defaults
5758 * @param array $options
5762 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = array(), $options = array()) {
5764 $tableAlias = str_replace('civicrm_', '', $tableName);
5766 $types = array('filters', 'group_bys', 'order_bys', 'join_filters');
5767 $columns = array($tableName => array_fill_keys($types, array()));
5768 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5769 $columns[$tableName]['dao'] = $daoName;
5770 $columns[$tableName]['alias'] = $tableAlias;
5772 foreach ($specs as $specName => $spec) {
5773 if (empty($spec['name'])) {
5774 $spec['name'] = $specName;
5777 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5778 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5779 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5780 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5781 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5784 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5785 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5788 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5789 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5792 foreach ($types as $type) {
5793 if ($options[$type] && !empty($spec['is_' . $type])) {
5794 $columns[$tableName][$type][$fieldAlias] = $spec;
5795 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5796 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5805 * Store group bys into array - so we can check elsewhere what is grouped.
5807 protected function storeGroupByArray() {
5809 if (!CRM_Utils_Array
::value('group_bys', $this->_params
)
5810 ||
!is_array($this->_params
['group_bys'])) {
5811 $this->_params
['group_bys'] = [];
5814 foreach ($this->_columns
as $tableName => $table) {
5815 $table = $this->_columns
[$tableName];
5816 if (array_key_exists('group_bys', $table)) {
5817 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5818 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5819 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5820 if (!empty($field['chart'])) {
5821 $this->assign('chartSupported', TRUE);
5824 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5825 !empty($this->_params
['group_bys_freq'][$fieldName])
5828 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5830 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5833 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
5836 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_{$this->_params['group_bys_freq'][$fieldName]} FROM {$field['dbAlias']})";
5841 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5842 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5857 protected function getDefaultsFromOptions($options) {
5859 'fields_defaults' => $options['fields_defaults'],
5860 'filters_defaults' => $options['filters_defaults'],
5861 'group_bys_defaults' => $options['group_bys_defaults'],
5862 'order_bys_defaults' => $options['order_bys_defaults'],
5868 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5870 * Full group by mode dictates that a field must either be in the group by function or
5871 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5874 * @param string $tableName
5875 * @param string $fieldName
5876 * @param string $field
5879 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5880 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5881 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5882 $label = CRM_Utils_Array
::value('title', $field);
5883 $alias = "{$tableName}_{$fieldName}";
5884 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5885 $this->_selectAliases
[] = $alias;
5886 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5887 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5889 return "({$field['dbAlias']}) as $alias";
5895 * Generate clause for the selected filter.
5897 * @param array $field
5898 * Field specification
5899 * @param string $fieldName
5903 * Relevant where clause.
5905 protected function generateFilterClause($field, $fieldName) {
5906 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
5907 if (CRM_Utils_Array
::value('operatorType', $field) ==
5908 CRM_Report_Form
::OP_MONTH
5910 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5911 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
5912 if (is_array($value) && !empty($value)) {
5913 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
5918 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
5919 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
5920 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
5921 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
5922 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
5923 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
5927 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5929 return $this->whereClause($field,
5931 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
5932 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
5933 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)