3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 public $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
156 * Has the report been optimised for group filtering.
158 * The functionality for group filtering has been improved but not
159 * all reports have been adjusted to take care of it.
161 * This property exists to highlight the reports which are still using the
162 * slow method & allow group filtering to still work for them until they
165 * In order to protect extensions we have to default to TRUE - but I have
166 * separately marked every class with a groupFilter in the hope that will trigger
167 * people to fix them as they touch them.
173 protected $groupFilterNotOptimised = TRUE;
180 public $_navigation = array();
182 public $_drilldownReport = array();
185 * Array of tabs to display on report.
187 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
189 * $this->tabs['OrderBy'] = array(
190 * 'title' => ts('Sorting'),
191 * 'tpl' => 'OrderBy',
192 * 'div_label' => 'order-by',
197 protected $tabs = array();
200 * Should we add paging.
204 protected $addPaging = TRUE;
206 protected $isForceGroupBy = FALSE;
208 protected $groupConcatTested = FALSE;
211 * An attribute for checkbox/radio form field layout
215 protected $_fourColumnAttribute = array(
216 '</td><td width="25%">',
217 '</td><td width="25%">',
218 '</td><td width="25%">',
222 protected $_force = 1;
224 protected $_params = NULL;
225 protected $_formValues = NULL;
226 protected $_instanceValues = NULL;
228 protected $_instanceForm = FALSE;
229 protected $_criteriaForm = FALSE;
231 protected $_instanceButtonName = NULL;
232 protected $_createNewButtonName = NULL;
233 protected $_printButtonName = NULL;
234 protected $_pdfButtonName = NULL;
235 protected $_csvButtonName = NULL;
236 protected $_groupButtonName = NULL;
237 protected $_chartButtonName = NULL;
238 protected $_csvSupported = TRUE;
239 protected $_add2groupSupported = TRUE;
240 protected $_groups = NULL;
241 protected $_grandFlag = FALSE;
242 protected $_rowsFound = NULL;
243 protected $_selectAliases = array();
244 protected $_rollup = NULL;
247 * Table containing list of contact IDs within the group filter.
251 protected $groupTempTable = '';
256 protected $_aliases = array();
272 protected $_limit = NULL;
275 * This can be set to specify a limit to the number of rows
276 * Since it is currently envisaged as part of the api usage it is only being applied
277 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
278 * of the code (see limit() fn.
282 protected $_limitValue = NULL;
285 * This can be set to specify row offset
286 * See notes on _limitValue
289 protected $_offsetValue = NULL;
293 protected $_sections = NULL;
294 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
295 protected $_absoluteUrl = FALSE;
298 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
302 protected $_storeResultSet = FALSE;
305 * When _storeResultSet Flag is set use this var to store result set in form of array
309 protected $_resultSet = array();
312 * To what frequency group-by a date column
316 protected $_groupByDateFreq = array(
318 'YEARWEEK' => 'Week',
319 'QUARTER' => 'Quarter',
324 * Variables to hold the acl inner join and where clause
326 protected $_aclFrom = NULL;
327 protected $_aclWhere = NULL;
330 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
332 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
336 protected $_selectedTables = array();
339 * Array of DAO tables having columns included in WHERE or HAVING clause
343 protected $filteredTables;
346 * Output mode e.g 'print', 'csv', 'pdf'.
350 protected $_outputMode;
353 * Format of any chart in use.
355 * (it's unclear if this could be merged with outputMode at this stage)
361 public $_having = NULL;
362 public $_select = NULL;
363 public $_selectClauses = array();
364 public $_columnHeaders = array();
365 public $_orderBy = NULL;
366 public $_orderByFields = array();
367 public $_orderByArray = array();
369 * Array of clauses to group by.
373 protected $_groupByArray = array();
374 public $_groupBy = NULL;
375 public $_whereClauses = array();
376 public $_havingClauses = array();
379 * DashBoardRowCount Dashboard row count
382 public $_dashBoardRowCount;
385 * Is this being called without a form controller (ie. the report is being render outside the normal form
386 * - e.g the api is retrieving the rows
389 public $noController = FALSE;
392 * Variable to hold the currency alias
394 protected $_currencyColumn = NULL;
399 protected $_interval;
404 protected $_sendmail;
417 * @var string Report description.
419 public $_description;
422 * @var bool Is an address field selected.
423 * This was intended to determine if the address table should be joined in
424 * The isTableSelected function is now preferred for this purpose
426 protected $_addressField;
429 * @var bool Is an email field selected.
430 * This was intended to determine if the email table should be joined in
431 * The isTableSelected function is now preferred for this purpose
433 protected $_emailField;
436 * @var bool Is a phone field selected.
437 * This was intended to determine if the phone table should be joined in
438 * The isTableSelected function is now preferred for this purpose
440 protected $_phoneField;
443 * @var bool Create new report instance? (or update existing) on save.
445 protected $_createNew;
448 * When a grand total row has calculated the status we pop it off to here.
450 * This allows us to access it from the stats function and avoid recalculating.
452 protected $rollupRow = array();
455 * @var string Database attributes - character set and collation
457 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
460 * SQL being run in this report.
462 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
470 * An instruction not to add a Group By.
472 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
474 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
475 * such as in pivot charts when no row header is set
479 protected $noGroupBy = FALSE;
482 * SQL being run in this report as an array.
484 * The sql in the report is stored in this variable in order to be returned to api & test calls.
492 * 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 * @todo improve presentation on the developer tab since CREATE TEMPORARY is removed.
1150 * @param string $identifier
1152 * @param bool $isTrueTemporary
1153 * Is this a mysql temporary table or temporary in a less technical sense.
1157 public function createTemporaryTable($identifier, $sql, $isTrueTemporary = TRUE) {
1158 $this->addToDeveloperTab($sql);
1159 $name = CRM_Utils_SQL_TempTable
::build()->setUtf8(TRUE)->setDurable($isTrueTemporary)->createWithQuery($sql)->getName();
1160 $this->temporaryTables
[$identifier] = ['temporary' => $isTrueTemporary, 'name' => $name];
1165 * Add columns to report.
1167 public function addColumns() {
1170 foreach ($this->_columns
as $tableName => $table) {
1171 if (array_key_exists('fields', $table)) {
1172 foreach ($table['fields'] as $fieldName => $field) {
1174 if (empty($field['no_display'])) {
1175 foreach (array('table', 'field') as $var) {
1176 if (!empty($
{$var}['grouping'])) {
1177 if (!is_array($
{$var}['grouping'])) {
1178 $tableName = $
{$var}['grouping'];
1181 $tableName = array_keys($
{$var}['grouping']);
1182 $tableName = $tableName[0];
1183 $groupTitle = array_values($
{$var}['grouping']);
1184 $groupTitle = $groupTitle[0];
1189 if (!$groupTitle && isset($table['group_title'])) {
1190 $groupTitle = $table['group_title'];
1191 // Having a group_title is secret code for being a custom group
1192 // which cryptically translates to needing an accordion.
1193 // here we make that explicit.
1194 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1197 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1198 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1199 $colGroups[$tableName]['group_title'] = $groupTitle;
1201 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1207 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1208 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1210 if (!empty($colGroups)) {
1211 $this->tabs
['FieldSelection'] = array(
1212 'title' => ts('Columns'),
1213 'tpl' => 'FieldSelection',
1214 'div_label' => 'col-groups',
1217 // Note this assignment is only really required in buildForm. It is being 'over-called'
1218 // to reduce risk of being missed due to overridden functions.
1219 $this->assign('tabs', $this->tabs
);
1222 $this->assign('colGroups', $colGroups);
1226 * Add filters to report.
1228 public function addFilters() {
1229 $filters = $filterGroups = array();
1232 foreach ($this->_filters
as $table => $attributes) {
1233 if (isset($this->_columns
[$table]['group_title'])) {
1234 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1235 // which magically means to 'display in an accordian'
1236 // here we make this explicit.
1237 $filterGroups[$table] = array(
1238 'group_title' => $this->_columns
[$table]['group_title'],
1239 'use_accordian_for_field_selection' => TRUE,
1243 foreach ($attributes as $fieldName => $field) {
1244 // get ready with option value pair
1245 // @ 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
1247 $operations = $this->getOperationPair(
1248 CRM_Utils_Array
::value('operatorType', $field),
1251 $filters[$table][$fieldName] = $field;
1253 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1254 case CRM_Report_Form
::OP_MONTH
:
1255 if (!array_key_exists('options', $field) ||
1256 !is_array($field['options']) ||
empty($field['options'])
1258 // If there's no option list for this filter, define one.
1259 $field['options'] = array(
1261 2 => ts('February'),
1268 9 => ts('September'),
1269 10 => ts('October'),
1270 11 => ts('November'),
1271 12 => ts('December'),
1273 // Add this option list to this column _columns. This is
1274 // required so that filter statistics show properly.
1275 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1277 case CRM_Report_Form
::OP_MULTISELECT
:
1278 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1279 // assume a multi-select field
1280 if (!empty($field['options']) ||
1281 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1283 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1284 if (count($operations) <= 1) {
1287 if ($fieldName == 'state_province_id' ||
1288 $fieldName == 'county_id'
1290 $this->addChainSelect($fieldName . '_value', array(
1297 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1298 'style' => 'min-width:250px',
1299 'class' => 'crm-select2 huge',
1301 'placeholder' => ts('- select -'),
1307 case CRM_Report_Form
::OP_SELECT
:
1308 // assume a select field
1309 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1310 if (!empty($field['options'])) {
1311 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1315 case CRM_Report_Form
::OP_ENTITYREF
:
1316 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1317 $this->setEntityRefDefaults($field, $table);
1318 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1321 case CRM_Report_Form
::OP_DATE
:
1322 // build datetime fields
1323 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1327 case CRM_Report_Form
::OP_DATETIME
:
1328 // build datetime fields
1329 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1333 case CRM_Report_Form
::OP_INT
:
1334 case CRM_Report_Form
::OP_FLOAT
:
1335 // and a min value input box
1336 $this->add('text', "{$fieldName}_min", ts('Min'));
1337 // and a max value input box
1338 $this->add('text', "{$fieldName}_max", ts('Max'));
1340 // default type is string
1341 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1342 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1344 // we need text box for value input
1345 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1350 if (!empty($filters)) {
1351 $this->tabs
['Filters'] = array(
1352 'title' => ts('Filters'),
1354 'div_label' => 'set-filters',
1357 $this->assign('filters', $filters);
1358 $this->assign('filterGroups', $filterGroups);
1362 * Function to assign the tabs to the template in the correct order.
1364 * We want the tabs to wind up in this order (if not overridden).
1372 protected function assignTabs() {
1380 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1381 $order = array_merge($order, $this->tabs
);
1382 $this->assign('tabs', $order);
1386 * The intent is to add a tab for developers to view the sql.
1388 * Currently using dpm.
1390 * @param string $sql
1392 public function addToDeveloperTab($sql) {
1393 if (!CRM_Core_Permission
::check('view report sql')) {
1396 $ignored_output_modes = array('pdf', 'csv', 'print');
1397 if (in_array($this->_outputMode
, $ignored_output_modes)) {
1400 $this->tabs
['Developer'] = array(
1401 'title' => ts('Developer'),
1402 'tpl' => 'Developer',
1403 'div_label' => 'set-developer',
1406 $this->assignTabs();
1407 $this->sqlArray
[] = $sql;
1408 foreach ($this->sqlArray
as $sql) {
1409 foreach (array('LEFT JOIN') as $term) {
1410 $sql = str_replace($term, '<br> ' . $term, $sql);
1412 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1413 $sql = str_replace($term, '<br><br>' . $term, $sql);
1415 $this->sqlFormattedArray
[] = $sql;
1416 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1418 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL
::getSqlModes());
1423 * Add options defined in $this->_options to the report.
1425 public function addOptions() {
1426 if (!empty($this->_options
)) {
1427 // FIXME: For now lets build all elements as checkboxes.
1428 // Once we clear with the format we can build elements based on type
1430 foreach ($this->_options
as $fieldName => $field) {
1433 if ($field['type'] == 'select') {
1434 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1436 elseif ($field['type'] == 'checkbox') {
1437 $options[$field['title']] = $fieldName;
1438 $this->addCheckBox($fieldName, NULL,
1440 NULL, NULL, NULL, $this->_fourColumnAttribute
1445 if (!empty($this->_options
) &&
1447 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1449 $this->tabs
['ReportOptions'] = array(
1450 'title' => ts('Display Options'),
1451 'tpl' => 'ReportOptions',
1452 'div_label' => 'other-options',
1455 $this->assign('otherOptions', $this->_options
);
1459 * Add chart options to the report.
1461 public function addChartOptions() {
1462 if (!empty($this->_charts
)) {
1463 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1464 $this->assign('charts', $this->_charts
);
1465 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1470 * Add group by options to the report.
1472 public function addGroupBys() {
1473 $options = $freqElements = array();
1475 foreach ($this->_columns
as $tableName => $table) {
1476 if (array_key_exists('group_bys', $table)) {
1477 foreach ($table['group_bys'] as $fieldName => $field) {
1478 if (!empty($field) && empty($field['no_display'])) {
1479 $options[$field['title']] = $fieldName;
1480 if (!empty($field['frequency'])) {
1481 $freqElements[$field['title']] = $fieldName;
1487 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1488 NULL, NULL, NULL, $this->_fourColumnAttribute
1490 $this->assign('groupByElements', $options);
1491 if (!empty($options)) {
1492 $this->tabs
['GroupBy'] = array(
1493 'title' => ts('Grouping'),
1495 'div_label' => 'group-by-elements',
1499 foreach ($freqElements as $name) {
1500 $this->addElement('select', "group_bys_freq[$name]",
1501 ts('Frequency'), $this->_groupByDateFreq
1507 * Add data for order by tab.
1509 public function addOrderBys() {
1511 foreach ($this->_columns
as $tableName => $table) {
1513 // Report developer may define any column to order by; include these as order-by options.
1514 if (array_key_exists('order_bys', $table)) {
1515 foreach ($table['order_bys'] as $fieldName => $field) {
1516 if (!empty($field)) {
1517 $options[$fieldName] = $field['title'];
1522 // Add searchable custom fields as order-by options, if so requested
1523 // (These are already indexed, so allowing to order on them is cheap.)
1525 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1526 array_key_exists('extends', $table) && !empty($table['extends'])
1528 foreach ($table['fields'] as $fieldName => $field) {
1529 if (empty($field['no_display'])) {
1530 $options[$fieldName] = $field['title'];
1538 $this->assign('orderByOptions', $options);
1539 if (!empty($options)) {
1540 $this->tabs
['OrderBy'] = array(
1541 'title' => ts('Sorting'),
1543 'div_label' => 'order-by-elements',
1547 if (!empty($options)) {
1549 '-' => ' - none - ',
1551 for ($i = 1; $i <= 5; $i++
) {
1552 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1553 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1554 'ASC' => ts('Ascending'),
1555 'DESC' => ts('Descending'),
1557 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1558 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1564 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1566 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1567 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1570 public function buildInstanceAndButtons() {
1571 CRM_Report_Form_Instance
::buildForm($this);
1572 $this->_actionButtonName
= $this->getButtonName('submit');
1573 $this->addTaskMenu($this->getActions($this->_id
));
1575 $this->assign('instanceForm', $this->_instanceForm
);
1577 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1578 $permission = CRM_Core_Permission
::getPermission();
1579 if ($permission == CRM_Core_Permission
::EDIT
&&
1580 $this->_add2groupSupported
1582 $this->addElement('select', 'groups', ts('Group'),
1583 array('' => ts('Add Contacts to Group')) +
1584 CRM_Core_PseudoConstant
::nestedGroup(),
1585 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1587 $this->assign('group', TRUE);
1590 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1592 $this->addChartOptions();
1593 $showResultsLabel = $this->getResultsLabel();
1594 $this->addButtons(array(
1597 'name' => $showResultsLabel,
1598 'isDefault' => TRUE,
1605 * Has this form been submitted already?
1609 public function resultsDisplayed() {
1610 $buttonName = $this->controller
->getButtonName();
1611 return ($buttonName ||
$this->_outputMode
);
1615 * Get the actions for this report instance.
1617 * @param int $instanceId
1621 protected function getActions($instanceId) {
1622 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1623 if (empty($instanceId)) {
1624 $actions['report_instance.save'] = array(
1625 'title' => ts('Create Report'),
1627 'is_confirm' => TRUE,
1628 'confirm_title' => ts('Create Report'),
1629 'confirm_refresh_fields' => json_encode(array(
1630 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1631 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1637 if (!$this->_csvSupported
) {
1638 unset($actions['report_instance.csv']);
1645 * Main build form function.
1647 public function buildQuickForm() {
1648 $this->addColumns();
1650 $this->addFilters();
1652 $this->addOptions();
1654 $this->addGroupBys();
1656 $this->addOrderBys();
1658 $this->buildInstanceAndButtons();
1660 // Add form rule for report.
1661 if (is_callable(array(
1665 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1667 $this->assignTabs();
1671 * A form rule function for custom data.
1673 * The rule ensures that fields selected in group_by if any) should only be the ones
1674 * present in display/select fields criteria;
1675 * note: works if and only if any custom field selected in group_by.
1677 * @param array $fields
1678 * @param array $ignoreFields
1682 public function customDataFormRule($fields, $ignoreFields = array()) {
1684 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1685 !empty($fields['group_bys'])
1687 foreach ($this->_columns
as $tableName => $table) {
1688 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1689 substr($tableName, 0, 12) == 'custom_value') &&
1690 !empty($this->_columns
[$tableName]['fields'])
1692 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1693 if (array_key_exists($fieldName, $fields['group_bys']) &&
1694 !array_key_exists($fieldName, $fields['fields'])
1696 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1698 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1699 foreach ($fields['fields'] as $fld => $val) {
1700 if (!array_key_exists($fld, $fields['group_bys']) &&
1701 !in_array($fld, $ignoreFields)
1703 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1715 * Get operators to display on form.
1717 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1719 * @param string $type
1720 * @param string $fieldName
1724 public function getOperationPair($type = "string", $fieldName = NULL) {
1725 // FIXME: At some point we should move these key-val pairs
1726 // to option_group and option_value table.
1728 case CRM_Report_Form
::OP_INT
:
1729 case CRM_Report_Form
::OP_FLOAT
:
1732 'lte' => ts('Is less than or equal to'),
1733 'gte' => ts('Is greater than or equal to'),
1734 'bw' => ts('Is between'),
1735 'eq' => ts('Is equal to'),
1736 'lt' => ts('Is less than'),
1737 'gt' => ts('Is greater than'),
1738 'neq' => ts('Is not equal to'),
1739 'nbw' => ts('Is not between'),
1740 'nll' => ts('Is empty (Null)'),
1741 'nnll' => ts('Is not empty (Null)'),
1745 case CRM_Report_Form
::OP_SELECT
:
1747 'eq' => ts('Is equal to'),
1751 case CRM_Report_Form
::OP_MONTH
:
1752 case CRM_Report_Form
::OP_MULTISELECT
:
1753 case CRM_Report_Form
::OP_ENTITYREF
:
1756 'in' => ts('Is one of'),
1757 'notin' => ts('Is not one of'),
1761 case CRM_Report_Form
::OP_DATE
:
1764 'nll' => ts('Is empty (Null)'),
1765 'nnll' => ts('Is not empty (Null)'),
1769 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1770 // use this operator for the values, concatenated with separator. For e.g if
1771 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1773 'mhas' => ts('Is one of'),
1774 'mnot' => ts('Is not one of'),
1781 'has' => ts('Contains'),
1782 'sw' => ts('Starts with'),
1783 'ew' => ts('Ends with'),
1784 'nhas' => ts('Does not contain'),
1785 'eq' => ts('Is equal to'),
1786 'neq' => ts('Is not equal to'),
1787 'nll' => ts('Is empty (Null)'),
1788 'nnll' => ts('Is not empty (Null)'),
1795 * Build the tag filter field to display on the filters tab.
1797 public function buildTagFilter() {
1798 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1799 if (!empty($contactTags)) {
1800 $this->_columns
['civicrm_tag'] = array(
1801 'dao' => 'CRM_Core_DAO_Tag',
1805 'title' => ts('Tag'),
1806 'type' => CRM_Utils_Type
::T_INT
,
1808 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1809 'options' => $contactTags,
1817 * Adds group filters to _columns (called from _Construct).
1819 public function buildGroupFilter() {
1820 $this->_columns
['civicrm_group']['filters'] = array(
1822 'name' => 'group_id',
1823 'title' => ts('Group'),
1824 'type' => CRM_Utils_Type
::T_INT
,
1825 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1827 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1830 if (empty($this->_columns
['civicrm_group']['dao'])) {
1831 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1833 if (empty($this->_columns
['civicrm_group']['alias'])) {
1834 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1839 * Get SQL operator from form text version.
1841 * @param string $operator
1845 public function getSQLOperator($operator = "like") {
1846 switch ($operator) {
1879 return 'IS NOT NULL';
1888 * Generate where clause.
1890 * This can be overridden in reports for special treatment of a field
1892 * @param array $field Field specifications
1893 * @param string $op Query operator (not an exact match to sql)
1894 * @param mixed $value
1898 * @return null|string
1900 public function whereClause(&$field, $op, $value, $min, $max) {
1902 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1904 // CRM-18010: Ensure type of each report filters
1906 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1913 if (($min !== NULL && strlen($min) > 0) ||
1914 ($max !== NULL && strlen($max) > 0)
1918 $min = CRM_Utils_Type
::escape($min, $type);
1920 $clauses[] = "( {$field['dbAlias']} >= $min )";
1923 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1927 $max = CRM_Utils_Type
::escape($max, $type);
1929 $clauses[] = "( {$field['dbAlias']} <= $max )";
1932 $clauses[] = "( {$field['dbAlias']} > $max )";
1936 if (!empty($clauses)) {
1938 $clause = implode(' AND ', $clauses);
1941 $clause = '(' . implode('OR', $clauses) . ')';
1949 if ($value !== NULL && strlen($value) > 0) {
1950 $value = CRM_Utils_Type
::escape($value, $type);
1951 if (strpos($value, '%') === FALSE) {
1952 $value = "'%{$value}%'";
1955 $value = "'{$value}'";
1957 $sqlOP = $this->getSQLOperator($op);
1958 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1964 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1965 $value = explode(',', $value);
1967 if ($value !== NULL && is_array($value) && count($value) > 0) {
1968 $sqlOP = $this->getSQLOperator($op);
1969 if (CRM_Utils_Array
::value('type', $field) ==
1970 CRM_Utils_Type
::T_STRING
1972 //cycle through selections and escape values
1973 foreach ($value as $key => $selection) {
1974 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1977 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1981 // for numerical values
1982 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1985 if ($op == 'notin') {
1986 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1989 $clause = "( " . $clause . " )";
1996 // multiple has or multiple not
1997 if ($value !== NULL && count($value) > 0) {
1998 $value = CRM_Utils_Type
::escapeAll($value, $type);
1999 $operator = $op == 'mnot' ?
'NOT' : '';
2000 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2001 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2007 if ($value !== NULL && strlen($value) > 0) {
2008 $value = CRM_Utils_Type
::escape($value, $type);
2009 if (strpos($value, '%') === FALSE) {
2011 $value = "'{$value}%'";
2014 $value = "'%{$value}'";
2018 $value = "'{$value}'";
2020 $sqlOP = $this->getSQLOperator($op);
2021 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2027 $sqlOP = $this->getSQLOperator($op);
2028 $clause = "( {$field['dbAlias']} $sqlOP )";
2034 //CRM-18457: some custom field passes value in array format against binary operator
2035 if (is_array($value) && count($value)) {
2040 if ($value !== NULL && $value !== '') {
2041 if (isset($field['clause'])) {
2042 // FIXME: we not doing escape here. Better solution is to use two
2043 // different types - data-type and filter-type
2044 $clause = $field['clause'];
2046 elseif (!is_array($value)) {
2047 $value = CRM_Utils_Type
::escape($value, $type);
2048 $sqlOP = $this->getSQLOperator($op);
2049 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
2050 $value = "'{$value}'";
2052 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2058 if (!empty($field['group']) && $clause) {
2059 $clause = $this->whereGroupClause($field, $value, $op);
2061 elseif (!empty($field['tag']) && $clause) {
2062 // not using left join in query because if any contact
2063 // belongs to more than one tag, results duplicate
2065 $clause = $this->whereTagClause($field, $value, $op);
2067 elseif (!empty($field['membership_org']) && $clause) {
2068 $clause = $this->whereMembershipOrgClause($value, $op);
2070 elseif (!empty($field['membership_type']) && $clause) {
2071 $clause = $this->whereMembershipTypeClause($value, $op);
2077 * Get SQL where clause for a date field.
2079 * @param string $fieldName
2080 * @param string $relative
2081 * @param string $from
2083 * @param string $type
2084 * @param string $fromTime
2085 * @param string $toTime
2087 * @return null|string
2089 public function dateClause(
2091 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2094 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2095 $sqlOP = $this->getSQLOperator($relative);
2096 return "( {$fieldName} {$sqlOP} )";
2099 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2102 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2103 $clauses[] = "( {$fieldName} >= $from )";
2107 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2108 $clauses[] = "( {$fieldName} <= {$to} )";
2111 if (!empty($clauses)) {
2112 return implode(' AND ', $clauses);
2119 * Get values for from and to for date ranges.
2123 * @param bool $relative
2124 * @param string $from
2126 * @param string $fromTime
2127 * @param string $toTime
2131 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2132 if (empty($toTime)) {
2133 // odd legacy behaviour to treat NULL as 'end of the day'
2134 // recommend updating reports to call CRM_Utils_Date::getFromTo
2135 //directly (default on the function is the actual default there).
2138 return CRM_Utils_Date
::getFromTo($relative, $from, $to, $fromTime, $toTime);
2142 * Alter display of rows.
2144 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2145 * such as rendering contacts as links.
2147 * @param array $rows
2148 * Rows generated by SQL, with an array for each row.
2150 public function alterDisplay(&$rows) {
2154 * Alter the way in which custom data fields are displayed.
2156 * @param array $rows
2158 public function alterCustomDataDisplay(&$rows) {
2159 // custom code to alter rows having custom values
2160 if (empty($this->_customGroupExtends
)) {
2164 $customFields = array();
2165 $customFieldIds = array();
2166 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2167 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2168 $customFieldIds[$fieldAlias] = $fieldId;
2171 if (empty($customFieldIds)) {
2175 // skip for type date and ContactReference since date format is already handled
2177 SELECT cg.table_name, cf.id
2178 FROM civicrm_custom_field cf
2179 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2180 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2181 cg.is_active = 1 AND
2182 cf.is_active = 1 AND
2183 cf.is_searchable = 1 AND
2184 cf.data_type NOT IN ('ContactReference', 'Date') AND
2185 cf.id IN (" . implode(",", $customFieldIds) . ")";
2187 $dao = CRM_Core_DAO
::executeQuery($query);
2188 while ($dao->fetch()) {
2189 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2193 $entryFound = FALSE;
2194 foreach ($rows as $rowNum => $row) {
2195 foreach ($row as $tableCol => $val) {
2196 if (array_key_exists($tableCol, $customFields)) {
2197 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2202 // skip looking further in rows, if first row itself doesn't
2203 // have the column we need
2211 * Remove duplicate rows.
2213 * @param array $rows
2215 public function removeDuplicates(&$rows) {
2216 if (empty($this->_noRepeats
)) {
2219 $checkList = array();
2221 foreach ($rows as $key => $list) {
2222 foreach ($list as $colName => $colVal) {
2223 if (array_key_exists($colName, $checkList) &&
2224 $checkList[$colName] == $colVal
2226 $rows[$key][$colName] = "";
2228 if (in_array($colName, $this->_noRepeats
)) {
2229 $checkList[$colName] = $colVal;
2236 * Fix subtotal display.
2239 * @param array $fields
2240 * @param bool $subtotal
2242 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2243 foreach ($row as $colName => $colVal) {
2244 if (in_array($colName, $fields)) {
2246 elseif (isset($this->_columnHeaders
[$colName])) {
2248 $row[$colName] = 'Subtotal';
2252 unset($row[$colName]);
2259 * Calculate grant total.
2261 * @param array $rows
2265 public function grandTotal(&$rows) {
2266 if (!$this->_rollup ||
count($rows) == 1) {
2270 $this->moveSummaryColumnsToTheRightHandSide();
2272 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2276 $this->rollupRow
= array_pop($rows);
2278 foreach ($this->_columnHeaders
as $fld => $val) {
2279 if (!in_array($fld, $this->_statFields
)) {
2280 if (!$this->_grandFlag
) {
2281 $this->rollupRow
[$fld] = ts('Grand Total');
2282 $this->_grandFlag
= TRUE;
2285 $this->rollupRow
[$fld] = "";
2290 $this->assign('grandStat', $this->rollupRow
);
2295 * Format display output.
2297 * @param array $rows
2298 * @param bool $pager
2300 public function formatDisplay(&$rows, $pager = TRUE) {
2301 // set pager based on if any limit was applied in the query.
2306 // allow building charts if any
2307 if (!empty($this->_params
['charts']) && !empty($rows)) {
2308 $this->buildChart($rows);
2309 $this->assign('chartEnabled', TRUE);
2310 $this->_chartId
= "{$this->_params['charts']}_" .
2311 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2313 $this->assign('chartId', $this->_chartId
);
2316 // unset columns not to be displayed.
2317 foreach ($this->_columnHeaders
as $key => $value) {
2318 if (!empty($value['no_display'])) {
2319 unset($this->_columnHeaders
[$key]);
2323 // unset columns not to be displayed.
2324 if (!empty($rows)) {
2325 foreach ($this->_noDisplay
as $noDisplayField) {
2326 foreach ($rows as $rowNum => $row) {
2327 unset($this->_columnHeaders
[$noDisplayField]);
2332 // build array of section totals
2333 $this->sectionTotals();
2335 // process grand-total row
2336 $this->grandTotal($rows);
2338 // Find alter display functions.
2339 $firstRow = reset($rows);
2341 $selectedFields = array_keys($firstRow);
2342 $alterFunctions = $alterMap = $alterSpecs = array();
2343 foreach ($this->_columns
as $tableName => $table) {
2344 if (array_key_exists('metadata', $table)) {
2345 foreach ($table['metadata'] as $field => $specs) {
2346 if (in_array($tableName . '_' . $field, $selectedFields)) {
2347 if (array_key_exists('alter_display', $specs)) {
2348 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2349 $alterMap[$tableName . '_' . $field] = $field;
2350 $alterSpecs[$tableName . '_' . $field] = NULL;
2352 // Add any alters that can be intuited from the field specs.
2353 // So far only boolean but a lot more could be.
2354 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2355 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2356 $alterMap[$tableName . '_' . $field] = $field;
2357 $alterSpecs[$tableName . '_' . $field] = NULL;
2364 // Run the alter display functions
2365 foreach ($rows as $index => & $row) {
2366 foreach ($row as $selectedField => $value) {
2367 if (array_key_exists($selectedField, $alterFunctions)) {
2368 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2374 // use this method for formatting rows for display purpose.
2375 $this->alterDisplay($rows);
2376 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2378 // use this method for formatting custom rows for display purpose.
2379 $this->alterCustomDataDisplay($rows);
2385 * @param $selectedfield
2386 * @param $criteriaFieldName
2390 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2391 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2392 $row[$selectedfield . '_link'] = $url;
2393 $row[$selectedfield . '_hover'] = ts("%1 for this state.", array(
2397 $states = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2398 if (!is_array($states)) {
2406 * @param $selectedField
2407 * @param $criteriaFieldName
2411 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2412 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2413 $row[$selectedField . '_link'] = $url;
2414 $row[$selectedField . '_hover'] = ts("%1 for this country.", array(
2417 $countries = CRM_Core_PseudoConstant
::country($value, FALSE);
2418 if (!is_array($countries)) {
2426 * @param $selectedfield
2427 * @param $criteriaFieldName
2431 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2432 $url = CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl
);
2433 $row[$selectedfield . '_link'] = $url;
2434 $row[$selectedfield . '_hover'] = ts("%1 for this county.", array(
2437 $counties = CRM_Core_PseudoConstant
::county($value, FALSE);
2438 if (!is_array($counties)) {
2446 * @param $selectedfield
2447 * @param $criteriaFieldName
2451 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2452 $values = $this->getLocationTypeOptions();
2453 return CRM_Utils_Array
::value($value, $values);
2463 protected function alterContactID($value, &$row, $fieldname) {
2464 $nameField = substr($fieldname, 0, -2) . 'name';
2465 static $first = TRUE;
2466 static $viewContactList = FALSE;
2468 $viewContactList = CRM_Core_Permission
::check('access CiviCRM');
2471 if (!$viewContactList) {
2474 if (array_key_exists($nameField, $row)) {
2475 $row[$nameField . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2478 $row[$fieldname . '_link'] = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl
);
2488 protected function alterBoolean($value) {
2489 $options = array(0 => '', 1 => ts('Yes'));
2490 if (isset($options[$value])) {
2491 return $options[$value];
2499 * @param array $rows
2501 public function buildChart(&$rows) {
2502 // override this method for building charts.
2505 // select() method below has been added recently (v3.3), and many of the report templates might
2506 // still be having their own select() method. We should fix them as and when encountered and move
2507 // towards generalizing the select() method below.
2510 * Generate the SELECT clause and set class variable $_select.
2512 public function select() {
2513 $select = $this->_selectAliases
= array();
2514 $this->storeGroupByArray();
2516 foreach ($this->_columns
as $tableName => $table) {
2517 if (array_key_exists('fields', $table)) {
2518 foreach ($table['fields'] as $fieldName => $field) {
2519 if ($tableName == 'civicrm_address') {
2520 // deprecated, use $this->isTableSelected.
2521 $this->_addressField
= TRUE;
2523 if ($tableName == 'civicrm_email') {
2524 $this->_emailField
= TRUE;
2526 if ($tableName == 'civicrm_phone') {
2527 $this->_phoneField
= TRUE;
2530 if (!empty($field['required']) ||
2531 !empty($this->_params
['fields'][$fieldName])
2534 // 1. In many cases we want select clause to be built in slightly different way
2535 // for a particular field of a particular type.
2536 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2538 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2539 if ($selectClause) {
2540 $select[] = $selectClause;
2544 // include statistics columns only if set
2545 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2546 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2550 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2551 if ($selectClause) {
2552 $select[] = $selectClause;
2555 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2562 // select for group bys
2563 if (array_key_exists('group_bys', $table)) {
2564 foreach ($table['group_bys'] as $fieldName => $field) {
2566 if ($tableName == 'civicrm_address') {
2567 $this->_addressField
= TRUE;
2569 if ($tableName == 'civicrm_email') {
2570 $this->_emailField
= TRUE;
2572 if ($tableName == 'civicrm_phone') {
2573 $this->_phoneField
= TRUE;
2575 // 1. In many cases we want select clause to be built in slightly different way
2576 // for a particular field of a particular type.
2577 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2579 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2580 if ($selectClause) {
2581 $select[] = $selectClause;
2585 if (!empty($this->_params
['group_bys']) &&
2586 !empty($this->_params
['group_bys'][$fieldName]) &&
2587 !empty($this->_params
['group_bys_freq'])
2589 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2591 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2592 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2593 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2594 $field['title'] = 'Week';
2598 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2599 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2600 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2601 $field['title'] = 'Year';
2605 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2606 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2607 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2608 $field['title'] = 'Month';
2612 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2613 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2614 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2615 $field['title'] = 'Quarter';
2618 // for graphs and charts -
2619 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2620 $this->_interval
= $field['title'];
2621 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2622 = $field['title'] . ' Beginning';
2623 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2624 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2626 // just to make sure these values are transferred to rows.
2627 // since we 'll need them for calculation purpose,
2628 // e.g making subtotals look nicer or graphs
2629 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2630 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2637 if (empty($select)) {
2638 // CRM-21412 Do not give fatal error on report when no fields selected
2642 $this->_selectClauses
= $select;
2643 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2647 * Build select clause for a single field.
2649 * @param string $tableName
2650 * @param string $tableKey
2651 * @param string $fieldName
2652 * @param string $field
2656 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2657 if (!empty($field['pseudofield'])) {
2658 $alias = "{$tableName}_{$fieldName}";
2659 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2660 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2661 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = CRM_Utils_Array
::value('dbAlias', $field);
2662 $this->_selectAliases
[] = $alias;
2663 return ' 1 as ' . $alias;
2669 * Build where clause.
2671 public function where() {
2672 $this->storeWhereHavingClauseArray();
2674 if (empty($this->_whereClauses
)) {
2675 $this->_where
= "WHERE ( 1 ) ";
2676 $this->_having
= "";
2679 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2682 if ($this->_aclWhere
) {
2683 $this->_where
.= " AND {$this->_aclWhere} ";
2686 if (!empty($this->_havingClauses
)) {
2687 // use this clause to construct group by clause.
2688 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2693 * Store Where clauses into an array.
2695 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2696 * temp table that may not be part of the final where clause or added
2697 * in other functions
2699 public function storeWhereHavingClauseArray() {
2700 foreach ($this->_columns
as $tableName => $table) {
2701 if (array_key_exists('filters', $table)) {
2702 foreach ($table['filters'] as $fieldName => $field) {
2703 // respect pseudofield to filter spec so fields can be marked as
2704 // not to be handled here
2705 if (!empty($field['pseudofield'])) {
2708 $clause = $this->generateFilterClause($field, $fieldName);
2710 if (!empty($clause)) {
2711 if (!empty($field['having'])) {
2712 $this->_havingClauses
[] = $clause;
2715 $this->_whereClauses
[] = $clause;
2727 public function processReportMode() {
2728 $this->setOutputMode();
2731 = CRM_Utils_Request
::retrieve(
2734 CRM_Core_DAO
::$_nullObject
2737 $this->_absoluteUrl
= FALSE;
2739 $this->assign('printOnly', FALSE);
2741 if ($this->_outputMode
== 'print' ||
2742 ($this->_sendmail
&& !$this->_outputMode
)
2744 $this->assign('printOnly', TRUE);
2746 $this->addPaging
= FALSE;
2747 $this->assign('outputMode', 'print');
2748 $this->_outputMode
= 'print';
2749 if ($this->_sendmail
) {
2750 $this->_absoluteUrl
= TRUE;
2753 elseif ($this->_outputMode
== 'pdf') {
2755 $this->addPaging
= FALSE;
2756 $this->_absoluteUrl
= TRUE;
2758 elseif ($this->_outputMode
== 'csv') {
2760 $this->_absoluteUrl
= TRUE;
2761 $this->addPaging
= FALSE;
2763 elseif ($this->_outputMode
== 'group') {
2764 $this->assign('outputMode', 'group');
2766 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2767 $this->assign('outputMode', 'create_report');
2769 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2770 $this->_createNew
= TRUE;
2773 $this->assign('outputMode', $this->_outputMode
);
2774 $this->assign('printOnly', $printOnly);
2775 // Get today's date to include in printed reports
2777 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2778 $this->assign('reportDate', $reportDate);
2783 * Post Processing function for Form.
2785 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2786 * This function is not accessed when the api calls the report.
2788 public function beginPostProcess() {
2789 $this->setParams($this->controller
->exportValues($this->_name
));
2790 if (empty($this->_params
) &&
2793 $this->setParams($this->_formValues
);
2796 // hack to fix params when submitted from dashboard, CRM-8532
2797 // fields array is missing because form building etc is skipped
2798 // in dashboard mode for report
2799 //@todo - this could be done in the dashboard no we have a setter
2800 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2801 $this->setParams($this->_formValues
);
2804 $this->processReportMode();
2806 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2807 $this->_createNew
= ($this->_outputMode
== 'copy');
2808 CRM_Report_Form_Instance
::postProcess($this);
2810 if ($this->_outputMode
== 'delete') {
2811 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2814 $this->_formValues
= $this->_params
;
2816 $this->beginPostProcessCommon();
2820 * BeginPostProcess function run in both report mode and non-report mode (api).
2822 public function beginPostProcessCommon() {
2826 * Build the report query.
2828 * @param bool $applyLimit
2832 public function buildQuery($applyLimit = TRUE) {
2833 $this->buildGroupTempTable();
2836 $this->customDataFrom();
2837 $this->buildPermissionClause();
2842 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
2843 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
2845 $clause = "{$field['dbAlias']} as {$alias}";
2847 $this->_select
.= ", $clause ";
2850 if ($applyLimit && empty($this->_params
['charts'])) {
2853 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2855 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2856 $this->addToDeveloperTab($sql);
2861 * Build group by clause.
2863 public function groupBy() {
2864 $this->storeGroupByArray();
2866 if (!empty($this->_groupByArray
)) {
2867 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2872 * Build order by clause.
2874 public function orderBy() {
2875 $this->_orderBy
= "";
2876 $this->_sections
= array();
2877 $this->storeOrderByArray();
2878 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2879 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2881 $this->assign('sections', $this->_sections
);
2885 * Extract order by fields and store as an array.
2887 * In some cases other functions want to know which fields are selected for ordering by
2888 * Separating this into a separate function allows it to be called separately from constructing
2889 * the order by clause
2891 public function storeOrderByArray() {
2892 $orderBys = array();
2894 if (!empty($this->_params
['order_bys']) &&
2895 is_array($this->_params
['order_bys']) &&
2896 !empty($this->_params
['order_bys'])
2899 // Process order_bys in user-specified order
2900 foreach ($this->_params
['order_bys'] as $orderBy) {
2901 $orderByField = array();
2902 foreach ($this->_columns
as $tableName => $table) {
2903 if (array_key_exists('order_bys', $table)) {
2904 // For DAO columns defined in $this->_columns
2905 $fields = $table['order_bys'];
2907 elseif (array_key_exists('extends', $table)) {
2908 // For custom fields referenced in $this->_customGroupExtends
2909 $fields = CRM_Utils_Array
::value('fields', $table, array());
2914 if (!empty($fields) && is_array($fields)) {
2915 foreach ($fields as $fieldName => $field) {
2916 if ($fieldName == $orderBy['column']) {
2917 $orderByField = array_merge($field, $orderBy);
2918 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2925 if (!empty($orderByField)) {
2926 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2927 if ($this->groupConcatTested
) {
2928 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
2931 // Not sure when this is preferable to using tplField (which has
2932 // definitely been tested to work in cases then this does not.
2933 // in caution not switching unless report has been tested for
2934 // group concat functionality.
2935 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2938 // Record any section headers for assignment to the template
2939 if (!empty($orderBy['section'])) {
2940 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2941 $this->_sections
[$orderByField['tplField']] = $orderByField;
2947 $this->_orderByArray
= $orderBys;
2949 $this->assign('sections', $this->_sections
);
2953 * Determine unselected columns.
2957 public function unselectedOrderByColumns() {
2958 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
2962 * Determine unselected columns.
2966 public function unselectedSectionColumns() {
2967 if (is_array($this->_sections
)) {
2968 return array_diff_key($this->_sections
, $this->getSelectColumns());
2976 * Build output rows.
2978 * @param string $sql
2979 * @param array $rows
2981 public function buildRows($sql, &$rows) {
2982 if (!$this->optimisedForOnlyFullGroupBy
) {
2983 CRM_Core_DAO
::disableFullGroupByMode();
2985 $dao = CRM_Core_DAO
::executeQuery($sql);
2986 if (stristr($this->_select
, 'SQL_CALC_FOUND_ROWS')) {
2987 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
2989 CRM_Core_DAO
::reenableFullGroupByMode();
2990 if (!is_array($rows)) {
2994 // use this method to modify $this->_columnHeaders
2995 $this->modifyColumnHeaders();
2997 $unselectedSectionColumns = $this->unselectedSectionColumns();
2999 while ($dao->fetch()) {
3001 foreach ($this->_columnHeaders
as $key => $value) {
3002 if (property_exists($dao, $key)) {
3003 $row[$key] = $dao->$key;
3007 // section headers not selected for display need to be added to row
3008 foreach ($unselectedSectionColumns as $key => $values) {
3009 if (property_exists($dao, $key)) {
3010 $row[$key] = $dao->$key;
3019 * Calculate section totals.
3021 * When "order by" fields are marked as sections, this assigns to the template
3022 * an array of total counts for each section. This data is used by the Smarty
3023 * plugin {sectionTotal}.
3025 public function sectionTotals() {
3027 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3028 if (empty($this->_selectAliases
)) {
3032 if (!empty($this->_sections
)) {
3033 // build the query with no LIMIT clause
3034 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
3035 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3037 // pull section aliases out of $this->_sections
3038 $sectionAliases = array_keys($this->_sections
);
3041 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
3042 $ifnulls[] = "ifnull($alias, '') as $alias";
3044 $this->_select
= "SELECT " . implode(", ", $ifnulls);
3045 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
3047 // Group (un-limited) report by all aliases and get counts. This might
3048 // be done more efficiently when the contents of $sql are known, ie. by
3049 // overriding this method in the report class.
3051 $query = $this->_select
.
3052 ", count(*) as ct from ($sql) as subquery group by " .
3053 implode(", ", $sectionAliases);
3055 // initialize array of total counts
3057 $dao = CRM_Core_DAO
::executeQuery($query);
3058 while ($dao->fetch()) {
3060 // let $this->_alterDisplay translate any integer ids to human-readable values.
3061 $rows[0] = $dao->toArray();
3062 $this->alterDisplay($rows);
3065 // add totals for all permutations of section values
3068 $aliasCount = count($sectionAliases);
3069 foreach ($sectionAliases as $alias) {
3070 $values[] = $row[$alias];
3071 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
3072 if ($i == $aliasCount) {
3073 // the last alias is the lowest-level section header; use count as-is
3074 $totals[$key] = $dao->ct
;
3077 // other aliases are higher level; roll count into their total
3078 $totals[$key] +
= $dao->ct
;
3082 $this->assign('sectionTotals', $totals);
3087 * Modify column headers.
3089 public function modifyColumnHeaders() {
3090 // use this method to modify $this->_columnHeaders
3094 * Move totals columns to the right edge of the table.
3096 * It seems like a more logical layout to have any totals columns on the far right regardless of
3097 * the location of the rest of their table.
3099 public function moveSummaryColumnsToTheRightHandSide() {
3100 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
3101 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
3105 * Assign rows to the template.
3107 * @param array $rows
3109 public function doTemplateAssignment(&$rows) {
3110 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
3111 $this->assign_by_ref('rows', $rows);
3112 $this->assign('statistics', $this->statistics($rows));
3116 * Build report statistics.
3118 * Override this method to build your own statistics.
3120 * @param array $rows
3124 public function statistics(&$rows) {
3125 $statistics = array();
3127 $count = count($rows);
3128 // Why do we increment the count for rollup seems to artificially inflate the count.
3129 // It seems perhaps intentional to include the summary row in the count of results - although
3130 // this just seems odd.
3131 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3135 $this->countStat($statistics, $count);
3137 $this->groupByStat($statistics);
3139 $this->filterStat($statistics);
3145 * Add count statistics.
3147 * @param array $statistics
3150 public function countStat(&$statistics, $count) {
3151 $statistics['counts']['rowCount'] = array(
3152 'title' => ts('Row(s) Listed'),
3156 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3157 $statistics['counts']['rowsFound'] = array(
3158 'title' => ts('Total Row(s)'),
3159 'value' => $this->_rowsFound
,
3165 * Add group by statistics.
3167 * @param array $statistics
3169 public function groupByStat(&$statistics) {
3170 if (!empty($this->_params
['group_bys']) &&
3171 is_array($this->_params
['group_bys']) &&
3172 !empty($this->_params
['group_bys'])
3174 foreach ($this->_columns
as $tableName => $table) {
3175 if (array_key_exists('group_bys', $table)) {
3176 foreach ($table['group_bys'] as $fieldName => $field) {
3177 if (!empty($this->_params
['group_bys'][$fieldName])) {
3178 $combinations[] = $field['title'];
3183 $statistics['groups'][] = array(
3184 'title' => ts('Grouping(s)'),
3185 'value' => implode(' & ', $combinations),
3191 * Filter statistics.
3193 * @param array $statistics
3195 public function filterStat(&$statistics) {
3196 foreach ($this->_columns
as $tableName => $table) {
3197 if (array_key_exists('filters', $table)) {
3198 foreach ($table['filters'] as $fieldName => $field) {
3199 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3200 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3201 CRM_Utils_Array
::value('operatorType', $field) !=
3202 CRM_Report_Form
::OP_MONTH
3206 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3207 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3208 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3209 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3210 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3212 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3213 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3215 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3216 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3219 $statistics['filters'][] = array(
3220 'title' => $field['title'],
3221 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3224 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3225 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3227 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3228 $statistics['filters'][] = array(
3229 'title' => $field['title'],
3230 'value' => $pair[$rel],
3235 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3238 $pair = $this->getOperationPair(
3239 CRM_Utils_Array
::value('operatorType', $field),
3242 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3243 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3244 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3245 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3246 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3248 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3249 $this->setEntityRefDefaults($field, $tableName);
3250 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3251 array('id' => $val) +
3252 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3254 foreach ($result['values'] as $v) {
3255 $values[] = $v['label'];
3257 $value = "{$pair[$op]} " . implode(', ', $values);
3259 elseif ($op == 'nll' ||
$op == 'nnll') {
3260 $value = $pair[$op];
3262 elseif (is_array($val) && (!empty($val))) {
3263 $options = CRM_Utils_Array
::value('options', $field, array());
3264 foreach ($val as $key => $valIds) {
3265 if (isset($options[$valIds])) {
3266 $val[$key] = $options[$valIds];
3269 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3270 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3271 $val = implode(', ', $val);
3272 $value = "{$pair[$op]} " . $val;
3274 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3275 isset($field['options']) &&
3276 is_array($field['options']) && !empty($field['options'])
3278 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3279 CRM_Utils_Array
::value($val, $field['options'], $val);
3282 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3285 if ($value && empty($field['no_display'])) {
3286 $statistics['filters'][] = array(
3287 'title' => CRM_Utils_Array
::value('title', $field),
3298 * End post processing.
3300 * @param array|null $rows
3302 public function endPostProcess(&$rows = NULL) {
3303 $this->assign('report_class', get_class($this));
3304 if ($this->_storeResultSet
) {
3305 $this->_resultSet
= $rows;
3308 if ($this->_outputMode
== 'print' ||
3309 $this->_outputMode
== 'pdf' ||
3313 $content = $this->compileContent();
3314 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3318 if ($this->_sendmail
) {
3319 $config = CRM_Core_Config
::singleton();
3320 $attachments = array();
3322 if ($this->_outputMode
== 'csv') {
3324 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3325 ": {$url}</p>" . '<p>' .
3326 ts('The report is attached as a CSV file.') . '</p>' .
3327 $this->_formValues
['report_footer'];
3329 $csvFullFilename = $config->templateCompileDir
.
3330 CRM_Utils_File
::makeFileName('CiviReport.csv');
3331 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3332 file_put_contents($csvFullFilename, $csvContent);
3333 $attachments[] = array(
3334 'fullPath' => $csvFullFilename,
3335 'mime_type' => 'text/csv',
3336 'cleanName' => 'CiviReport.csv',
3339 if ($this->_outputMode
== 'pdf') {
3340 // generate PDF content
3341 $pdfFullFilename = $config->templateCompileDir
.
3342 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3343 file_put_contents($pdfFullFilename,
3344 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3345 TRUE, array('orientation' => 'landscape')
3348 // generate Email Content
3350 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3351 ": {$url}</p>" . '<p>' .
3352 ts('The report is attached as a PDF file.') . '</p>' .
3353 $this->_formValues
['report_footer'];
3355 $attachments[] = array(
3356 'fullPath' => $pdfFullFilename,
3357 'mime_type' => 'application/pdf',
3358 'cleanName' => 'CiviReport.pdf',
3362 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3363 $this->_outputMode
, $attachments
3366 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3369 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3373 elseif ($this->_outputMode
== 'print') {
3377 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3378 $config = CRM_Core_Config
::singleton();
3379 //get chart image name
3380 $chartImg = $this->_chartId
. '.png';
3381 //get image url path
3383 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3385 $uploadUrl .= $chartImg;
3386 //get image doc path to overwrite
3388 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3389 'openFlashChart/' . $chartImg;
3391 $chart = imagecreatefrompng($uploadUrl);
3392 //convert it into formatted png
3393 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3394 //overwrite with same image
3395 imagepng($chart, $uploadImg);
3397 imagedestroy($chart);
3399 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3401 CRM_Utils_System
::civiExit();
3403 elseif ($this->_outputMode
== 'csv') {
3404 CRM_Report_Utils_Report
::export2csv($this, $rows);
3406 elseif ($this->_outputMode
== 'group') {
3407 $group = $this->_params
['groups'];
3408 $this->add2group($group);
3413 * Set store result set indicator to TRUE.
3415 * @todo explain what this does
3417 public function storeResultSet() {
3418 $this->_storeResultSet
= TRUE;
3426 public function getResultSet() {
3427 return $this->_resultSet
;
3431 * Get the sql used to generate the report.
3435 public function getReportSql() {
3436 return $this->sqlArray
;
3440 * Use the form name to create the tpl file name.
3444 public function getTemplateFileName() {
3445 $defaultTpl = parent
::getTemplateFileName();
3446 $template = CRM_Core_Smarty
::singleton();
3447 if (!$template->template_exists($defaultTpl)) {
3448 $defaultTpl = 'CRM/Report/Form.tpl';
3454 * Compile the report content.
3456 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3460 public function compileContent() {
3461 $templateFile = $this->getHookedTemplateFileName();
3462 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3463 CRM_Core_Form
::$_template->fetch($templateFile) .
3464 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3469 * Post process function.
3471 public function postProcess() {
3472 // get ready with post process params
3473 $this->beginPostProcess();
3476 $sql = $this->buildQuery();
3478 // build array of result based on column headers. This method also allows
3479 // modifying column headers before using it to build result set i.e $rows.
3481 $this->buildRows($sql, $rows);
3483 // format result set.
3484 $this->formatDisplay($rows);
3486 // assign variables to templates
3487 $this->doTemplateAssignment($rows);
3489 // do print / pdf / instance stuff if needed
3490 $this->endPostProcess($rows);
3496 * @param int $rowCount
3500 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3501 // lets do the pager if in html mode
3502 $this->_limit
= NULL;
3504 // CRM-14115, over-ride row count if rowCount is specified in URL
3505 if ($this->_dashBoardRowCount
) {
3506 $rowCount = $this->_dashBoardRowCount
;
3508 if ($this->addPaging
) {
3509 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3511 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3513 // @todo all http vars should be extracted in the preProcess
3514 // - not randomly in the class
3515 if (!$pageId && !empty($_POST)) {
3516 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3517 $pageId = max((int) $_POST['crmPID_B'], 1);
3519 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3520 $pageId = max((int) $_POST['crmPID'], 1);
3522 unset($_POST['crmPID_B'], $_POST['crmPID']);
3525 $pageId = $pageId ?
$pageId : 1;
3526 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3527 $offset = ($pageId - 1) * $rowCount;
3529 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3530 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3532 $this->_limit
= " LIMIT $offset, $rowCount";
3533 return array($offset, $rowCount);
3535 if ($this->_limitValue
) {
3536 if ($this->_offsetValue
) {
3537 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3540 $this->_limit
= " LIMIT " . $this->_limitValue
;
3548 * @param int $rowCount
3550 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3551 // CRM-14115, over-ride row count if rowCount is specified in URL
3552 if ($this->_dashBoardRowCount
) {
3553 $rowCount = $this->_dashBoardRowCount
;
3556 if ($this->_limit
&& ($this->_limit
!= '')) {
3557 if (!$this->_rowsFound
) {
3558 $sql = "SELECT FOUND_ROWS();";
3559 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3562 'total' => $this->_rowsFound
,
3563 'rowCount' => $rowCount,
3564 'status' => ts('Records') . ' %%StatusMessage%%',
3565 'buttonBottom' => 'PagerBottomButton',
3566 'buttonTop' => 'PagerTopButton',
3568 if (!empty($this->controller
)) {
3569 // This happens when being called from the api Really we want the api to be able to
3570 // pass paging parameters, but at this stage just preventing test crashes.
3571 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3574 $pager = new CRM_Utils_Pager($params);
3575 $this->assign_by_ref('pager', $pager);
3576 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3581 * Build a group filter with contempt for large data sets.
3583 * This function has been retained as it takes time to migrate the reports over
3584 * to the new method which will not crash on large datasets.
3588 * @param string $field
3589 * @param mixed $value
3594 public function legacySlowGroupFilterClause($field, $value, $op) {
3595 $smartGroupQuery = "";
3597 $group = new CRM_Contact_DAO_Group();
3598 $group->is_active
= 1;
3600 $smartGroups = array();
3601 while ($group->fetch()) {
3602 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3603 $group->saved_search_id
3605 $smartGroups[] = $group->id
;
3609 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3611 $smartGroupQuery = '';
3612 if (!empty($smartGroups)) {
3613 $smartGroups = implode(',', $smartGroups);
3614 $smartGroupQuery = " UNION DISTINCT
3615 SELECT DISTINCT smartgroup_contact.contact_id
3616 FROM civicrm_group_contact_cache smartgroup_contact
3617 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3620 $sqlOp = $this->getSQLOperator($op);
3621 if (!is_array($value)) {
3622 $value = array($value);
3624 //include child groups if any
3625 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3627 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3629 $contactAlias = $this->_aliases
['civicrm_contact'];
3630 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3631 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3633 return " {$contactAlias}.id {$sqlOp} (
3634 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3635 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3636 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3637 {$smartGroupQuery} ) ";
3641 * Build where clause for groups.
3643 * @param string $field
3644 * @param mixed $value
3649 public function whereGroupClause($field, $value, $op) {
3650 if ($this->groupFilterNotOptimised
) {
3651 return $this->legacySlowGroupFilterClause($field, $value, $op);
3653 if ($op === 'notin') {
3654 return " group_temp_table.id IS NULL ";
3656 // We will have used an inner join instead.
3662 * Create a table of the contact ids included by the group filter.
3664 * This function is called by both the api (tests) and the UI.
3666 public function buildGroupTempTable() {
3667 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3670 $filteredGroups = (array) $this->_params
['gid_value'];
3672 $groups = civicrm_api3('Group', 'get', array(
3674 'id' => array('IN' => $filteredGroups),
3675 'saved_search_id' => array('>' => 0),
3678 $smartGroups = array_keys($groups['values']);
3681 SELECT DISTINCT group_contact.contact_id as id
3682 FROM civicrm_group_contact group_contact
3683 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3684 AND group_contact.status = 'Added' ";
3686 if (!empty($smartGroups)) {
3687 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3688 $smartGroups = implode(',', $smartGroups);
3691 SELECT smartgroup_contact.contact_id as id
3692 FROM civicrm_group_contact_cache smartgroup_contact
3693 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3696 $this->groupTempTable
= CRM_Utils_SQL_TempTable
::build()->setCategory('rptgrp')->setId(date('Ymd_') . uniqid())->getName();
3697 $this->executeReportQuery("
3698 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3701 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3705 * Execute query and add it to the developer tab.
3707 * @param string $query
3708 * @param array $params
3710 * @return \CRM_Core_DAO|object
3712 protected function executeReportQuery($query, $params = array()) {
3713 $this->addToDeveloperTab($query);
3714 return CRM_Core_DAO
::executeQuery($query, $params);
3718 * Build where clause for tags.
3720 * @param string $field
3721 * @param mixed $value
3726 public function whereTagClause($field, $value, $op) {
3727 // not using left join in query because if any contact
3728 // belongs to more than one tag, results duplicate
3730 $sqlOp = $this->getSQLOperator($op);
3731 if (!is_array($value)) {
3732 $value = array($value);
3734 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3735 $entity_table = $this->_tagFilterTable
;
3736 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3737 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3738 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3739 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3743 * Generate membership organization clause.
3745 * @param mixed $value
3746 * @param string $op SQL Operator
3750 public function whereMembershipOrgClause($value, $op) {
3751 $sqlOp = $this->getSQLOperator($op);
3752 if (!is_array($value)) {
3753 $value = array($value);
3756 $tmp_membership_org_sql_list = implode(', ', $value);
3757 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3758 SELECT DISTINCT mem.contact_id
3759 FROM civicrm_membership mem
3760 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3761 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3762 WHERE mt.member_of_contact_id IN (" .
3763 $tmp_membership_org_sql_list . ")
3764 AND mt.is_active = '1'
3765 AND mem_status.is_current_member = '1'
3766 AND mem_status.is_active = '1' ) ";
3770 * Generate Membership Type SQL Clause.
3772 * @param mixed $value
3778 public function whereMembershipTypeClause($value, $op) {
3779 $sqlOp = $this->getSQLOperator($op);
3780 if (!is_array($value)) {
3781 $value = array($value);
3784 $tmp_membership_sql_list = implode(', ', $value);
3785 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3786 SELECT DISTINCT mem.contact_id
3787 FROM civicrm_membership mem
3788 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3789 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3790 WHERE mem.membership_type_id IN (" .
3791 $tmp_membership_sql_list . ")
3792 AND mt.is_active = '1'
3793 AND mem_status.is_current_member = '1'
3794 AND mem_status.is_active = '1' ) ";
3798 * Buld contact acl clause
3799 * @deprecated in favor of buildPermissionClause
3801 * @param string $tableAlias
3803 public function buildACLClause($tableAlias = 'contact_a') {
3804 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3808 * Build the permision clause for all entities in this report
3810 public function buildPermissionClause() {
3812 foreach ($this->selectedTables() as $tableName) {
3813 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3814 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3815 $tableAlias = $this->_columns
[$tableName]['alias'];
3816 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3817 foreach ($clauses as $field => $clause) {
3818 // Skip contact_id field if redundant
3819 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3820 $ret["$tableName.$field"] = $clause;
3825 // Override output from buildACLClause
3826 $this->_aclFrom
= NULL;
3827 $this->_aclWhere
= implode(' AND ', $ret);
3831 * Add custom data to the columns.
3833 * @param bool $addFields
3834 * @param array $permCustomGroupIds
3836 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3837 if (empty($this->_customGroupExtends
)) {
3840 if (!is_array($this->_customGroupExtends
)) {
3841 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3843 $customGroupWhere = '';
3844 if (!empty($permCustomGroupIds)) {
3845 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3849 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3850 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3851 FROM civicrm_custom_group cg
3852 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3853 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3855 cg.is_active = 1 AND
3856 cf.is_active = 1 AND
3857 cf.is_searchable = 1
3858 ORDER BY cg.weight, cf.weight";
3859 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3862 while ($customDAO->fetch()) {
3863 if ($customDAO->table_name
!= $curTable) {
3864 $curTable = $customDAO->table_name
;
3865 $curFields = $curFilters = array();
3868 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3869 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3870 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3871 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3873 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3874 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3875 $this->_columns
[$curTable][$colKey] = array();
3879 $fieldName = 'custom_' . $customDAO->cf_id
;
3882 // this makes aliasing work in favor
3883 $curFields[$fieldName] = array(
3884 'name' => $customDAO->column_name
,
3885 'title' => $customDAO->label
,
3886 'dataType' => $customDAO->data_type
,
3887 'htmlType' => $customDAO->html_type
,
3890 if ($this->_customGroupFilters
) {
3891 // this makes aliasing work in favor
3892 $curFilters[$fieldName] = array(
3893 'name' => $customDAO->column_name
,
3894 'title' => $customDAO->label
,
3895 'dataType' => $customDAO->data_type
,
3896 'htmlType' => $customDAO->html_type
,
3900 switch ($customDAO->data_type
) {
3903 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3904 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3905 // CRM-6946, show time part for datetime date fields
3906 if ($customDAO->time_format
) {
3907 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3912 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3913 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3914 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3918 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3919 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3923 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3924 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3925 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3929 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3930 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3934 case 'StateProvince':
3936 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3938 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3939 if ($options !== FALSE) {
3940 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3941 $curFilters[$fieldName]['options'] = $options;
3945 case 'ContactReference':
3946 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3947 $curFilters[$fieldName]['name'] = 'display_name';
3948 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3950 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3951 $curFields[$fieldName]['name'] = 'display_name';
3952 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3956 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3957 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3961 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3962 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3963 if ($options !== FALSE) {
3964 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3965 $curFilters[$fieldName]['options'] = $options;
3969 if (!array_key_exists('type', $curFields[$fieldName])) {
3970 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3974 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3976 if ($this->_customGroupFilters
) {
3977 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3979 if ($this->_customGroupGroupBy
) {
3980 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3986 * Build custom data from clause.
3988 * @param bool $joinsForFiltersOnly
3989 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3991 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3992 if (empty($this->_customGroupExtends
)) {
3995 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3996 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3997 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3998 $customTables = array();
3999 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
4000 while ($customTablesDAO->fetch()) {
4001 $customTables[] = $customTablesDAO->table_name
;
4004 foreach ($this->_columns
as $table => $prop) {
4005 if (in_array($table, $customTables)) {
4006 $extendsTable = $mapper[$prop['extends']];
4007 // Check field is required for rendering the report.
4008 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4011 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
4013 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
4015 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4016 // handle for ContactReference
4017 if (array_key_exists('fields', $prop)) {
4018 foreach ($prop['fields'] as $fieldName => $field) {
4019 if (CRM_Utils_Array
::value('dataType', $field) ==
4022 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
4024 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4033 * Check if the field is selected.
4035 * @param string $prop
4039 public function isFieldSelected($prop) {
4044 if (!empty($this->_params
['fields'])) {
4045 foreach (array_keys($prop['fields']) as $fieldAlias) {
4046 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
4047 if ($customFieldId) {
4048 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
4052 //might be survey response field.
4053 if (!empty($this->_params
['fields']['survey_response']) &&
4054 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4062 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
4063 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4064 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
4065 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4072 if (!empty($this->_params
['order_bys'])) {
4073 foreach (array_keys($prop['fields']) as $fieldAlias) {
4074 foreach ($this->_params
['order_bys'] as $orderBy) {
4075 if ($fieldAlias == $orderBy['column'] &&
4076 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
4083 return $this->isFieldFiltered($prop);
4088 * Check if the field is used as a filter.
4090 * @param string $prop
4094 protected function isFieldFiltered($prop) {
4095 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
4096 foreach ($prop['filters'] as $fieldAlias => $val) {
4105 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
4106 (!empty($this->_params
[$fieldAlias . '_' . $attach])
4107 ||
($attach != 'relative' &&
4108 $this->_params
[$fieldAlias . '_' . $attach] == '0')
4114 if (!empty($this->_params
[$fieldAlias . '_op']) &&
4115 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
4126 * Check for empty order_by configurations and remove them.
4128 * Also set template to hide them.
4130 * @param array $formValues
4132 public function preProcessOrderBy(&$formValues) {
4133 // Object to show/hide form elements
4134 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4136 $_showHide->addShow('optionField_1');
4138 // Cycle through order_by options; skip any empty ones, and hide them as well
4141 if (!empty($formValues['order_bys'])) {
4142 foreach ($formValues['order_bys'] as $order_by) {
4143 if ($order_by['column'] && $order_by['column'] != '-') {
4144 $_showHide->addShow('optionField_' . $n);
4145 $orderBys[$n] = $order_by;
4150 for ($i = $n; $i <= 5; $i++
) {
4152 $_showHide->addHide('optionField_' . $i);
4156 // overwrite order_by options with modified values
4157 if (!empty($orderBys)) {
4158 $formValues['order_bys'] = $orderBys;
4161 $formValues['order_bys'] = array(1 => array('column' => '-'));
4164 // assign show/hide data to template
4165 $_showHide->addToTemplate();
4169 * Check if table name has columns in SELECT clause.
4171 * @param string $tableName
4172 * Name of table (index of $this->_columns array).
4176 public function isTableSelected($tableName) {
4177 return in_array($tableName, $this->selectedTables());
4181 * Check if table name has columns in WHERE or HAVING clause.
4183 * @param string $tableName
4184 * Name of table (index of $this->_columns array).
4188 public function isTableFiltered($tableName) {
4189 // Cause the array to be generated if not previously done.
4190 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4191 $this->selectedTables();
4193 return in_array($tableName, $this->filteredTables
);
4197 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4199 * If the array is unset it will be built.
4204 public function selectedTables() {
4205 if (!$this->_selectedTables
) {
4206 $orderByColumns = array();
4207 if (array_key_exists('order_bys', $this->_params
) &&
4208 is_array($this->_params
['order_bys'])
4210 foreach ($this->_params
['order_bys'] as $orderBy) {
4211 $orderByColumns[] = $orderBy['column'];
4215 foreach ($this->_columns
as $tableName => $table) {
4216 if (array_key_exists('fields', $table)) {
4217 foreach ($table['fields'] as $fieldName => $field) {
4218 if (!empty($field['required']) ||
4219 !empty($this->_params
['fields'][$fieldName])
4221 $this->_selectedTables
[] = $tableName;
4226 if (array_key_exists('order_bys', $table)) {
4227 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4228 if (in_array($orderByName, $orderByColumns)) {
4229 $this->_selectedTables
[] = $tableName;
4234 if (array_key_exists('filters', $table)) {
4235 foreach ($table['filters'] as $filterName => $filter) {
4236 if (!empty($this->_params
["{$filterName}_value"])
4237 ||
!empty($this->_params
["{$filterName}_relative"])
4238 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4240 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4243 $this->_selectedTables
[] = $tableName;
4244 $this->filteredTables
[] = $tableName;
4251 return $this->_selectedTables
;
4255 * Add address fields.
4257 * @deprecated - use getAddressColumns which is a more accurate description
4258 * and also accepts an array of options rather than a long list
4260 * adding address fields to construct function in reports
4262 * @param bool $groupBy
4263 * Add GroupBy? Not appropriate for detail report.
4264 * @param bool $orderBy
4265 * Add GroupBy? Not appropriate for detail report.
4266 * @param bool $filters
4267 * @param array $defaults
4270 * address fields for construct clause
4272 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4273 $defaultAddressFields = array(
4274 'street_address' => ts('Street Address'),
4275 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4276 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4277 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4278 'street_number' => ts('Street Number'),
4279 'street_name' => ts('Street Name'),
4280 'street_unit' => ts('Street Unit'),
4281 'city' => ts('City'),
4282 'postal_code' => ts('Postal Code'),
4283 'postal_code_suffix' => ts('Postal Code Suffix'),
4284 'country_id' => ts('Country'),
4285 'state_province_id' => ts('State/Province'),
4286 'county_id' => ts('County'),
4288 $addressFields = array(
4289 'civicrm_address' => array(
4290 'dao' => 'CRM_Core_DAO_Address',
4292 'address_name' => array(
4293 'title' => ts('Address Name'),
4294 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4298 'grouping' => 'location-fields',
4301 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4302 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4303 'title' => $fieldLabel,
4304 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4308 $street_address_filters = $general_address_filters = array();
4310 // Address filter depends on whether street address parsing is enabled.
4312 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4315 if ($addressOptions['street_address_parsing']) {
4316 $street_address_filters = array(
4317 'street_number' => array(
4318 'title' => ts('Street Number'),
4319 'type' => CRM_Utils_Type
::T_INT
,
4320 'name' => 'street_number',
4322 'street_name' => array(
4323 'title' => ts('Street Name'),
4324 'name' => 'street_name',
4325 'type' => CRM_Utils_Type
::T_STRING
,
4330 $street_address_filters = array(
4331 'street_address' => array(
4332 'title' => ts('Street Address'),
4333 'type' => CRM_Utils_Type
::T_STRING
,
4334 'name' => 'street_address',
4338 $general_address_filters = array(
4339 'postal_code' => array(
4340 'title' => ts('Postal Code'),
4341 'type' => CRM_Utils_Type
::T_STRING
,
4342 'name' => 'postal_code',
4345 'title' => ts('City'),
4346 'type' => CRM_Utils_Type
::T_STRING
,
4349 'country_id' => array(
4350 'name' => 'country_id',
4351 'title' => ts('Country'),
4352 'type' => CRM_Utils_Type
::T_INT
,
4353 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4354 'options' => CRM_Core_PseudoConstant
::country(),
4356 'state_province_id' => array(
4357 'name' => 'state_province_id',
4358 'title' => ts('State/Province'),
4359 'type' => CRM_Utils_Type
::T_INT
,
4360 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4361 'options' => array(),
4363 'county_id' => array(
4364 'name' => 'county_id',
4365 'title' => ts('County'),
4366 'type' => CRM_Utils_Type
::T_INT
,
4367 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4368 'options' => array(),
4372 $addressFields['civicrm_address']['filters'] = array_merge(
4373 $street_address_filters,
4374 $general_address_filters);
4377 $addressFields['civicrm_address']['order_bys'] = array(
4378 'street_name' => array('title' => ts('Street Name')),
4379 'street_number' => array('title' => ts('Odd / Even Street Number')),
4380 'street_address' => NULL,
4382 'postal_code' => NULL,
4387 $addressFields['civicrm_address']['group_bys'] = array(
4388 'street_address' => NULL,
4390 'postal_code' => NULL,
4391 'state_province_id' => array(
4392 'title' => ts('State/Province'),
4394 'country_id' => array(
4395 'title' => ts('Country'),
4397 'county_id' => array(
4398 'title' => ts('County'),
4402 return $addressFields;
4406 * Do AlterDisplay processing on Address Fields.
4407 * If there are multiple address field values then
4408 * on basis of provided separator the code values are translated into respective labels
4411 * @param array $rows
4412 * @param int $rowNum
4413 * @param string $baseUrl
4414 * @param string $linkText
4415 * @param string $separator
4419 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4420 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4421 $entryFound = FALSE;
4423 'civicrm_address_country_id' => 'country',
4424 'civicrm_address_county_id' => 'county',
4425 'civicrm_address_state_province_id' => 'stateProvince',
4427 foreach ($columnMap as $fieldName => $fnName) {
4428 if (array_key_exists($fieldName, $row)) {
4429 if ($values = $row[$fieldName]) {
4430 $values = (array) explode($separator, $values);
4431 $rows[$rowNum][$fieldName] = [];
4432 $addressField = $fnName == 'stateProvince' ?
'state' : $fnName;
4433 foreach ($values as $value) {
4434 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant
::$fnName($value);
4436 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4438 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4439 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4440 $criteriaQueryParams,
4441 str_replace('civicrm_address_', '', $fieldName),
4442 str_replace('civicrm_address_', '', $fieldName),
4443 implode(',', $values)
4444 ), $this->_absoluteUrl
, $this->_id
4446 $rows[$rowNum]["{$fieldName}_link"] = $url;
4447 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", array(1 => $linkText, 2 => $addressField));
4458 * Do AlterDisplay processing on Address Fields.
4461 * @param array $rows
4462 * @param int $rowNum
4463 * @param string $baseUrl
4464 * @param string $linkText
4468 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4469 $entryFound = FALSE;
4470 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4471 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4472 $addLinks = array('gender_id' => 'Gender');
4473 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4474 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4475 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4476 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4477 $rowLabels = array();
4478 foreach ($rowValues as $rowValue) {
4480 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4483 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4484 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4485 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4491 $yesNoFields = array(
4492 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4494 foreach ($yesNoFields as $fieldName) {
4495 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4496 // Since these are essentially 'negative fields' it feels like it
4497 // makes sense to only highlight the exceptions hence no 'No'.
4498 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4503 // Handle employer id
4504 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4505 $employerId = $row['civicrm_contact_employer_id'];
4507 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact
::displayName($employerId);
4508 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
4509 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4518 * Adjusts dates passed in to YEAR() for fiscal year.
4520 * @param string $fieldName
4524 public function fiscalYearOffset($fieldName) {
4525 $config = CRM_Core_Config
::singleton();
4526 $fy = $config->fiscalYearStart
;
4527 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4528 ($fy['d'] == 1 && $fy['M'] == 1)
4530 return "YEAR( $fieldName )";
4532 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4533 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4537 * Add Address into From Table if required.
4539 * @deprecated use joinAddressFromContact
4540 * (left here in case extensions use it).
4542 public function addAddressFromClause() {
4543 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinAddressFromContact');
4544 // include address field if address column is to be included
4545 if ((isset($this->_addressField
) &&
4546 $this->_addressField
4548 $this->isTableSelected('civicrm_address')
4551 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4552 ON ({$this->_aliases['civicrm_contact']}.id =
4553 {$this->_aliases['civicrm_address']}.contact_id) AND
4554 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4559 * Add Phone into From Table if required.
4561 * @deprecated use joinPhoneFromContact
4562 * (left here in case extensions use it).
4564 public function addPhoneFromClause() {
4565 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Report_Form::joinPhoneFromContact');
4566 // include address field if address column is to be included
4567 if ($this->isTableSelected('civicrm_phone')) {
4569 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4570 ON ({$this->_aliases['civicrm_contact']}.id =
4571 {$this->_aliases['civicrm_phone']}.contact_id) AND
4572 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4577 * Add Address into From Table if required.
4579 * Prefix will be added to both tables as
4580 * it is assumed you are using it to get address of a secondary contact.
4582 * @param string $prefix
4583 * @param array $extra Additional options.
4584 * Not currently used in core but may be used in override extensions.
4586 protected function joinAddressFromContact($prefix = '', $extra = array()) {
4587 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4588 $isJoinRequired = $this->_addressField
;
4589 foreach ($addressTables as $addressTable) {
4590 if ($this->isTableSelected($prefix . $addressTable)) {
4591 $isJoinRequired = TRUE;
4594 if ($isJoinRequired) {
4596 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4597 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4598 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id) AND
4599 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4604 * Add Country into From Table if required.
4606 * Prefix will be added to both tables as
4607 * it is assumed you are using it to get address of a secondary contact.
4609 * @param string $prefix
4610 * @param array $extra Additional options.
4611 * Not currently used in core but may be used in override extensions.
4613 protected function joinCountryFromAddress($prefix = '', $extra = array()) {
4614 // include country field if country column is to be included
4615 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4616 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4617 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4620 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4621 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id AND
4622 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4627 * Add Phone into From Table if required.
4629 * Prefix will be added to both tables as
4630 * it is assumed you are using it to get address of a secondary contact.
4632 * @param string $prefix
4633 * @param array $extra Additional options.
4634 * Not currently used in core but may be used in override extensions.
4636 protected function joinPhoneFromContact($prefix = '', $extra = array()) {
4637 // include phone field if phone column is to be included
4638 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4640 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4641 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id AND
4642 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4647 * Add Email into From Table if required.
4649 * Prefix will be added to both tables as
4650 * it is assumed you are using it to get address of a secondary contact.
4652 * @param string $prefix
4653 * @param array $extra Additional options.
4654 * Not currently used in core but may be used in override extensions.
4656 protected function joinEmailFromContact($prefix = '', $extra = array()) {
4657 // include email field if email column is to be included
4658 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4660 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4661 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id AND
4662 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1) ";
4667 * Add Financial Transaction into From Table if required.
4669 public function addFinancialTrxnFromClause() {
4670 if ($this->isTableSelected('civicrm_financial_trxn')) {
4672 LEFT JOIN civicrm_entity_financial_trxn eftcc
4673 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4674 eftcc.entity_table = 'civicrm_contribution')
4675 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4676 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4681 * Get phone columns to add to array.
4683 * @param array $options
4684 * - prefix Prefix to add to table (in case of more than one instance of the table)
4685 * - prefix_label Label to give columns from this phone table instance
4688 * phone columns definition
4690 public function getPhoneColumns($options = array()) {
4691 $defaultOptions = array(
4693 'prefix_label' => '',
4696 $options = array_merge($defaultOptions, $options);
4699 $options['prefix'] . 'civicrm_phone' => array(
4700 'dao' => 'CRM_Core_DAO_Phone',
4702 $options['prefix'] . 'phone' => array(
4703 'title' => $options['prefix_label'] . ts('Phone'),
4713 * Get a standard set of contact fields.
4717 public function getBasicContactFields() {
4719 'sort_name' => array(
4720 'title' => ts('Contact Name'),
4725 'no_display' => TRUE,
4728 'prefix_id' => array(
4729 'title' => ts('Contact Prefix'),
4731 'first_name' => array(
4732 'title' => ts('First Name'),
4734 'nick_name' => array(
4735 'title' => ts('Nick Name'),
4737 'middle_name' => array(
4738 'title' => ts('Middle Name'),
4740 'last_name' => array(
4741 'title' => ts('Last Name'),
4743 'suffix_id' => array(
4744 'title' => ts('Contact Suffix'),
4746 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4747 'email_greeting_display' => array('title' => ts('Email Greeting')),
4748 'addressee_display' => array('title' => ts('Addressee')),
4749 'contact_type' => array(
4750 'title' => ts('Contact Type'),
4752 'contact_sub_type' => array(
4753 'title' => ts('Contact Subtype'),
4755 'gender_id' => array(
4756 'title' => ts('Gender'),
4758 'birth_date' => array(
4759 'title' => ts('Birth Date'),
4762 'title' => ts('Age'),
4763 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4765 'job_title' => array(
4766 'title' => ts('Contact Job title'),
4768 'organization_name' => array(
4769 'title' => ts('Organization Name'),
4771 'external_identifier' => array(
4772 'title' => ts('Contact identifier from external system'),
4774 'do_not_email' => array(),
4775 'do_not_phone' => array(),
4776 'do_not_mail' => array(),
4777 'do_not_sms' => array(),
4778 'is_opt_out' => array(),
4779 'is_deceased' => array(),
4780 'preferred_language' => array(),
4781 'employer_id' => array(
4782 'title' => ts('Current Employer'),
4788 * Get a standard set of contact filters.
4792 public function getBasicContactFilters() {
4794 'sort_name' => array(
4795 'title' => ts('Contact Name'),
4798 'title' => ts('Contact Source'),
4799 'type' => CRM_Utils_Type
::T_STRING
,
4802 'title' => ts('Contact ID'),
4803 'no_display' => TRUE,
4805 'gender_id' => array(
4806 'title' => ts('Gender'),
4807 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4808 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4810 'birth_date' => array(
4811 'title' => ts('Birth Date'),
4812 'operatorType' => CRM_Report_Form
::OP_DATE
,
4814 'contact_type' => array(
4815 'title' => ts('Contact Type'),
4817 'contact_sub_type' => array(
4818 'title' => ts('Contact Subtype'),
4820 'modified_date' => array(
4821 'title' => ts('Contact Modified'),
4822 'operatorType' => CRM_Report_Form
::OP_DATE
,
4823 'type' => CRM_Utils_Type
::T_DATE
,
4825 'is_deceased' => array(
4826 'title' => ts('Deceased'),
4827 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4830 'do_not_email' => array(
4831 'title' => ts('Do not email'),
4832 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4834 'do_not_phone' => array(
4835 'title' => ts('Do not phone'),
4836 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4838 'do_not_mail' => array(
4839 'title' => ts('Do not mail'),
4840 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4842 'do_not_sms' => array(
4843 'title' => ts('Do not SMS'),
4844 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4846 'is_opt_out' => array(
4847 'title' => ts('Do not bulk email'),
4848 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4850 'preferred_language' => array(
4851 'title' => ts('Preferred Language'),
4853 'is_deleted' => array(
4854 'no_display' => TRUE,
4856 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4862 * Add contact to group.
4864 * @param int $groupID
4866 public function add2group($groupID) {
4867 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4868 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4869 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4870 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4871 $sql = str_replace('WITH ROLLUP', '', $sql);
4872 $dao = CRM_Core_DAO
::executeQuery($sql);
4874 $contact_ids = array();
4875 // Add resulting contacts to group
4876 while ($dao->fetch()) {
4877 if ($dao->addtogroup_contact_id
) {
4878 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4882 if (!empty($contact_ids)) {
4883 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4884 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4887 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4893 * Show charts on print screen.
4895 public static function uploadChartImage() {
4896 // upload strictly for '.png' images
4897 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4898 if (preg_match('/\.png$/', $name)) {
4900 // Get the RAW .png from the input.
4901 $httpRawPostData = file_get_contents("php://input");
4903 // prepare the directory
4904 $config = CRM_Core_Config
::singleton();
4906 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4908 if (!file_exists($defaultPath)) {
4909 mkdir($defaultPath, 0777, TRUE);
4912 // full path to the saved image including filename
4913 $destination = $defaultPath . $name;
4916 $jfh = fopen($destination, 'w') or die("can't open file");
4917 fwrite($jfh, $httpRawPostData);
4919 CRM_Utils_System
::civiExit();
4924 * Apply common settings to entityRef fields.
4926 * @param array $field
4927 * @param string $table
4929 public function setEntityRefDefaults(&$field, $table) {
4930 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4931 $field['attributes'] +
= array(
4932 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4934 'placeholder' => ts('- select -'),
4939 * Add link fields to the row.
4941 * Function adds the _link & _hover fields to the row.
4944 * @param string $baseUrl
4945 * @param string $linkText
4946 * @param string $value
4947 * @param string $fieldName
4948 * @param string $tablePrefix
4949 * @param string $fieldLabel
4953 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4954 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4955 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4956 "reset=1&force=1&{$criteriaQueryParams}&" .
4957 $fieldName . "_op=in&{$fieldName}_value={$value}",
4958 $this->_absoluteUrl
, $this->_id
4960 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4961 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4962 array(1 => $linkText, 2 => $fieldLabel)
4967 * Get label for show results buttons.
4971 public function getResultsLabel() {
4972 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4973 return $showResultsLabel;
4977 * Determine the output mode from the url or input.
4980 * - pdf : Render as pdf
4981 * - csv : Render as csv
4982 * - print : Render in print format
4983 * - save : save the report and display the new report
4984 * - copy : save the report as a new instance and display that.
4985 * - group : go to the add to group screen.
4987 * Potentially chart variations could also be included but the complexity
4988 * is that we might print a bar chart as a pdf.
4990 protected function setOutputMode() {
4991 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4994 CRM_Core_DAO
::$_nullObject,
4996 CRM_Utils_Array
::value('task', $this->_params
)
4998 // if contacts are added to group
4999 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
5000 $this->_outputMode
= 'group';
5002 if (isset($this->_params
['task'])) {
5003 unset($this->_params
['task']);
5008 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5011 * @param $columnName
5013 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5014 // add new column with date value for the datetime field
5015 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5016 CRM_Core_DAO
::executeQuery($tempQuery);
5017 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5018 CRM_Core_DAO
::executeQuery($updateQuery);
5019 $this->_selectClauses
[] = "{$columnName}_date";
5020 $this->_select
.= ", {$columnName}_date";
5021 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
5022 unset($this->_sections
["{$columnName}"]);
5023 $this->assign('sections', $this->_sections
);
5027 * Get an array of the columns that have been selected for display.
5031 public function getSelectColumns() {
5032 $selectColumns = array();
5033 foreach ($this->_columns
as $tableName => $table) {
5034 if (array_key_exists('fields', $table)) {
5035 foreach ($table['fields'] as $fieldName => $field) {
5036 if (!empty($field['required']) ||
5037 !empty($this->_params
['fields'][$fieldName])
5040 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5045 return $selectColumns;
5049 * Add location tables to the query if they are used for filtering.
5051 * This is for when we are running the query separately for filtering and retrieving display fields.
5053 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5054 if ($this->isTableFiltered('civicrm_email')) {
5056 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5057 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5058 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5060 if ($this->isTableFiltered('civicrm_phone')) {
5062 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5063 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5064 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5066 if ($this->isTableFiltered('civicrm_address')) {
5068 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5069 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5070 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5075 * Set the base table for the FROM clause.
5077 * Sets up the from clause, allowing for the possibility it might be a
5078 * temp table pre-filtered by groups if a group filter is in use.
5080 * @param string $baseTable
5081 * @param string $field
5082 * @param null $tableAlias
5084 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5086 $tableAlias = $this->_aliases
[$baseTable];
5088 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
5089 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5090 $this->_from
.= " {$this->_aclFrom} ";
5094 * Join the temp table contacting contacts who are members of the filtered groups.
5096 * If we are using an IN filter we use an inner join, otherwise a left join.
5098 * @param string $baseTable
5099 * @param string $field
5100 * @param string $tableAlias
5102 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5103 if ($this->groupTempTable
) {
5104 if ($this->_params
['gid_op'] == 'in') {
5105 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5106 ON group_temp_table.id = $tableAlias.{$field} ";
5110 LEFT JOIN $this->groupTempTable group_temp_table
5111 ON $tableAlias.{$field} = group_temp_table.id ";
5117 * Get all labels for fields that are used in a group concat.
5119 * @param string $options
5120 * comma separated option values.
5121 * @param string $baoName
5122 * The BAO name for the field.
5123 * @param string $fieldName
5124 * The name of the field for which labels should be retrieved.
5128 public function getLabels($options, $baoName, $fieldName) {
5129 $types = explode(',', $options);
5131 foreach ($types as $value) {
5132 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
5134 return implode(', ', array_filter($labels));
5138 * Add statistics columns.
5140 * If a group by is in play then add columns for the statistics fields.
5142 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5143 * column header field.
5145 * @param array $field
5146 * @param string $tableName
5147 * @param string $fieldName
5148 * @param array $select
5152 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5153 foreach ($field['statistics'] as $stat => $label) {
5154 $alias = "{$tableName}_{$fieldName}_{$stat}";
5155 switch (strtolower($stat)) {
5158 $select[] = "$stat({$field['dbAlias']}) as $alias";
5159 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5160 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5161 $this->_statFields
[$label] = $alias;
5162 $this->_selectAliases
[] = $alias;
5166 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5167 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5168 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5169 $this->_statFields
[$label] = $alias;
5170 $this->_selectAliases
[] = $alias;
5173 case 'count_distinct':
5174 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5175 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5176 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5177 $this->_statFields
[$label] = $alias;
5178 $this->_selectAliases
[] = $alias;
5182 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5183 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5184 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5185 $this->_statFields
[$label] = $alias;
5186 $this->_selectAliases
[] = $alias;
5194 * Add a basic field to the select clause.
5196 * @param string $tableName
5197 * @param string $fieldName
5198 * @param array $field
5199 * @param string $select
5202 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5203 $alias = "{$tableName}_{$fieldName}";
5204 $select[] = "{$field['dbAlias']} as $alias";
5205 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
5206 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
5207 $this->_selectAliases
[] = $alias;
5214 * @param array $table
5215 * @param string $tableName
5220 protected function setTableAlias($table, $tableName) {
5221 if (!isset($table['alias'])) {
5222 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5226 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5229 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5230 return $this->_aliases
[$tableName];
5234 * Function to add columns to reports.
5236 * This is ported from extended reports, which also adds join filters to the options.
5238 * @param string $type
5239 * @param array $options
5240 * - prefix - A string to prepend to the table name
5241 * - prefix_label A string to prepend to the fields
5242 * - fields (bool) - should the fields for this table be made available
5243 * - group_by (bool) - should the group bys for this table be made available.
5244 * - order_by (bool) - should the group bys for this table be made available.
5245 * - filters (bool) - should the filters for this table by made available.
5246 * - fields_defaults (array) array of fields that should be displayed by default.
5247 * - filters_defaults (array) array of fields that should be filtered by default.
5248 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5249 * - join_fields (array) fields available from join (requires additional custom code).
5250 * - group_by_defaults (array) array of group bys that should be applied by default.
5251 * - order_by_defaults (array) array of order bys that should be applied by default.
5252 * - custom_fields (array) array of entity types for custom fields (not usually required).
5253 * - contact_type (string) optional restriction on contact type for some tables.
5254 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5258 protected function getColumns($type, $options = array()) {
5259 $defaultOptions = array(
5261 'prefix_label' => '',
5263 'group_bys' => FALSE,
5264 'order_bys' => TRUE,
5266 'join_filters' => FALSE,
5267 'fields_defaults' => array(),
5268 'filters_defaults' => array(),
5269 'group_bys_defaults' => array(),
5270 'order_bys_defaults' => array(),
5272 $options = array_merge($defaultOptions, $options);
5274 $fn = 'get' . $type . 'Columns';
5275 return $this->$fn($options);
5279 * Get columns for contact table.
5281 * @param array $options
5285 protected function getContactColumns($options = array()) {
5286 $defaultOptions = array(
5287 'custom_fields' => array('Individual', 'Contact', 'Organization'),
5288 'fields_defaults' => array('display_name', 'id'),
5289 'order_bys_defaults' => array('sort_name ASC'),
5290 'contact_type' => NULL,
5293 $options = array_merge($defaultOptions, $options);
5295 $tableAlias = $options['prefix'] . 'contact';
5298 $options['prefix'] . 'display_name' => array(
5299 'name' => 'display_name',
5300 'title' => $options['prefix_label'] . ts('Contact Name'),
5301 'is_fields' => TRUE,
5303 $options['prefix'] . 'sort_name' => array(
5304 'name' => 'sort_name',
5305 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5306 'is_fields' => TRUE,
5307 'is_filters' => TRUE,
5308 'is_order_bys' => TRUE,
5310 $options['prefix'] . 'id' => array(
5312 'title' => $options['prefix_label'] . ts('Contact ID'),
5313 'alter_display' => 'alterContactID',
5314 'type' => CRM_Utils_Type
::T_INT
,
5315 'is_order_bys' => TRUE,
5316 'is_group_bys' => TRUE,
5317 'is_fields' => TRUE,
5318 'is_filters' => TRUE,
5320 $options['prefix'] . 'external_identifier' => array(
5321 'name' => 'external_identifier',
5322 'title' => $options['prefix_label'] . ts('External ID'),
5323 'type' => CRM_Utils_Type
::T_INT
,
5324 'is_fields' => TRUE,
5326 $options['prefix'] . 'contact_type' => array(
5327 'title' => $options['prefix_label'] . ts('Contact Type'),
5328 'name' => 'contact_type',
5329 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5330 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5331 'is_fields' => TRUE,
5332 'is_filters' => TRUE,
5333 'is_group_bys' => TRUE,
5335 $options['prefix'] . 'contact_sub_type' => array(
5336 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5337 'name' => 'contact_sub_type',
5338 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5339 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5340 'is_fields' => TRUE,
5341 'is_filters' => TRUE,
5342 'is_group_bys' => TRUE,
5344 $options['prefix'] . 'is_deleted' => array(
5345 'title' => $options['prefix_label'] . ts('Is deleted'),
5346 'name' => 'is_deleted',
5347 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5348 'is_fields' => FALSE,
5349 'is_filters' => TRUE,
5350 'is_group_bys' => FALSE,
5353 $individualFields = array(
5354 $options['prefix'] . 'first_name' => array(
5355 'name' => 'first_name',
5356 'title' => $options['prefix_label'] . ts('First Name'),
5357 'is_fields' => TRUE,
5358 'is_filters' => TRUE,
5359 'is_order_bys' => TRUE,
5361 $options['prefix'] . 'middle_name' => array(
5362 'name' => 'middle_name',
5363 'title' => $options['prefix_label'] . ts('Middle Name'),
5364 'is_fields' => TRUE,
5366 $options['prefix'] . 'last_name' => array(
5367 'name' => 'last_name',
5368 'title' => $options['prefix_label'] . ts('Last Name'),
5369 'default_order' => 'ASC',
5370 'is_fields' => TRUE,
5372 $options['prefix'] . 'nick_name' => array(
5373 'name' => 'nick_name',
5374 'title' => $options['prefix_label'] . ts('Nick Name'),
5375 'is_fields' => TRUE,
5377 $options['prefix'] . 'prefix_id' => array(
5378 'name' => 'prefix_id',
5379 'title' => $options['prefix_label'] . ts('Prefix'),
5380 'options' => CRM_Contact_BAO_Contact
::buildOptions('prefix_id'),
5381 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5382 'is_fields' => TRUE,
5383 'is_filters' => TRUE,
5385 $options['prefix'] . 'suffix_id' => array(
5386 'name' => 'suffix_id',
5387 'title' => $options['prefix_label'] . ts('Suffix'),
5388 'options' => CRM_Contact_BAO_Contact
::buildOptions('suffix_id'),
5389 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5390 'is_fields' => TRUE,
5391 'is_filters' => TRUE,
5393 $options['prefix'] . 'gender_id' => array(
5394 'name' => 'gender_id',
5395 'title' => $options['prefix_label'] . ts('Gender'),
5396 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5397 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5398 'is_fields' => TRUE,
5399 'is_filters' => TRUE,
5401 'birth_date' => array(
5402 'title' => $options['prefix_label'] . ts('Birth Date'),
5403 'operatorType' => CRM_Report_Form
::OP_DATE
,
5404 'type' => CRM_Utils_Type
::T_DATE
,
5405 'is_fields' => TRUE,
5406 'is_filters' => TRUE,
5409 'title' => $options['prefix_label'] . ts('Age'),
5410 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5411 'type' => CRM_Utils_Type
::T_INT
,
5412 'is_fields' => TRUE,
5414 $options['prefix'] . 'is_deceased' => array(
5415 'title' => $options['prefix_label'] . ts('Is deceased'),
5416 'name' => 'is_deceased',
5417 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5418 'is_fields' => FALSE,
5419 'is_filters' => TRUE,
5420 'is_group_bys' => FALSE,
5423 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5424 $spec = array_merge($spec, $individualFields);
5427 if (!empty($options['custom_fields'])) {
5428 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = array(
5429 'extends' => $options['custom_fields'],
5430 'title' => $options['prefix_label'],
5431 'filters' => $options['filters'],
5432 'prefix' => $options['prefix'],
5433 'prefix_label' => $options['prefix_label'],
5437 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5441 * Get address columns to add to array.
5443 * @param array $options
5444 * - prefix Prefix to add to table (in case of more than one instance of the table)
5445 * - prefix_label Label to give columns from this address table instance
5446 * - group_bys enable these fields for group by - default false
5447 * - order_bys enable these fields for order by
5448 * - filters enable these fields for filtering
5450 * @return array address columns definition
5452 protected function getAddressColumns($options = array()) {
5453 $defaultOptions = array(
5455 'prefix_label' => '',
5457 'group_bys' => FALSE,
5458 'order_bys' => TRUE,
5460 'join_filters' => FALSE,
5461 'fields_defaults' => array(),
5462 'filters_defaults' => array(),
5463 'group_bys_defaults' => array(),
5464 'order_bys_defaults' => array(),
5467 $options = array_merge($defaultOptions, $options);
5468 $defaults = $this->getDefaultsFromOptions($options);
5469 $tableAlias = $options['prefix'] . 'address';
5472 $options['prefix'] . 'name' => array(
5473 'title' => ts($options['prefix_label'] . 'Address Name'),
5475 'is_fields' => TRUE,
5477 $options['prefix'] . 'street_number' => array(
5478 'name' => 'street_number',
5479 'title' => ts($options['prefix_label'] . 'Street Number'),
5481 'is_fields' => TRUE,
5483 $options['prefix'] . 'odd_street_number' => array(
5484 'title' => ts('Odd / Even Street Number'),
5485 'name' => 'odd_street_number',
5486 'type' => CRM_Utils_Type
::T_INT
,
5487 'no_display' => TRUE,
5489 'dbAlias' => '(address_civireport.street_number % 2)',
5490 'is_fields' => TRUE,
5491 'is_order_bys' => TRUE,
5493 $options['prefix'] . 'street_name' => array(
5494 'name' => 'street_name',
5495 'title' => ts($options['prefix_label'] . 'Street Name'),
5497 'is_fields' => TRUE,
5498 'is_filters' => TRUE,
5499 'operator' => 'like',
5500 'is_order_bys' => TRUE,
5502 $options['prefix'] . 'street_address' => array(
5503 'title' => ts($options['prefix_label'] . 'Street Address'),
5504 'name' => 'street_address',
5505 'is_fields' => TRUE,
5506 'is_filters' => TRUE,
5507 'is_group_bys' => TRUE,
5509 $options['prefix'] . 'supplemental_address_1' => array(
5510 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 1'),
5511 'name' => 'supplemental_address_1',
5512 'is_fields' => TRUE,
5514 $options['prefix'] . 'supplemental_address_2' => array(
5515 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 2'),
5516 'name' => 'supplemental_address_2',
5517 'is_fields' => TRUE,
5519 $options['prefix'] . 'supplemental_address_3' => array(
5520 'title' => ts($options['prefix_label'] . 'Supplementary Address Field 3'),
5521 'name' => 'supplemental_address_3',
5522 'is_fields' => TRUE,
5524 $options['prefix'] . 'street_number' => array(
5525 'name' => 'street_number',
5526 'title' => ts($options['prefix_label'] . 'Street Number'),
5528 'is_order_bys' => TRUE,
5529 'is_filters' => TRUE,
5530 'is_fields' => TRUE,
5532 $options['prefix'] . 'street_unit' => array(
5533 'name' => 'street_unit',
5534 'title' => ts($options['prefix_label'] . 'Street Unit'),
5536 'is_fields' => TRUE,
5538 $options['prefix'] . 'city' => array(
5539 'title' => ts($options['prefix_label'] . 'City'),
5541 'operator' => 'like',
5542 'is_fields' => TRUE,
5543 'is_filters' => TRUE,
5544 'is_group_bys' => TRUE,
5545 'is_order_bys' => TRUE,
5547 $options['prefix'] . 'postal_code' => array(
5548 'title' => ts($options['prefix_label'] . 'Postal Code'),
5549 'name' => 'postal_code',
5551 'is_fields' => TRUE,
5552 'is_filters' => TRUE,
5553 'is_group_bys' => TRUE,
5554 'is_order_bys' => TRUE,
5556 $options['prefix'] . 'postal_code_suffix' => array(
5557 'title' => ts($options['prefix_label'] . 'Postal Code Suffix'),
5558 'name' => 'postal_code',
5560 'is_fields' => TRUE,
5561 'is_filters' => TRUE,
5562 'is_group_bys' => TRUE,
5563 'is_order_bys' => TRUE,
5565 $options['prefix'] . 'county_id' => array(
5566 'title' => ts($options['prefix_label'] . 'County'),
5567 'alter_display' => 'alterCountyID',
5568 'name' => 'county_id',
5569 'type' => CRM_Utils_Type
::T_INT
,
5570 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5571 'options' => CRM_Core_PseudoConstant
::county(),
5572 'is_fields' => TRUE,
5573 'is_filters' => TRUE,
5574 'is_group_bys' => TRUE,
5576 $options['prefix'] . 'state_province_id' => array(
5577 'title' => ts($options['prefix_label'] . 'State/Province'),
5578 'alter_display' => 'alterStateProvinceID',
5579 'name' => 'state_province_id',
5580 'type' => CRM_Utils_Type
::T_INT
,
5581 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5582 'options' => CRM_Core_PseudoConstant
::stateProvince(),
5583 'is_fields' => TRUE,
5584 'is_filters' => TRUE,
5585 'is_group_bys' => TRUE,
5587 $options['prefix'] . 'country_id' => array(
5588 'title' => ts($options['prefix_label'] . 'Country'),
5589 'alter_display' => 'alterCountryID',
5590 'name' => 'country_id',
5591 'is_fields' => TRUE,
5592 'is_filters' => TRUE,
5593 'is_group_bys' => TRUE,
5594 'type' => CRM_Utils_Type
::T_INT
,
5595 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5596 'options' => CRM_Core_PseudoConstant
::country(),
5598 $options['prefix'] . 'location_type_id' => array(
5599 'name' => 'is_primary',
5600 'title' => ts($options['prefix_label'] . 'Location Type'),
5601 'type' => CRM_Utils_Type
::T_INT
,
5602 'is_fields' => TRUE,
5603 'alter_display' => 'alterLocationTypeID',
5605 $options['prefix'] . 'id' => array(
5606 'title' => ts($options['prefix_label'] . 'ID'),
5608 'is_fields' => TRUE,
5610 $options['prefix'] . 'is_primary' => array(
5611 'name' => 'is_primary',
5612 'title' => ts($options['prefix_label'] . 'Primary Address?'),
5613 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5614 'is_fields' => TRUE,
5617 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5621 * Build the columns.
5623 * The normal report class needs you to remember to do a few things that are often erratic
5625 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5626 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5627 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5628 * means any saved filters / fields on saved report instances. This will mean that matching names from
5629 * different tables may be ambigious, but it will smooth any code transition.
5630 * - note that it assumes the value being passed in is the actual table field name
5632 * 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
5633 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5635 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5636 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5637 * the core classes can start to move towards that.
5639 * @param array $specs
5640 * @param string $tableName
5641 * @param string $daoName
5642 * @param string $tableAlias
5643 * @param array $defaults
5644 * @param array $options
5648 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = array(), $options = array()) {
5650 $tableAlias = str_replace('civicrm_', '', $tableName);
5652 $types = array('filters', 'group_bys', 'order_bys', 'join_filters');
5653 $columns = array($tableName => array_fill_keys($types, array()));
5654 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5655 $columns[$tableName]['dao'] = $daoName;
5656 $columns[$tableName]['alias'] = $tableAlias;
5658 foreach ($specs as $specName => $spec) {
5659 if (empty($spec['name'])) {
5660 $spec['name'] = $specName;
5663 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5664 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5665 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5666 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5667 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5670 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5671 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5674 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5675 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5678 foreach ($types as $type) {
5679 if ($options[$type] && !empty($spec['is_' . $type])) {
5680 $columns[$tableName][$type][$fieldAlias] = $spec;
5681 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5682 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5691 * Store group bys into array - so we can check elsewhere what is grouped.
5693 protected function storeGroupByArray() {
5695 if (!CRM_Utils_Array
::value('group_bys', $this->_params
)
5696 ||
!is_array($this->_params
['group_bys'])) {
5697 $this->_params
['group_bys'] = [];
5700 foreach ($this->_columns
as $tableName => $table) {
5701 $table = $this->_columns
[$tableName];
5702 if (array_key_exists('group_bys', $table)) {
5703 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5704 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5705 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5706 if (!empty($field['chart'])) {
5707 $this->assign('chartSupported', TRUE);
5710 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5711 !empty($this->_params
['group_bys_freq'][$fieldName])
5714 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5716 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5719 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
5722 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_{$this->_params['group_bys_freq'][$fieldName]} FROM {$field['dbAlias']})";
5727 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5728 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5743 protected function getDefaultsFromOptions($options) {
5745 'fields_defaults' => $options['fields_defaults'],
5746 'filters_defaults' => $options['filters_defaults'],
5747 'group_bys_defaults' => $options['group_bys_defaults'],
5748 'order_bys_defaults' => $options['order_bys_defaults'],
5754 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5756 * Full group by mode dictates that a field must either be in the group by function or
5757 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5760 * @param string $tableName
5761 * @param string $fieldName
5762 * @param string $field
5765 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5766 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5767 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5768 $label = CRM_Utils_Array
::value('title', $field);
5769 $alias = "{$tableName}_{$fieldName}";
5770 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5771 $this->_selectAliases
[] = $alias;
5772 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5773 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5775 return "({$field['dbAlias']}) as $alias";
5781 * Generate clause for the selected filter.
5783 * @param array $field
5784 * Field specification
5785 * @param string $fieldName
5789 * Relevant where clause.
5791 protected function generateFilterClause($field, $fieldName) {
5792 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
5793 if (CRM_Utils_Array
::value('operatorType', $field) ==
5794 CRM_Report_Form
::OP_MONTH
5796 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5797 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
5798 if (is_array($value) && !empty($value)) {
5799 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
5804 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
5805 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
5806 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
5807 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
5808 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
5809 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
5813 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
5815 return $this->whereClause($field,
5817 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
5818 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
5819 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)