3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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.
493 public function __construct() {
494 parent
::__construct();
496 $this->addClass('crm-report-form');
498 if ($this->_tagFilter
) {
499 $this->buildTagFilter();
501 if ($this->_exposeContactID
) {
502 if (array_key_exists('civicrm_contact', $this->_columns
)) {
503 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
505 'title' => ts('Contact ID'),
511 if ($this->_groupFilter
) {
512 $this->buildGroupFilter();
515 // Get all custom groups
516 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
518 // Get the custom groupIds for which the user has VIEW permission
519 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
520 // and addCustomDataToColumns() will allow access to all custom groups.
521 $permCustomGroupIds = array();
522 if (!CRM_Core_Permission
::check('access all custom data')) {
523 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
524 // do not allow custom data for reports if user doesn't have
525 // permission to access custom data.
526 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
527 $this->_customGroupExtends
= array();
531 // merge custom data columns to _columns list, if any
532 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
534 // add / modify display columns, filters ..etc
535 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
537 //assign currencyColumn variable to tpl
538 $this->assign('currencyColumn', $this->_currencyColumn
);
542 * Shared pre-process function.
544 * If overriding preProcess function this should still be called.
548 public function preProcessCommon() {
549 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
551 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
553 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
555 $this->assign('section', $this->_section
);
556 CRM_Core_Region
::instance('page-header')->add(array(
557 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
559 if (!$this->noController
) {
560 $this->setID($this->get('instanceId'));
563 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
565 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
569 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
570 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
571 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
575 $this->assign('instanceId', $this->_id
);
576 $params = array('id' => $this->_id
);
577 $this->_instanceValues
= array();
578 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
580 $this->_instanceValues
582 if (empty($this->_instanceValues
)) {
583 CRM_Core_Error
::fatal("Report could not be loaded.");
585 $this->_title
= $this->_instanceValues
['title'];
586 if (!empty($this->_instanceValues
['permission']) &&
587 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
588 CRM_Core_Permission
::check('administer Reports')
591 CRM_Utils_System
::permissionDenied();
592 CRM_Utils_System
::civiExit();
595 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
597 $this->_formValues
= unserialize($formValues);
600 $this->_formValues
= NULL;
603 $this->setOutputMode();
605 if ($this->_outputMode
== 'copy') {
606 $this->_createNew
= TRUE;
607 $this->_params
= $this->_formValues
;
608 $this->_params
['view_mode'] = 'criteria';
609 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
610 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
611 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
613 // Do not pass go. Do not collect another chance to re-run the same query.
614 CRM_Report_Form_Instance
::postProcess($this);
617 // lets always do a force if reset is found in the url.
618 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
619 // in the comment line above these 2.
620 if (!empty($_REQUEST['reset'])
621 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
626 $this->assign('mode', 'instance');
628 elseif (!$this->noController
) {
629 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
630 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
631 if (($instanceCount > 0) && $optionValueID) {
632 $this->assign('instanceUrl',
633 CRM_Utils_System
::url('civicrm/report/list',
634 "reset=1&ovid=$optionValueID"
638 if ($optionValueID) {
639 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
643 $this->assign('mode', 'template');
646 // lets display the Report Settings section
647 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
649 // Do not display Report Settings section if administer Reports permission is absent OR
650 // if report instance is reserved and administer reserved reports absent
651 if (!CRM_Core_Permission
::check('administer Reports') ||
652 ($this->_instanceValues
['is_reserved'] &&
653 !CRM_Core_Permission
::check('administer reserved reports'))
655 $this->_instanceForm
= FALSE;
658 $this->assign('criteriaForm', FALSE);
659 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
660 if (CRM_Core_Permission
::check('administer Reports') ||
661 CRM_Core_Permission
::check('access Report Criteria')
663 if (!$this->_instanceValues
['is_reserved'] ||
664 CRM_Core_Permission
::check('administer reserved reports')
666 $this->assign('criteriaForm', TRUE);
667 $this->_criteriaForm
= TRUE;
671 // Special permissions check for private instance if it's not the current contact instance
673 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
674 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
675 if (!CRM_Core_Permission
::check('access all private reports')) {
676 $this->_instanceForm
= FALSE;
677 $this->assign('criteriaForm', FALSE);
681 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
682 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
683 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
684 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
690 public function addBreadCrumb() {
694 'title' => ts('Report Templates'),
695 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
699 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
703 * Pre process function.
705 * Called prior to build form.
707 public function preProcess() {
708 $this->preProcessCommon();
711 $this->addBreadCrumb();
714 foreach ($this->_columns
as $tableName => $table) {
715 $this->setTableAlias($table, $tableName);
717 $expFields = array();
718 // higher preference to bao object
719 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
722 if (method_exists($daoOrBaoName, 'exportableFields')) {
723 $expFields = $daoOrBaoName::exportableFields();
726 $expFields = $daoOrBaoName::export();
730 $doNotCopy = array('required', 'default');
732 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
733 foreach ($fieldGroups as $fieldGrp) {
734 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
735 foreach ($table[$fieldGrp] as $fieldName => $field) {
736 // $name is the field name used to reference the BAO/DAO export fields array
737 $name = isset($field['name']) ?
$field['name'] : $fieldName;
739 // Sometimes the field name key in the BAO/DAO export fields array is
740 // different from the actual database field name.
741 // Unset $field['name'] so that actual database field name can be obtained
742 // from the BAO/DAO export fields array.
743 unset($field['name']);
745 if (array_key_exists($name, $expFields)) {
746 foreach ($doNotCopy as $dnc) {
747 // unset the values we don't want to be copied.
748 unset($expFields[$name][$dnc]);
751 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
754 foreach ($expFields[$name] as $property => $val) {
755 if (!array_key_exists($property, $field)) {
756 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
763 if (!empty($field['no_repeat'])) {
764 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
766 if (!empty($field['no_display'])) {
767 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
770 // set alias = table-name, unless already set
771 $alias = isset($field['alias']) ?
$field['alias'] : (
772 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
774 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
776 // set name = fieldName, unless already set
777 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
778 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
781 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'])) {
782 $this->_columns
[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
785 // set dbAlias = alias.name, unless already set
786 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
787 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
789 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
792 // a few auto fills for filters
793 if ($fieldGrp == 'filters') {
794 // fill operator types
795 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
796 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
797 case CRM_Utils_Type
::T_MONEY
:
798 case CRM_Utils_Type
::T_FLOAT
:
799 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
802 case CRM_Utils_Type
::T_INT
:
803 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
806 case CRM_Utils_Type
::T_DATE
:
807 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
810 case CRM_Utils_Type
::T_BOOLEAN
:
811 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
812 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
813 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
824 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
826 // with multiple options operator-type is generally multi-select
827 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
828 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
830 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
837 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
838 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
844 // copy filters to a separate handy variable
845 if (array_key_exists('filters', $table)) {
846 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
849 if (array_key_exists('group_bys', $table)) {
850 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
853 if (array_key_exists('fields', $table)) {
854 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
859 $this->setDefaultValues(FALSE);
862 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
863 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
864 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
865 CRM_Report_Utils_Get
::processChart($this->_defaults
);
868 $this->_formValues
= $this->_defaults
;
869 $this->postProcess();
874 * Set default values.
876 * @param bool $freeze
880 public function setDefaultValues($freeze = TRUE) {
881 $freezeGroup = array();
883 // FIXME: generalizing form field naming conventions would reduce
884 // Lots of lines below.
885 foreach ($this->_columns
as $tableName => $table) {
886 if (array_key_exists('fields', $table)) {
887 foreach ($table['fields'] as $fieldName => $field) {
888 if (empty($field['no_display'])) {
889 if (!empty($field['required'])) {
891 $this->_defaults
['fields'][$fieldName] = 1;
894 // find element object, so that we could use quickform's freeze method
895 // for required elements
896 $obj = $this->getElementFromGroup("fields", $fieldName);
898 $freezeGroup[] = $obj;
902 elseif (isset($field['default'])) {
903 $this->_defaults
['fields'][$fieldName] = $field['default'];
909 if (array_key_exists('group_bys', $table)) {
910 foreach ($table['group_bys'] as $fieldName => $field) {
911 if (isset($field['default'])) {
912 if (!empty($field['frequency'])) {
913 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
915 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
919 if (array_key_exists('filters', $table)) {
920 foreach ($table['filters'] as $fieldName => $field) {
921 if (isset($field['default'])) {
922 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
924 if (is_array($field['default'])) {
925 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
926 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
927 $this->_defaults
["{$fieldName}_relative"] = 0;
930 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
934 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
935 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
936 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
938 $this->_defaults
["{$fieldName}_value"] = $field['default'];
941 //assign default value as "in" for multiselect
942 //operator, To freeze the select element
943 if (CRM_Utils_Array
::value('operatorType', $field) ==
944 CRM_Report_Form
::OP_MULTISELECT
946 $this->_defaults
["{$fieldName}_op"] = 'in';
948 if (CRM_Utils_Array
::value('operatorType', $field) ==
949 CRM_Report_Form
::OP_ENTITYREF
951 $this->_defaults
["{$fieldName}_op"] = 'in';
953 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
954 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
956 $this->_defaults
["{$fieldName}_op"] = 'mhas';
958 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
959 $this->_defaults
["{$fieldName}_op"] = $op;
965 empty($this->_formValues
['order_bys']) &&
966 (array_key_exists('order_bys', $table) &&
967 is_array($table['order_bys']))
969 if (!array_key_exists('order_bys', $this->_defaults
)) {
970 $this->_defaults
['order_bys'] = array();
972 foreach ($table['order_bys'] as $fieldName => $field) {
973 if (!empty($field['default']) ||
!empty($field['default_order']) ||
974 CRM_Utils_Array
::value('default_is_section', $field) ||
975 !empty($field['default_weight'])
978 'column' => $fieldName,
979 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
980 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
983 if (!empty($field['default_weight'])) {
984 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
987 array_unshift($this->_defaults
['order_bys'], $order_by);
993 foreach ($this->_options
as $fieldName => $field) {
994 if (isset($field['default'])) {
995 $this->_defaults
['options'][$fieldName] = $field['default'];
1000 if (!empty($this->_submitValues
)) {
1001 $this->preProcessOrderBy($this->_submitValues
);
1004 $this->preProcessOrderBy($this->_defaults
);
1007 // lets finish freezing task here itself
1008 if (!empty($freezeGroup)) {
1009 foreach ($freezeGroup as $elem) {
1014 if ($this->_formValues
) {
1015 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1018 if ($this->_instanceValues
) {
1019 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1022 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1024 return $this->_defaults
;
1028 * Get element from group.
1030 * @param string $group
1031 * @param string $grpFieldName
1035 public function getElementFromGroup($group, $grpFieldName) {
1036 $eleObj = $this->getElement($group);
1037 foreach ($eleObj->_elements
as $index => $obj) {
1038 if ($grpFieldName == $obj->_attributes
['name']) {
1046 * Setter for $_params.
1048 * @param array $params
1050 public function setParams($params) {
1051 $this->_params
= $params;
1057 * @param int $instanceID
1059 public function setID($instanceID) {
1060 $this->_id
= $instanceID;
1064 * Setter for $_force.
1066 * @param bool $isForce
1068 public function setForce($isForce) {
1069 $this->_force
= $isForce;
1073 * Setter for $_limitValue.
1075 * @param int $_limitValue
1077 public function setLimitValue($_limitValue) {
1078 $this->_limitValue
= $_limitValue;
1082 * Setter for $_offsetValue.
1084 * @param int $_offsetValue
1086 public function setOffsetValue($_offsetValue) {
1087 $this->_offsetValue
= $_offsetValue;
1091 * Setter for $addPaging.
1093 * @param bool $value
1095 public function setAddPaging($value) {
1096 $this->addPaging
= $value;
1100 * Getter for $_defaultValues.
1104 public function getDefaultValues() {
1105 return $this->_defaults
;
1109 * Add columns to report.
1111 public function addColumns() {
1114 foreach ($this->_columns
as $tableName => $table) {
1115 if (array_key_exists('fields', $table)) {
1116 foreach ($table['fields'] as $fieldName => $field) {
1118 if (empty($field['no_display'])) {
1119 foreach (array('table', 'field') as $var) {
1120 if (!empty($
{$var}['grouping'])) {
1121 if (!is_array($
{$var}['grouping'])) {
1122 $tableName = $
{$var}['grouping'];
1125 $tableName = array_keys($
{$var}['grouping']);
1126 $tableName = $tableName[0];
1127 $groupTitle = array_values($
{$var}['grouping']);
1128 $groupTitle = $groupTitle[0];
1133 if (!$groupTitle && isset($table['group_title'])) {
1134 $groupTitle = $table['group_title'];
1135 // Having a group_title is secret code for being a custom group
1136 // which cryptically translates to needing an accordion.
1137 // here we make that explicit.
1138 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1141 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1142 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1143 $colGroups[$tableName]['group_title'] = $groupTitle;
1145 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1151 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1152 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1154 if (!empty($colGroups)) {
1155 $this->tabs
['FieldSelection'] = array(
1156 'title' => ts('Columns'),
1157 'tpl' => 'FieldSelection',
1158 'div_label' => 'col-groups',
1161 // Note this assignment is only really required in buildForm. It is being 'over-called'
1162 // to reduce risk of being missed due to overridden functions.
1163 $this->assign('tabs', $this->tabs
);
1166 $this->assign('colGroups', $colGroups);
1170 * Add filters to report.
1172 public function addFilters() {
1173 $filters = $filterGroups = array();
1176 foreach ($this->_filters
as $table => $attributes) {
1177 if (isset($this->_columns
[$table]['group_title'])) {
1178 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1179 // which magically means to 'display in an accordian'
1180 // here we make this explicit.
1181 $filterGroups[$table] = array(
1182 'group_title' => $this->_columns
[$table]['group_title'],
1183 'use_accordian_for_field_selection' => TRUE,
1187 foreach ($attributes as $fieldName => $field) {
1188 // get ready with option value pair
1189 // @ 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
1191 $operations = $this->getOperationPair(
1192 CRM_Utils_Array
::value('operatorType', $field),
1195 $filters[$table][$fieldName] = $field;
1197 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1198 case CRM_Report_Form
::OP_MONTH
:
1199 if (!array_key_exists('options', $field) ||
1200 !is_array($field['options']) ||
empty($field['options'])
1202 // If there's no option list for this filter, define one.
1203 $field['options'] = array(
1205 2 => ts('February'),
1212 9 => ts('September'),
1213 10 => ts('October'),
1214 11 => ts('November'),
1215 12 => ts('December'),
1217 // Add this option list to this column _columns. This is
1218 // required so that filter statistics show properly.
1219 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1221 case CRM_Report_Form
::OP_MULTISELECT
:
1222 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1223 // assume a multi-select field
1224 if (!empty($field['options']) ||
1225 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1227 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1228 if (count($operations) <= 1) {
1231 if ($fieldName == 'state_province_id' ||
1232 $fieldName == 'county_id'
1234 $this->addChainSelect($fieldName . '_value', array(
1241 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1242 'style' => 'min-width:250px',
1243 'class' => 'crm-select2 huge',
1245 'placeholder' => ts('- select -'),
1251 case CRM_Report_Form
::OP_SELECT
:
1252 // assume a select field
1253 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1254 if (!empty($field['options'])) {
1255 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1259 case CRM_Report_Form
::OP_ENTITYREF
:
1260 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1261 $this->setEntityRefDefaults($field, $table);
1262 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1265 case CRM_Report_Form
::OP_DATE
:
1266 // build datetime fields
1267 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1271 case CRM_Report_Form
::OP_DATETIME
:
1272 // build datetime fields
1273 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1277 case CRM_Report_Form
::OP_INT
:
1278 case CRM_Report_Form
::OP_FLOAT
:
1279 // and a min value input box
1280 $this->add('text', "{$fieldName}_min", ts('Min'));
1281 // and a max value input box
1282 $this->add('text', "{$fieldName}_max", ts('Max'));
1284 // default type is string
1285 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1286 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1288 // we need text box for value input
1289 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1294 if (!empty($filters)) {
1295 $this->tabs
['Filters'] = array(
1296 'title' => ts('Filters'),
1298 'div_label' => 'set-filters',
1301 $this->assign('filters', $filters);
1302 $this->assign('filterGroups', $filterGroups);
1306 * Function to assign the tabs to the template in the correct order.
1308 * We want the tabs to wind up in this order (if not overridden).
1316 protected function assignTabs() {
1324 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1325 $order = array_merge($order, $this->tabs
);
1326 $this->assign('tabs', $order);
1330 * The intent is to add a tab for developers to view the sql.
1332 * Currently using dpm.
1334 * @param string $sql
1336 public function addToDeveloperTab($sql) {
1337 if (!CRM_Core_Permission
::check('view report sql')) {
1340 $this->tabs
['Developer'] = array(
1341 'title' => ts('Developer'),
1342 'tpl' => 'Developer',
1343 'div_label' => 'set-developer',
1346 $this->assignTabs();
1347 $this->sqlArray
[] = $sql;
1348 foreach ($this->sqlArray
as $sql) {
1349 foreach (array('LEFT JOIN') as $term) {
1350 $sql = str_replace($term, '<br>  ' . $term, $sql);
1352 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1353 $sql = str_replace($term, '<br><br>' . $term, $sql);
1355 $this->sqlFormattedArray
[] = $sql;
1356 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1361 * Add options defined in $this->_options to the report.
1363 public function addOptions() {
1364 if (!empty($this->_options
)) {
1365 // FIXME: For now lets build all elements as checkboxes.
1366 // Once we clear with the format we can build elements based on type
1368 foreach ($this->_options
as $fieldName => $field) {
1371 if ($field['type'] == 'select') {
1372 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1374 elseif ($field['type'] == 'checkbox') {
1375 $options[$field['title']] = $fieldName;
1376 $this->addCheckBox($fieldName, NULL,
1378 NULL, NULL, NULL, $this->_fourColumnAttribute
1383 if (!empty($this->_options
) &&
1385 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1387 $this->tabs
['ReportOptions'] = array(
1388 'title' => ts('Display Options'),
1389 'tpl' => 'ReportOptions',
1390 'div_label' => 'other-options',
1393 $this->assign('otherOptions', $this->_options
);
1397 * Add chart options to the report.
1399 public function addChartOptions() {
1400 if (!empty($this->_charts
)) {
1401 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1402 $this->assign('charts', $this->_charts
);
1403 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1408 * Add group by options to the report.
1410 public function addGroupBys() {
1411 $options = $freqElements = array();
1413 foreach ($this->_columns
as $tableName => $table) {
1414 if (array_key_exists('group_bys', $table)) {
1415 foreach ($table['group_bys'] as $fieldName => $field) {
1416 if (!empty($field) && empty($field['no_display'])) {
1417 $options[$field['title']] = $fieldName;
1418 if (!empty($field['frequency'])) {
1419 $freqElements[$field['title']] = $fieldName;
1425 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1426 NULL, NULL, NULL, $this->_fourColumnAttribute
1428 $this->assign('groupByElements', $options);
1429 if (!empty($options)) {
1430 $this->tabs
['GroupBy'] = array(
1431 'title' => ts('Grouping'),
1433 'div_label' => 'group-by-elements',
1437 foreach ($freqElements as $name) {
1438 $this->addElement('select', "group_bys_freq[$name]",
1439 ts('Frequency'), $this->_groupByDateFreq
1445 * Add data for order by tab.
1447 public function addOrderBys() {
1449 foreach ($this->_columns
as $tableName => $table) {
1451 // Report developer may define any column to order by; include these as order-by options.
1452 if (array_key_exists('order_bys', $table)) {
1453 foreach ($table['order_bys'] as $fieldName => $field) {
1454 if (!empty($field)) {
1455 $options[$fieldName] = $field['title'];
1460 // Add searchable custom fields as order-by options, if so requested
1461 // (These are already indexed, so allowing to order on them is cheap.)
1463 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1464 array_key_exists('extends', $table) && !empty($table['extends'])
1466 foreach ($table['fields'] as $fieldName => $field) {
1467 if (empty($field['no_display'])) {
1468 $options[$fieldName] = $field['title'];
1476 $this->assign('orderByOptions', $options);
1477 if (!empty($options)) {
1478 $this->tabs
['OrderBy'] = array(
1479 'title' => ts('Sorting'),
1481 'div_label' => 'order-by-elements',
1485 if (!empty($options)) {
1487 '-' => ' - none - ',
1489 for ($i = 1; $i <= 5; $i++
) {
1490 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1491 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1492 'ASC' => ts('Ascending'),
1493 'DESC' => ts('Descending'),
1495 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1496 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1502 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1504 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1505 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1508 public function buildInstanceAndButtons() {
1509 CRM_Report_Form_Instance
::buildForm($this);
1510 $this->_actionButtonName
= $this->getButtonName('submit');
1511 $this->addTaskMenu($this->getActions($this->_id
));
1513 $this->assign('instanceForm', $this->_instanceForm
);
1515 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1516 $permission = CRM_Core_Permission
::getPermission();
1517 if ($permission == CRM_Core_Permission
::EDIT
&&
1518 $this->_add2groupSupported
1520 $this->addElement('select', 'groups', ts('Group'),
1521 array('' => ts('Add Contacts to Group')) +
1522 CRM_Core_PseudoConstant
::nestedGroup(),
1523 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1525 $this->assign('group', TRUE);
1528 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1530 $this->addChartOptions();
1531 $showResultsLabel = $this->getResultsLabel();
1532 $this->addButtons(array(
1535 'name' => $showResultsLabel,
1536 'isDefault' => TRUE,
1543 * Has this form been submitted already?
1547 public function resultsDisplayed() {
1548 $buttonName = $this->controller
->getButtonName();
1549 return ($buttonName ||
$this->_outputMode
);
1553 * Get the actions for this report instance.
1555 * @param int $instanceId
1559 protected function getActions($instanceId) {
1560 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1561 if (empty($instanceId)) {
1562 $actions['report_instance.save'] = array(
1563 'title' => ts('Create Report'),
1565 'is_confirm' => TRUE,
1566 'confirm_title' => ts('Create Report'),
1567 'confirm_refresh_fields' => json_encode(array(
1568 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1569 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1575 if (!$this->_csvSupported
) {
1576 unset($actions['report_instance.csv']);
1583 * Main build form function.
1585 public function buildQuickForm() {
1586 $this->addColumns();
1588 $this->addFilters();
1590 $this->addOptions();
1592 $this->addGroupBys();
1594 $this->addOrderBys();
1596 $this->buildInstanceAndButtons();
1598 // Add form rule for report.
1599 if (is_callable(array(
1603 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1605 $this->assignTabs();
1609 * A form rule function for custom data.
1611 * The rule ensures that fields selected in group_by if any) should only be the ones
1612 * present in display/select fields criteria;
1613 * note: works if and only if any custom field selected in group_by.
1615 * @param array $fields
1616 * @param array $ignoreFields
1620 public function customDataFormRule($fields, $ignoreFields = array()) {
1622 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1623 !empty($fields['group_bys'])
1625 foreach ($this->_columns
as $tableName => $table) {
1626 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1627 substr($tableName, 0, 12) == 'custom_value') &&
1628 !empty($this->_columns
[$tableName]['fields'])
1630 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1631 if (array_key_exists($fieldName, $fields['group_bys']) &&
1632 !array_key_exists($fieldName, $fields['fields'])
1634 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1636 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1637 foreach ($fields['fields'] as $fld => $val) {
1638 if (!array_key_exists($fld, $fields['group_bys']) &&
1639 !in_array($fld, $ignoreFields)
1641 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1653 * Get operators to display on form.
1655 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1657 * @param string $type
1658 * @param string $fieldName
1662 public function getOperationPair($type = "string", $fieldName = NULL) {
1663 // FIXME: At some point we should move these key-val pairs
1664 // to option_group and option_value table.
1666 case CRM_Report_Form
::OP_INT
:
1667 case CRM_Report_Form
::OP_FLOAT
:
1670 'lte' => ts('Is less than or equal to'),
1671 'gte' => ts('Is greater than or equal to'),
1672 'bw' => ts('Is between'),
1673 'eq' => ts('Is equal to'),
1674 'lt' => ts('Is less than'),
1675 'gt' => ts('Is greater than'),
1676 'neq' => ts('Is not equal to'),
1677 'nbw' => ts('Is not between'),
1678 'nll' => ts('Is empty (Null)'),
1679 'nnll' => ts('Is not empty (Null)'),
1683 case CRM_Report_Form
::OP_SELECT
:
1685 'eq' => ts('Is equal to'),
1689 case CRM_Report_Form
::OP_MONTH
:
1690 case CRM_Report_Form
::OP_MULTISELECT
:
1691 case CRM_Report_Form
::OP_ENTITYREF
:
1694 'in' => ts('Is one of'),
1695 'notin' => ts('Is not one of'),
1699 case CRM_Report_Form
::OP_DATE
:
1702 'nll' => ts('Is empty (Null)'),
1703 'nnll' => ts('Is not empty (Null)'),
1707 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1708 // use this operator for the values, concatenated with separator. For e.g if
1709 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1711 'mhas' => ts('Is one of'),
1712 'mnot' => ts('Is not one of'),
1719 'has' => ts('Contains'),
1720 'sw' => ts('Starts with'),
1721 'ew' => ts('Ends with'),
1722 'nhas' => ts('Does not contain'),
1723 'eq' => ts('Is equal to'),
1724 'neq' => ts('Is not equal to'),
1725 'nll' => ts('Is empty (Null)'),
1726 'nnll' => ts('Is not empty (Null)'),
1733 * Build the tag filter field to display on the filters tab.
1735 public function buildTagFilter() {
1736 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1737 if (!empty($contactTags)) {
1738 $this->_columns
['civicrm_tag'] = array(
1739 'dao' => 'CRM_Core_DAO_Tag',
1743 'title' => ts('Tag'),
1744 'type' => CRM_Utils_Type
::T_INT
,
1746 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1747 'options' => $contactTags,
1755 * Adds group filters to _columns (called from _Construct).
1757 public function buildGroupFilter() {
1758 $this->_columns
['civicrm_group']['filters'] = array(
1760 'name' => 'group_id',
1761 'title' => ts('Group'),
1762 'type' => CRM_Utils_Type
::T_INT
,
1763 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1765 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1768 if (empty($this->_columns
['civicrm_group']['dao'])) {
1769 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1771 if (empty($this->_columns
['civicrm_group']['alias'])) {
1772 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1777 * Get SQL operator from form text version.
1779 * @param string $operator
1783 public function getSQLOperator($operator = "like") {
1784 switch ($operator) {
1817 return 'IS NOT NULL';
1826 * Generate where clause.
1828 * This can be overridden in reports for special treatment of a field
1830 * @param array $field Field specifications
1831 * @param string $op Query operator (not an exact match to sql)
1832 * @param mixed $value
1836 * @return null|string
1838 public function whereClause(&$field, $op, $value, $min, $max) {
1840 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1842 // CRM-18010: Ensure type of each report filters
1844 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1851 if (($min !== NULL && strlen($min) > 0) ||
1852 ($max !== NULL && strlen($max) > 0)
1856 $min = CRM_Utils_Type
::escape($min, $type);
1858 $clauses[] = "( {$field['dbAlias']} >= $min )";
1861 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1865 $max = CRM_Utils_Type
::escape($max, $type);
1867 $clauses[] = "( {$field['dbAlias']} <= $max )";
1870 $clauses[] = "( {$field['dbAlias']} > $max )";
1874 if (!empty($clauses)) {
1876 $clause = implode(' AND ', $clauses);
1879 $clause = '(' . implode('OR', $clauses) . ')';
1887 if ($value !== NULL && strlen($value) > 0) {
1888 $value = CRM_Utils_Type
::escape($value, $type);
1889 if (strpos($value, '%') === FALSE) {
1890 $value = "'%{$value}%'";
1893 $value = "'{$value}'";
1895 $sqlOP = $this->getSQLOperator($op);
1896 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1902 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1903 $value = explode(',', $value);
1905 if ($value !== NULL && is_array($value) && count($value) > 0) {
1906 $sqlOP = $this->getSQLOperator($op);
1907 if (CRM_Utils_Array
::value('type', $field) ==
1908 CRM_Utils_Type
::T_STRING
1910 //cycle through selections and escape values
1911 foreach ($value as $key => $selection) {
1912 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1915 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1919 // for numerical values
1920 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1923 if ($op == 'notin') {
1924 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1927 $clause = "( " . $clause . " )";
1934 // multiple has or multiple not
1935 if ($value !== NULL && count($value) > 0) {
1936 $value = CRM_Utils_Type
::escapeAll($value, $type);
1937 $operator = $op == 'mnot' ?
'NOT' : '';
1938 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1939 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1945 if ($value !== NULL && strlen($value) > 0) {
1946 $value = CRM_Utils_Type
::escape($value, $type);
1947 if (strpos($value, '%') === FALSE) {
1949 $value = "'{$value}%'";
1952 $value = "'%{$value}'";
1956 $value = "'{$value}'";
1958 $sqlOP = $this->getSQLOperator($op);
1959 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1965 $sqlOP = $this->getSQLOperator($op);
1966 $clause = "( {$field['dbAlias']} $sqlOP )";
1972 //CRM-18457: some custom field passes value in array format against binary operator
1973 if (is_array($value) && count($value)) {
1978 if ($value !== NULL && $value !== '') {
1979 if (isset($field['clause'])) {
1980 // FIXME: we not doing escape here. Better solution is to use two
1981 // different types - data-type and filter-type
1982 $clause = $field['clause'];
1984 elseif (!is_array($value)) {
1985 $value = CRM_Utils_Type
::escape($value, $type);
1986 $sqlOP = $this->getSQLOperator($op);
1987 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1988 $value = "'{$value}'";
1990 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1996 if (!empty($field['group']) && $clause) {
1997 $clause = $this->whereGroupClause($field, $value, $op);
1999 elseif (!empty($field['tag']) && $clause) {
2000 // not using left join in query because if any contact
2001 // belongs to more than one tag, results duplicate
2003 $clause = $this->whereTagClause($field, $value, $op);
2005 elseif (!empty($field['membership_org']) && $clause) {
2006 $clause = $this->whereMembershipOrgClause($value, $op);
2008 elseif (!empty($field['membership_type']) && $clause) {
2009 $clause = $this->whereMembershipTypeClause($value, $op);
2015 * Get SQL where clause for a date field.
2017 * @param string $fieldName
2018 * @param string $relative
2019 * @param string $from
2021 * @param string $type
2022 * @param string $fromTime
2023 * @param string $toTime
2025 * @return null|string
2027 public function dateClause(
2029 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2032 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2033 $sqlOP = $this->getSQLOperator($relative);
2034 return "( {$fieldName} {$sqlOP} )";
2037 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2040 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2041 $clauses[] = "( {$fieldName} >= $from )";
2045 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2046 $clauses[] = "( {$fieldName} <= {$to} )";
2049 if (!empty($clauses)) {
2050 return implode(' AND ', $clauses);
2057 * Get values for from and to for date ranges.
2061 * @param bool $relative
2062 * @param string $from
2064 * @param string $fromTime
2065 * @param string $toTime
2069 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2070 if (empty($toTime)) {
2071 // odd legacy behaviour to treat NULL as 'end of the day'
2072 // recommend updating reports to call CRM_Utils_Date::getFromTo
2073 //directly (default on the function is the actual default there).
2076 return CRM_Utils_Date
::getFromTo($relative, $from, $to, $fromTime, $toTime);
2080 * Alter display of rows.
2082 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2083 * such as rendering contacts as links.
2085 * @param array $rows
2086 * Rows generated by SQL, with an array for each row.
2088 public function alterDisplay(&$rows) {
2092 * Alter the way in which custom data fields are displayed.
2094 * @param array $rows
2096 public function alterCustomDataDisplay(&$rows) {
2097 // custom code to alter rows having custom values
2098 if (empty($this->_customGroupExtends
)) {
2102 $customFields = array();
2103 $customFieldIds = array();
2104 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2105 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2106 $customFieldIds[$fieldAlias] = $fieldId;
2109 if (empty($customFieldIds)) {
2113 // skip for type date and ContactReference since date format is already handled
2115 SELECT cg.table_name, cf.id
2116 FROM civicrm_custom_field cf
2117 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2118 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2119 cg.is_active = 1 AND
2120 cf.is_active = 1 AND
2121 cf.is_searchable = 1 AND
2122 cf.data_type NOT IN ('ContactReference', 'Date') AND
2123 cf.id IN (" . implode(",", $customFieldIds) . ")";
2125 $dao = CRM_Core_DAO
::executeQuery($query);
2126 while ($dao->fetch()) {
2127 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2131 $entryFound = FALSE;
2132 foreach ($rows as $rowNum => $row) {
2133 foreach ($row as $tableCol => $val) {
2134 if (array_key_exists($tableCol, $customFields)) {
2135 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2140 // skip looking further in rows, if first row itself doesn't
2141 // have the column we need
2149 * Remove duplicate rows.
2151 * @param array $rows
2153 public function removeDuplicates(&$rows) {
2154 if (empty($this->_noRepeats
)) {
2157 $checkList = array();
2159 foreach ($rows as $key => $list) {
2160 foreach ($list as $colName => $colVal) {
2161 if (array_key_exists($colName, $checkList) &&
2162 $checkList[$colName] == $colVal
2164 $rows[$key][$colName] = "";
2166 if (in_array($colName, $this->_noRepeats
)) {
2167 $checkList[$colName] = $colVal;
2174 * Fix subtotal display.
2177 * @param array $fields
2178 * @param bool $subtotal
2180 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2181 foreach ($row as $colName => $colVal) {
2182 if (in_array($colName, $fields)) {
2184 elseif (isset($this->_columnHeaders
[$colName])) {
2186 $row[$colName] = 'Subtotal';
2190 unset($row[$colName]);
2197 * Calculate grant total.
2199 * @param array $rows
2203 public function grandTotal(&$rows) {
2204 if (!$this->_rollup ||
count($rows) == 1) {
2208 $this->moveSummaryColumnsToTheRightHandSide();
2210 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2214 $this->rollupRow
= array_pop($rows);
2216 foreach ($this->_columnHeaders
as $fld => $val) {
2217 if (!in_array($fld, $this->_statFields
)) {
2218 if (!$this->_grandFlag
) {
2219 $this->rollupRow
[$fld] = ts('Grand Total');
2220 $this->_grandFlag
= TRUE;
2223 $this->rollupRow
[$fld] = "";
2228 $this->assign('grandStat', $this->rollupRow
);
2233 * Format display output.
2235 * @param array $rows
2236 * @param bool $pager
2238 public function formatDisplay(&$rows, $pager = TRUE) {
2239 // set pager based on if any limit was applied in the query.
2244 // allow building charts if any
2245 if (!empty($this->_params
['charts']) && !empty($rows)) {
2246 $this->buildChart($rows);
2247 $this->assign('chartEnabled', TRUE);
2248 $this->_chartId
= "{$this->_params['charts']}_" .
2249 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2251 $this->assign('chartId', $this->_chartId
);
2254 // unset columns not to be displayed.
2255 foreach ($this->_columnHeaders
as $key => $value) {
2256 if (!empty($value['no_display'])) {
2257 unset($this->_columnHeaders
[$key]);
2261 // unset columns not to be displayed.
2262 if (!empty($rows)) {
2263 foreach ($this->_noDisplay
as $noDisplayField) {
2264 foreach ($rows as $rowNum => $row) {
2265 unset($this->_columnHeaders
[$noDisplayField]);
2270 // build array of section totals
2271 $this->sectionTotals();
2273 // process grand-total row
2274 $this->grandTotal($rows);
2276 // use this method for formatting rows for display purpose.
2277 $this->alterDisplay($rows);
2278 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2280 // use this method for formatting custom rows for display purpose.
2281 $this->alterCustomDataDisplay($rows);
2287 * @param array $rows
2289 public function buildChart(&$rows) {
2290 // override this method for building charts.
2293 // select() method below has been added recently (v3.3), and many of the report templates might
2294 // still be having their own select() method. We should fix them as and when encountered and move
2295 // towards generalizing the select() method below.
2298 * Generate the SELECT clause and set class variable $_select.
2300 public function select() {
2301 $select = $this->_selectAliases
= array();
2302 $this->storeGroupByArray();
2304 foreach ($this->_columns
as $tableName => $table) {
2305 if (array_key_exists('fields', $table)) {
2306 foreach ($table['fields'] as $fieldName => $field) {
2307 if ($tableName == 'civicrm_address') {
2308 // deprecated, use $this->isTableSelected.
2309 $this->_addressField
= TRUE;
2311 if ($tableName == 'civicrm_email') {
2312 $this->_emailField
= TRUE;
2314 if ($tableName == 'civicrm_phone') {
2315 $this->_phoneField
= TRUE;
2318 if (!empty($field['required']) ||
2319 !empty($this->_params
['fields'][$fieldName])
2322 // 1. In many cases we want select clause to be built in slightly different way
2323 // for a particular field of a particular type.
2324 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2326 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2327 if ($selectClause) {
2328 $select[] = $selectClause;
2332 // include statistics columns only if set
2333 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2334 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2338 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2339 if ($selectClause) {
2340 $select[] = $selectClause;
2343 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2350 // select for group bys
2351 if (array_key_exists('group_bys', $table)) {
2352 foreach ($table['group_bys'] as $fieldName => $field) {
2354 if ($tableName == 'civicrm_address') {
2355 $this->_addressField
= TRUE;
2357 if ($tableName == 'civicrm_email') {
2358 $this->_emailField
= TRUE;
2360 if ($tableName == 'civicrm_phone') {
2361 $this->_phoneField
= TRUE;
2363 // 1. In many cases we want select clause to be built in slightly different way
2364 // for a particular field of a particular type.
2365 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2367 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2368 if ($selectClause) {
2369 $select[] = $selectClause;
2373 if (!empty($this->_params
['group_bys']) &&
2374 !empty($this->_params
['group_bys'][$fieldName]) &&
2375 !empty($this->_params
['group_bys_freq'])
2377 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2379 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2380 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2381 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2382 $field['title'] = 'Week';
2386 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2387 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2388 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2389 $field['title'] = 'Year';
2393 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2394 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2395 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2396 $field['title'] = 'Month';
2400 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2401 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2402 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2403 $field['title'] = 'Quarter';
2406 // for graphs and charts -
2407 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2408 $this->_interval
= $field['title'];
2409 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2410 = $field['title'] . ' Beginning';
2411 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2412 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2414 // just to make sure these values are transferred to rows.
2415 // since we 'll need them for calculation purpose,
2416 // e.g making subtotals look nicer or graphs
2417 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2418 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2425 if (empty($select)) {
2426 // CRM-21412 Do not give fatal error on report when no fields selected
2430 $this->_selectClauses
= $select;
2431 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2435 * Build select clause for a single field.
2437 * @param string $tableName
2438 * @param string $tableKey
2439 * @param string $fieldName
2440 * @param string $field
2444 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2445 if (!empty($field['pseudofield'])) {
2446 $alias = "{$tableName}_{$fieldName}";
2447 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2448 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2449 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['dbAlias'] = CRM_Utils_Array
::value('dbAlias', $field);
2450 $this->_selectAliases
[] = $alias;
2451 return ' 1 as ' . $alias;
2457 * Build where clause.
2459 public function where() {
2460 $this->storeWhereHavingClauseArray();
2462 if (empty($this->_whereClauses
)) {
2463 $this->_where
= "WHERE ( 1 ) ";
2464 $this->_having
= "";
2467 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2470 if ($this->_aclWhere
) {
2471 $this->_where
.= " AND {$this->_aclWhere} ";
2474 if (!empty($this->_havingClauses
)) {
2475 // use this clause to construct group by clause.
2476 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2481 * Store Where clauses into an array.
2483 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2484 * temp table that may not be part of the final where clause or added
2485 * in other functions
2487 public function storeWhereHavingClauseArray() {
2488 foreach ($this->_columns
as $tableName => $table) {
2489 if (array_key_exists('filters', $table)) {
2490 foreach ($table['filters'] as $fieldName => $field) {
2491 // respect pseudofield to filter spec so fields can be marked as
2492 // not to be handled here
2493 if (!empty($field['pseudofield'])) {
2497 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2498 if (CRM_Utils_Array
::value('operatorType', $field) ==
2499 CRM_Report_Form
::OP_MONTH
2501 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2502 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2503 if (is_array($value) && !empty($value)) {
2505 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2510 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2511 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2512 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2513 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2514 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2515 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2519 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2521 $clause = $this->whereClause($field,
2523 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2524 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2525 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2530 if (!empty($clause)) {
2531 if (!empty($field['having'])) {
2532 $this->_havingClauses
[] = $clause;
2535 $this->_whereClauses
[] = $clause;
2547 public function processReportMode() {
2548 $this->setOutputMode();
2551 = CRM_Utils_Request
::retrieve(
2554 CRM_Core_DAO
::$_nullObject
2557 $this->_absoluteUrl
= FALSE;
2559 $this->assign('printOnly', FALSE);
2561 if ($this->_outputMode
== 'print' ||
2562 ($this->_sendmail
&& !$this->_outputMode
)
2564 $this->assign('printOnly', TRUE);
2566 $this->addPaging
= FALSE;
2567 $this->assign('outputMode', 'print');
2568 $this->_outputMode
= 'print';
2569 if ($this->_sendmail
) {
2570 $this->_absoluteUrl
= TRUE;
2573 elseif ($this->_outputMode
== 'pdf') {
2575 $this->addPaging
= FALSE;
2576 $this->_absoluteUrl
= TRUE;
2578 elseif ($this->_outputMode
== 'csv') {
2580 $this->_absoluteUrl
= TRUE;
2581 $this->addPaging
= FALSE;
2583 elseif ($this->_outputMode
== 'group') {
2584 $this->assign('outputMode', 'group');
2586 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2587 $this->assign('outputMode', 'create_report');
2589 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2590 $this->_createNew
= TRUE;
2593 $this->assign('outputMode', $this->_outputMode
);
2594 $this->assign('printOnly', $printOnly);
2595 // Get today's date to include in printed reports
2597 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2598 $this->assign('reportDate', $reportDate);
2603 * Post Processing function for Form.
2605 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2606 * This function is not accessed when the api calls the report.
2608 public function beginPostProcess() {
2609 $this->setParams($this->controller
->exportValues($this->_name
));
2610 if (empty($this->_params
) &&
2613 $this->setParams($this->_formValues
);
2616 // hack to fix params when submitted from dashboard, CRM-8532
2617 // fields array is missing because form building etc is skipped
2618 // in dashboard mode for report
2619 //@todo - this could be done in the dashboard no we have a setter
2620 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2621 $this->setParams($this->_formValues
);
2624 $this->processReportMode();
2626 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2627 $this->_createNew
= ($this->_outputMode
== 'copy');
2628 CRM_Report_Form_Instance
::postProcess($this);
2630 if ($this->_outputMode
== 'delete') {
2631 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2634 $this->_formValues
= $this->_params
;
2636 $this->beginPostProcessCommon();
2640 * BeginPostProcess function run in both report mode and non-report mode (api).
2642 public function beginPostProcessCommon() {
2646 * Build the report query.
2648 * @param bool $applyLimit
2652 public function buildQuery($applyLimit = TRUE) {
2653 $this->buildGroupTempTable();
2656 $this->customDataFrom();
2657 $this->buildPermissionClause();
2662 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
2663 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
2665 $clause = "{$field['dbAlias']} as {$alias}";
2667 $this->_select
.= ", $clause ";
2670 if ($applyLimit && empty($this->_params
['charts'])) {
2673 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2675 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2676 $this->addToDeveloperTab($sql);
2681 * Build group by clause.
2683 public function groupBy() {
2684 $this->storeGroupByArray();
2686 if (!empty($this->_groupByArray
)) {
2687 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2692 * Build order by clause.
2694 public function orderBy() {
2695 $this->_orderBy
= "";
2696 $this->_sections
= array();
2697 $this->storeOrderByArray();
2698 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2699 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2701 $this->assign('sections', $this->_sections
);
2705 * Extract order by fields and store as an array.
2707 * In some cases other functions want to know which fields are selected for ordering by
2708 * Separating this into a separate function allows it to be called separately from constructing
2709 * the order by clause
2711 public function storeOrderByArray() {
2712 $orderBys = array();
2714 if (!empty($this->_params
['order_bys']) &&
2715 is_array($this->_params
['order_bys']) &&
2716 !empty($this->_params
['order_bys'])
2719 // Process order_bys in user-specified order
2720 foreach ($this->_params
['order_bys'] as $orderBy) {
2721 $orderByField = array();
2722 foreach ($this->_columns
as $tableName => $table) {
2723 if (array_key_exists('order_bys', $table)) {
2724 // For DAO columns defined in $this->_columns
2725 $fields = $table['order_bys'];
2727 elseif (array_key_exists('extends', $table)) {
2728 // For custom fields referenced in $this->_customGroupExtends
2729 $fields = CRM_Utils_Array
::value('fields', $table, array());
2734 if (!empty($fields) && is_array($fields)) {
2735 foreach ($fields as $fieldName => $field) {
2736 if ($fieldName == $orderBy['column']) {
2737 $orderByField = array_merge($field, $orderBy);
2738 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2745 if (!empty($orderByField)) {
2746 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2747 if ($this->groupConcatTested
) {
2748 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
2751 // Not sure when this is preferable to using tplField (which has
2752 // definitely been tested to work in cases then this does not.
2753 // in caution not switching unless report has been tested for
2754 // group concat functionality.
2755 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2758 // Record any section headers for assignment to the template
2759 if (!empty($orderBy['section'])) {
2760 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2761 $this->_sections
[$orderByField['tplField']] = $orderByField;
2767 $this->_orderByArray
= $orderBys;
2769 $this->assign('sections', $this->_sections
);
2773 * Determine unselected columns.
2777 public function unselectedOrderByColumns() {
2778 return array_diff_key($this->_orderByFields
, $this->getSelectColumns());
2782 * Determine unselected columns.
2786 public function unselectedSectionColumns() {
2787 if (is_array($this->_sections
)) {
2788 return array_diff_key($this->_sections
, $this->getSelectColumns());
2796 * Build output rows.
2798 * @param string $sql
2799 * @param array $rows
2801 public function buildRows($sql, &$rows) {
2802 $dao = CRM_Core_DAO
::executeQuery($sql);
2803 if (!is_array($rows)) {
2807 // use this method to modify $this->_columnHeaders
2808 $this->modifyColumnHeaders();
2810 $unselectedSectionColumns = $this->unselectedSectionColumns();
2812 while ($dao->fetch()) {
2814 foreach ($this->_columnHeaders
as $key => $value) {
2815 if (property_exists($dao, $key)) {
2816 $row[$key] = $dao->$key;
2820 // section headers not selected for display need to be added to row
2821 foreach ($unselectedSectionColumns as $key => $values) {
2822 if (property_exists($dao, $key)) {
2823 $row[$key] = $dao->$key;
2832 * Calculate section totals.
2834 * When "order by" fields are marked as sections, this assigns to the template
2835 * an array of total counts for each section. This data is used by the Smarty
2836 * plugin {sectionTotal}.
2838 public function sectionTotals() {
2840 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2841 if (empty($this->_selectAliases
)) {
2845 if (!empty($this->_sections
)) {
2846 // build the query with no LIMIT clause
2847 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2848 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2850 // pull section aliases out of $this->_sections
2851 $sectionAliases = array_keys($this->_sections
);
2854 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2855 $ifnulls[] = "ifnull($alias, '') as $alias";
2857 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2858 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2860 // Group (un-limited) report by all aliases and get counts. This might
2861 // be done more efficiently when the contents of $sql are known, ie. by
2862 // overriding this method in the report class.
2864 $query = $this->_select
.
2865 ", count(*) as ct from ($sql) as subquery group by " .
2866 implode(", ", $sectionAliases);
2868 // initialize array of total counts
2870 $dao = CRM_Core_DAO
::executeQuery($query);
2871 while ($dao->fetch()) {
2873 // let $this->_alterDisplay translate any integer ids to human-readable values.
2874 $rows[0] = $dao->toArray();
2875 $this->alterDisplay($rows);
2878 // add totals for all permutations of section values
2881 $aliasCount = count($sectionAliases);
2882 foreach ($sectionAliases as $alias) {
2883 $values[] = $row[$alias];
2884 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2885 if ($i == $aliasCount) {
2886 // the last alias is the lowest-level section header; use count as-is
2887 $totals[$key] = $dao->ct
;
2890 // other aliases are higher level; roll count into their total
2891 $totals[$key] +
= $dao->ct
;
2895 $this->assign('sectionTotals', $totals);
2900 * Modify column headers.
2902 public function modifyColumnHeaders() {
2903 // use this method to modify $this->_columnHeaders
2907 * Move totals columns to the right edge of the table.
2909 * It seems like a more logical layout to have any totals columns on the far right regardless of
2910 * the location of the rest of their table.
2912 public function moveSummaryColumnsToTheRightHandSide() {
2913 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2914 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2918 * Assign rows to the template.
2920 * @param array $rows
2922 public function doTemplateAssignment(&$rows) {
2923 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2924 $this->assign_by_ref('rows', $rows);
2925 $this->assign('statistics', $this->statistics($rows));
2929 * Build report statistics.
2931 * Override this method to build your own statistics.
2933 * @param array $rows
2937 public function statistics(&$rows) {
2938 $statistics = array();
2940 $count = count($rows);
2941 // Why do we increment the count for rollup seems to artificially inflate the count.
2942 // It seems perhaps intentional to include the summary row in the count of results - although
2943 // this just seems odd.
2944 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2948 $this->countStat($statistics, $count);
2950 $this->groupByStat($statistics);
2952 $this->filterStat($statistics);
2958 * Add count statistics.
2960 * @param array $statistics
2963 public function countStat(&$statistics, $count) {
2964 $statistics['counts']['rowCount'] = array(
2965 'title' => ts('Row(s) Listed'),
2969 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2970 $statistics['counts']['rowsFound'] = array(
2971 'title' => ts('Total Row(s)'),
2972 'value' => $this->_rowsFound
,
2978 * Add group by statistics.
2980 * @param array $statistics
2982 public function groupByStat(&$statistics) {
2983 if (!empty($this->_params
['group_bys']) &&
2984 is_array($this->_params
['group_bys']) &&
2985 !empty($this->_params
['group_bys'])
2987 foreach ($this->_columns
as $tableName => $table) {
2988 if (array_key_exists('group_bys', $table)) {
2989 foreach ($table['group_bys'] as $fieldName => $field) {
2990 if (!empty($this->_params
['group_bys'][$fieldName])) {
2991 $combinations[] = $field['title'];
2996 $statistics['groups'][] = array(
2997 'title' => ts('Grouping(s)'),
2998 'value' => implode(' & ', $combinations),
3004 * Filter statistics.
3006 * @param array $statistics
3008 public function filterStat(&$statistics) {
3009 foreach ($this->_columns
as $tableName => $table) {
3010 if (array_key_exists('filters', $table)) {
3011 foreach ($table['filters'] as $fieldName => $field) {
3012 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3013 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3014 CRM_Utils_Array
::value('operatorType', $field) !=
3015 CRM_Report_Form
::OP_MONTH
3019 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3020 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3021 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3022 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3023 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3025 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3026 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3028 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3029 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3032 $statistics['filters'][] = array(
3033 'title' => $field['title'],
3034 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3037 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3038 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3040 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3041 $statistics['filters'][] = array(
3042 'title' => $field['title'],
3043 'value' => $pair[$rel],
3048 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3051 $pair = $this->getOperationPair(
3052 CRM_Utils_Array
::value('operatorType', $field),
3055 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3056 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3057 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3058 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3059 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3061 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3062 $this->setEntityRefDefaults($field, $tableName);
3063 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3064 array('id' => $val) +
3065 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3067 foreach ($result['values'] as $v) {
3068 $values[] = $v['label'];
3070 $value = "{$pair[$op]} " . implode(', ', $values);
3072 elseif ($op == 'nll' ||
$op == 'nnll') {
3073 $value = $pair[$op];
3075 elseif (is_array($val) && (!empty($val))) {
3076 $options = CRM_Utils_Array
::value('options', $field, array());
3077 foreach ($val as $key => $valIds) {
3078 if (isset($options[$valIds])) {
3079 $val[$key] = $options[$valIds];
3082 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3083 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3084 $val = implode(', ', $val);
3085 $value = "{$pair[$op]} " . $val;
3087 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3088 isset($field['options']) &&
3089 is_array($field['options']) && !empty($field['options'])
3091 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3092 CRM_Utils_Array
::value($val, $field['options'], $val);
3095 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3098 if ($value && empty($field['no_display'])) {
3099 $statistics['filters'][] = array(
3100 'title' => CRM_Utils_Array
::value('title', $field),
3111 * End post processing.
3113 * @param array|null $rows
3115 public function endPostProcess(&$rows = NULL) {
3116 $this->assign('report_class', get_class($this));
3117 if ($this->_storeResultSet
) {
3118 $this->_resultSet
= $rows;
3121 if ($this->_outputMode
== 'print' ||
3122 $this->_outputMode
== 'pdf' ||
3126 $content = $this->compileContent();
3127 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3131 if ($this->_sendmail
) {
3132 $config = CRM_Core_Config
::singleton();
3133 $attachments = array();
3135 if ($this->_outputMode
== 'csv') {
3137 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3138 ": {$url}</p>" . '<p>' .
3139 ts('The report is attached as a CSV file.') . '</p>' .
3140 $this->_formValues
['report_footer'];
3142 $csvFullFilename = $config->templateCompileDir
.
3143 CRM_Utils_File
::makeFileName('CiviReport.csv');
3144 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3145 file_put_contents($csvFullFilename, $csvContent);
3146 $attachments[] = array(
3147 'fullPath' => $csvFullFilename,
3148 'mime_type' => 'text/csv',
3149 'cleanName' => 'CiviReport.csv',
3152 if ($this->_outputMode
== 'pdf') {
3153 // generate PDF content
3154 $pdfFullFilename = $config->templateCompileDir
.
3155 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3156 file_put_contents($pdfFullFilename,
3157 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3158 TRUE, array('orientation' => 'landscape')
3161 // generate Email Content
3163 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3164 ": {$url}</p>" . '<p>' .
3165 ts('The report is attached as a PDF file.') . '</p>' .
3166 $this->_formValues
['report_footer'];
3168 $attachments[] = array(
3169 'fullPath' => $pdfFullFilename,
3170 'mime_type' => 'application/pdf',
3171 'cleanName' => 'CiviReport.pdf',
3175 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3176 $this->_outputMode
, $attachments
3179 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3182 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3186 elseif ($this->_outputMode
== 'print') {
3190 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3191 $config = CRM_Core_Config
::singleton();
3192 //get chart image name
3193 $chartImg = $this->_chartId
. '.png';
3194 //get image url path
3196 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3198 $uploadUrl .= $chartImg;
3199 //get image doc path to overwrite
3201 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3202 'openFlashChart/' . $chartImg;
3204 $chart = imagecreatefrompng($uploadUrl);
3205 //convert it into formatted png
3206 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3207 //overwrite with same image
3208 imagepng($chart, $uploadImg);
3210 imagedestroy($chart);
3212 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3214 CRM_Utils_System
::civiExit();
3216 elseif ($this->_outputMode
== 'csv') {
3217 CRM_Report_Utils_Report
::export2csv($this, $rows);
3219 elseif ($this->_outputMode
== 'group') {
3220 $group = $this->_params
['groups'];
3221 $this->add2group($group);
3226 * Set store result set indicator to TRUE.
3228 * @todo explain what this does
3230 public function storeResultSet() {
3231 $this->_storeResultSet
= TRUE;
3239 public function getResultSet() {
3240 return $this->_resultSet
;
3244 * Get the sql used to generate the report.
3248 public function getReportSql() {
3249 return $this->sqlArray
;
3253 * Use the form name to create the tpl file name.
3257 public function getTemplateFileName() {
3258 $defaultTpl = parent
::getTemplateFileName();
3259 $template = CRM_Core_Smarty
::singleton();
3260 if (!$template->template_exists($defaultTpl)) {
3261 $defaultTpl = 'CRM/Report/Form.tpl';
3267 * Compile the report content.
3269 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3273 public function compileContent() {
3274 $templateFile = $this->getHookedTemplateFileName();
3275 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3276 CRM_Core_Form
::$_template->fetch($templateFile) .
3277 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3282 * Post process function.
3284 public function postProcess() {
3285 // get ready with post process params
3286 $this->beginPostProcess();
3289 $sql = $this->buildQuery();
3291 // build array of result based on column headers. This method also allows
3292 // modifying column headers before using it to build result set i.e $rows.
3294 $this->buildRows($sql, $rows);
3296 // format result set.
3297 $this->formatDisplay($rows);
3299 // assign variables to templates
3300 $this->doTemplateAssignment($rows);
3302 // do print / pdf / instance stuff if needed
3303 $this->endPostProcess($rows);
3309 * @param int $rowCount
3313 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3314 // lets do the pager if in html mode
3315 $this->_limit
= NULL;
3317 // CRM-14115, over-ride row count if rowCount is specified in URL
3318 if ($this->_dashBoardRowCount
) {
3319 $rowCount = $this->_dashBoardRowCount
;
3321 if ($this->addPaging
) {
3322 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3324 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3326 // @todo all http vars should be extracted in the preProcess
3327 // - not randomly in the class
3328 if (!$pageId && !empty($_POST)) {
3329 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3330 $pageId = max((int) $_POST['crmPID_B'], 1);
3332 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3333 $pageId = max((int) $_POST['crmPID'], 1);
3335 unset($_POST['crmPID_B'], $_POST['crmPID']);
3338 $pageId = $pageId ?
$pageId : 1;
3339 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3340 $offset = ($pageId - 1) * $rowCount;
3342 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3343 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3345 $this->_limit
= " LIMIT $offset, $rowCount";
3346 return array($offset, $rowCount);
3348 if ($this->_limitValue
) {
3349 if ($this->_offsetValue
) {
3350 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3353 $this->_limit
= " LIMIT " . $this->_limitValue
;
3361 * @param int $rowCount
3363 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3364 // CRM-14115, over-ride row count if rowCount is specified in URL
3365 if ($this->_dashBoardRowCount
) {
3366 $rowCount = $this->_dashBoardRowCount
;
3369 if ($this->_limit
&& ($this->_limit
!= '')) {
3370 if (!$this->_rowsFound
) {
3371 $sql = "SELECT FOUND_ROWS();";
3372 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3375 'total' => $this->_rowsFound
,
3376 'rowCount' => $rowCount,
3377 'status' => ts('Records') . ' %%StatusMessage%%',
3378 'buttonBottom' => 'PagerBottomButton',
3379 'buttonTop' => 'PagerTopButton',
3381 if (!empty($this->controller
)) {
3382 // This happens when being called from the api Really we want the api to be able to
3383 // pass paging parameters, but at this stage just preventing test crashes.
3384 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3387 $pager = new CRM_Utils_Pager($params);
3388 $this->assign_by_ref('pager', $pager);
3389 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3394 * Build a group filter with contempt for large data sets.
3396 * This function has been retained as it takes time to migrate the reports over
3397 * to the new method which will not crash on large datasets.
3401 * @param string $field
3402 * @param mixed $value
3407 public function legacySlowGroupFilterClause($field, $value, $op) {
3408 $smartGroupQuery = "";
3410 $group = new CRM_Contact_DAO_Group();
3411 $group->is_active
= 1;
3413 $smartGroups = array();
3414 while ($group->fetch()) {
3415 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3416 $group->saved_search_id
3418 $smartGroups[] = $group->id
;
3422 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3424 $smartGroupQuery = '';
3425 if (!empty($smartGroups)) {
3426 $smartGroups = implode(',', $smartGroups);
3427 $smartGroupQuery = " UNION DISTINCT
3428 SELECT DISTINCT smartgroup_contact.contact_id
3429 FROM civicrm_group_contact_cache smartgroup_contact
3430 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3433 $sqlOp = $this->getSQLOperator($op);
3434 if (!is_array($value)) {
3435 $value = array($value);
3437 //include child groups if any
3438 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3440 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3442 $contactAlias = $this->_aliases
['civicrm_contact'];
3443 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3444 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3446 return " {$contactAlias}.id {$sqlOp} (
3447 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3448 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3449 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3450 {$smartGroupQuery} ) ";
3454 * Build where clause for groups.
3456 * @param string $field
3457 * @param mixed $value
3462 public function whereGroupClause($field, $value, $op) {
3463 if ($this->groupFilterNotOptimised
) {
3464 return $this->legacySlowGroupFilterClause($field, $value, $op);
3466 if ($op === 'notin') {
3467 return " group_temp_table.id IS NULL ";
3469 // We will have used an inner join instead.
3475 * Create a table of the contact ids included by the group filter.
3477 * This function is called by both the api (tests) and the UI.
3479 public function buildGroupTempTable() {
3480 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3483 $filteredGroups = (array) $this->_params
['gid_value'];
3485 $groups = civicrm_api3('Group', 'get', array(
3487 'id' => array('IN' => $filteredGroups),
3488 'saved_search_id' => array('>' => 0),
3491 $smartGroups = array_keys($groups['values']);
3494 SELECT DISTINCT group_contact.contact_id as id
3495 FROM civicrm_group_contact group_contact
3496 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3497 AND group_contact.status = 'Added' ";
3499 if (!empty($smartGroups)) {
3500 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3501 $smartGroups = implode(',', $smartGroups);
3504 SELECT smartgroup_contact.contact_id as id
3505 FROM civicrm_group_contact_cache smartgroup_contact
3506 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3509 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3510 $this->executeReportQuery("
3511 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3514 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3518 * Execute query and add it to the developer tab.
3520 * @param string $query
3521 * @param array $params
3523 * @return \CRM_Core_DAO|object
3525 protected function executeReportQuery($query, $params = array()) {
3526 $this->addToDeveloperTab($query);
3527 return CRM_Core_DAO
::executeQuery($query, $params);
3531 * Build where clause for tags.
3533 * @param string $field
3534 * @param mixed $value
3539 public function whereTagClause($field, $value, $op) {
3540 // not using left join in query because if any contact
3541 // belongs to more than one tag, results duplicate
3543 $sqlOp = $this->getSQLOperator($op);
3544 if (!is_array($value)) {
3545 $value = array($value);
3547 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3548 $entity_table = $this->_tagFilterTable
;
3549 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3550 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3551 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3552 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3556 * Generate membership organization clause.
3558 * @param mixed $value
3559 * @param string $op SQL Operator
3563 public function whereMembershipOrgClause($value, $op) {
3564 $sqlOp = $this->getSQLOperator($op);
3565 if (!is_array($value)) {
3566 $value = array($value);
3569 $tmp_membership_org_sql_list = implode(', ', $value);
3570 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3571 SELECT DISTINCT mem.contact_id
3572 FROM civicrm_membership mem
3573 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3574 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3575 WHERE mt.member_of_contact_id IN (" .
3576 $tmp_membership_org_sql_list . ")
3577 AND mt.is_active = '1'
3578 AND mem_status.is_current_member = '1'
3579 AND mem_status.is_active = '1' ) ";
3583 * Generate Membership Type SQL Clause.
3585 * @param mixed $value
3591 public function whereMembershipTypeClause($value, $op) {
3592 $sqlOp = $this->getSQLOperator($op);
3593 if (!is_array($value)) {
3594 $value = array($value);
3597 $tmp_membership_sql_list = implode(', ', $value);
3598 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3599 SELECT DISTINCT mem.contact_id
3600 FROM civicrm_membership mem
3601 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3602 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3603 WHERE mem.membership_type_id IN (" .
3604 $tmp_membership_sql_list . ")
3605 AND mt.is_active = '1'
3606 AND mem_status.is_current_member = '1'
3607 AND mem_status.is_active = '1' ) ";
3611 * Buld contact acl clause
3612 * @deprecated in favor of buildPermissionClause
3614 * @param string $tableAlias
3616 public function buildACLClause($tableAlias = 'contact_a') {
3617 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3621 * Build the permision clause for all entities in this report
3623 public function buildPermissionClause() {
3625 foreach ($this->selectedTables() as $tableName) {
3626 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3627 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3628 $tableAlias = $this->_columns
[$tableName]['alias'];
3629 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3630 foreach ($clauses as $field => $clause) {
3631 // Skip contact_id field if redundant
3632 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3633 $ret["$tableName.$field"] = $clause;
3638 // Override output from buildACLClause
3639 $this->_aclFrom
= NULL;
3640 $this->_aclWhere
= implode(' AND ', $ret);
3644 * Add custom data to the columns.
3646 * @param bool $addFields
3647 * @param array $permCustomGroupIds
3649 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3650 if (empty($this->_customGroupExtends
)) {
3653 if (!is_array($this->_customGroupExtends
)) {
3654 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3656 $customGroupWhere = '';
3657 if (!empty($permCustomGroupIds)) {
3658 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3662 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3663 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3664 FROM civicrm_custom_group cg
3665 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3666 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3668 cg.is_active = 1 AND
3669 cf.is_active = 1 AND
3670 cf.is_searchable = 1
3671 ORDER BY cg.weight, cf.weight";
3672 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3675 while ($customDAO->fetch()) {
3676 if ($customDAO->table_name
!= $curTable) {
3677 $curTable = $customDAO->table_name
;
3678 $curFields = $curFilters = array();
3681 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3682 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3683 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3684 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3686 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3687 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3688 $this->_columns
[$curTable][$colKey] = array();
3692 $fieldName = 'custom_' . $customDAO->cf_id
;
3695 // this makes aliasing work in favor
3696 $curFields[$fieldName] = array(
3697 'name' => $customDAO->column_name
,
3698 'title' => $customDAO->label
,
3699 'dataType' => $customDAO->data_type
,
3700 'htmlType' => $customDAO->html_type
,
3703 if ($this->_customGroupFilters
) {
3704 // this makes aliasing work in favor
3705 $curFilters[$fieldName] = array(
3706 'name' => $customDAO->column_name
,
3707 'title' => $customDAO->label
,
3708 'dataType' => $customDAO->data_type
,
3709 'htmlType' => $customDAO->html_type
,
3713 switch ($customDAO->data_type
) {
3716 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3717 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3718 // CRM-6946, show time part for datetime date fields
3719 if ($customDAO->time_format
) {
3720 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3725 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3726 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3727 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3731 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3732 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3736 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3737 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3738 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3742 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3743 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3747 case 'StateProvince':
3749 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3751 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3752 if ($options !== FALSE) {
3753 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3754 $curFilters[$fieldName]['options'] = $options;
3758 case 'ContactReference':
3759 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3760 $curFilters[$fieldName]['name'] = 'display_name';
3761 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3763 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3764 $curFields[$fieldName]['name'] = 'display_name';
3765 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3769 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3770 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3774 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3775 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3776 if ($options !== FALSE) {
3777 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3778 $curFilters[$fieldName]['options'] = $options;
3782 if (!array_key_exists('type', $curFields[$fieldName])) {
3783 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3787 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3789 if ($this->_customGroupFilters
) {
3790 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3792 if ($this->_customGroupGroupBy
) {
3793 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3799 * Build custom data from clause.
3801 * @param bool $joinsForFiltersOnly
3802 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3804 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3805 if (empty($this->_customGroupExtends
)) {
3808 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3809 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3810 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3811 $customTables = array();
3812 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3813 while ($customTablesDAO->fetch()) {
3814 $customTables[] = $customTablesDAO->table_name
;
3817 foreach ($this->_columns
as $table => $prop) {
3818 if (in_array($table, $customTables)) {
3819 $extendsTable = $mapper[$prop['extends']];
3820 // Check field is required for rendering the report.
3821 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3824 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3826 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3828 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3829 // handle for ContactReference
3830 if (array_key_exists('fields', $prop)) {
3831 foreach ($prop['fields'] as $fieldName => $field) {
3832 if (CRM_Utils_Array
::value('dataType', $field) ==
3835 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3837 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3846 * Check if the field is selected.
3848 * @param string $prop
3852 public function isFieldSelected($prop) {
3857 if (!empty($this->_params
['fields'])) {
3858 foreach (array_keys($prop['fields']) as $fieldAlias) {
3859 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3860 if ($customFieldId) {
3861 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3865 //might be survey response field.
3866 if (!empty($this->_params
['fields']['survey_response']) &&
3867 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3875 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3876 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3877 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3878 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3885 if (!empty($this->_params
['order_bys'])) {
3886 foreach (array_keys($prop['fields']) as $fieldAlias) {
3887 foreach ($this->_params
['order_bys'] as $orderBy) {
3888 if ($fieldAlias == $orderBy['column'] &&
3889 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3896 return $this->isFieldFiltered($prop);
3901 * Check if the field is used as a filter.
3903 * @param string $prop
3907 protected function isFieldFiltered($prop) {
3908 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3909 foreach ($prop['filters'] as $fieldAlias => $val) {
3918 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3919 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3920 ||
($attach != 'relative' &&
3921 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3927 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3928 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3939 * Check for empty order_by configurations and remove them.
3941 * Also set template to hide them.
3943 * @param array $formValues
3945 public function preProcessOrderBy(&$formValues) {
3946 // Object to show/hide form elements
3947 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3949 $_showHide->addShow('optionField_1');
3951 // Cycle through order_by options; skip any empty ones, and hide them as well
3954 if (!empty($formValues['order_bys'])) {
3955 foreach ($formValues['order_bys'] as $order_by) {
3956 if ($order_by['column'] && $order_by['column'] != '-') {
3957 $_showHide->addShow('optionField_' . $n);
3958 $orderBys[$n] = $order_by;
3963 for ($i = $n; $i <= 5; $i++
) {
3965 $_showHide->addHide('optionField_' . $i);
3969 // overwrite order_by options with modified values
3970 if (!empty($orderBys)) {
3971 $formValues['order_bys'] = $orderBys;
3974 $formValues['order_bys'] = array(1 => array('column' => '-'));
3977 // assign show/hide data to template
3978 $_showHide->addToTemplate();
3982 * Check if table name has columns in SELECT clause.
3984 * @param string $tableName
3985 * Name of table (index of $this->_columns array).
3989 public function isTableSelected($tableName) {
3990 return in_array($tableName, $this->selectedTables());
3994 * Check if table name has columns in WHERE or HAVING clause.
3996 * @param string $tableName
3997 * Name of table (index of $this->_columns array).
4001 public function isTableFiltered($tableName) {
4002 // Cause the array to be generated if not previously done.
4003 if (!$this->_selectedTables
&& !$this->filteredTables
) {
4004 $this->selectedTables();
4006 return in_array($tableName, $this->filteredTables
);
4010 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4012 * If the array is unset it will be built.
4017 public function selectedTables() {
4018 if (!$this->_selectedTables
) {
4019 $orderByColumns = array();
4020 if (array_key_exists('order_bys', $this->_params
) &&
4021 is_array($this->_params
['order_bys'])
4023 foreach ($this->_params
['order_bys'] as $orderBy) {
4024 $orderByColumns[] = $orderBy['column'];
4028 foreach ($this->_columns
as $tableName => $table) {
4029 if (array_key_exists('fields', $table)) {
4030 foreach ($table['fields'] as $fieldName => $field) {
4031 if (!empty($field['required']) ||
4032 !empty($this->_params
['fields'][$fieldName])
4034 $this->_selectedTables
[] = $tableName;
4039 if (array_key_exists('order_bys', $table)) {
4040 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4041 if (in_array($orderByName, $orderByColumns)) {
4042 $this->_selectedTables
[] = $tableName;
4047 if (array_key_exists('filters', $table)) {
4048 foreach ($table['filters'] as $filterName => $filter) {
4049 if (!empty($this->_params
["{$filterName}_value"])
4050 ||
!empty($this->_params
["{$filterName}_relative"])
4051 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4053 || CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4056 $this->_selectedTables
[] = $tableName;
4057 $this->filteredTables
[] = $tableName;
4064 return $this->_selectedTables
;
4068 * Add address fields.
4070 * @deprecated - use getAddressColumns which is a more accurate description
4071 * and also accepts an array of options rather than a long list
4073 * adding address fields to construct function in reports
4075 * @param bool $groupBy
4076 * Add GroupBy? Not appropriate for detail report.
4077 * @param bool $orderBy
4078 * Add GroupBy? Not appropriate for detail report.
4079 * @param bool $filters
4080 * @param array $defaults
4083 * address fields for construct clause
4085 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4086 $defaultAddressFields = array(
4087 'street_address' => ts('Street Address'),
4088 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4089 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4090 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4091 'street_number' => ts('Street Number'),
4092 'street_name' => ts('Street Name'),
4093 'street_unit' => ts('Street Unit'),
4094 'city' => ts('City'),
4095 'postal_code' => ts('Postal Code'),
4096 'postal_code_suffix' => ts('Postal Code Suffix'),
4097 'country_id' => ts('Country'),
4098 'state_province_id' => ts('State/Province'),
4099 'county_id' => ts('County'),
4101 $addressFields = array(
4102 'civicrm_address' => array(
4103 'dao' => 'CRM_Core_DAO_Address',
4105 'address_name' => array(
4106 'title' => ts('Address Name'),
4107 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4111 'grouping' => 'location-fields',
4114 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4115 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4116 'title' => $fieldLabel,
4117 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4121 $street_address_filters = $general_address_filters = array();
4123 // Address filter depends on whether street address parsing is enabled.
4125 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4128 if ($addressOptions['street_address_parsing']) {
4129 $street_address_filters = array(
4130 'street_number' => array(
4131 'title' => ts('Street Number'),
4132 'type' => CRM_Utils_Type
::T_INT
,
4133 'name' => 'street_number',
4135 'street_name' => array(
4136 'title' => ts('Street Name'),
4137 'name' => 'street_name',
4138 'type' => CRM_Utils_Type
::T_STRING
,
4143 $street_address_filters = array(
4144 'street_address' => array(
4145 'title' => ts('Street Address'),
4146 'type' => CRM_Utils_Type
::T_STRING
,
4147 'name' => 'street_address',
4151 $general_address_filters = array(
4152 'postal_code' => array(
4153 'title' => ts('Postal Code'),
4154 'type' => CRM_Utils_Type
::T_STRING
,
4155 'name' => 'postal_code',
4158 'title' => ts('City'),
4159 'type' => CRM_Utils_Type
::T_STRING
,
4162 'country_id' => array(
4163 'name' => 'country_id',
4164 'title' => ts('Country'),
4165 'type' => CRM_Utils_Type
::T_INT
,
4166 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4167 'options' => CRM_Core_PseudoConstant
::country(),
4169 'state_province_id' => array(
4170 'name' => 'state_province_id',
4171 'title' => ts('State/Province'),
4172 'type' => CRM_Utils_Type
::T_INT
,
4173 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4174 'options' => array(),
4176 'county_id' => array(
4177 'name' => 'county_id',
4178 'title' => ts('County'),
4179 'type' => CRM_Utils_Type
::T_INT
,
4180 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4181 'options' => array(),
4185 $addressFields['civicrm_address']['filters'] = array_merge(
4186 $street_address_filters,
4187 $general_address_filters);
4190 $addressFields['civicrm_address']['order_bys'] = array(
4191 'street_name' => array('title' => ts('Street Name')),
4192 'street_number' => array('title' => ts('Odd / Even Street Number')),
4193 'street_address' => NULL,
4195 'postal_code' => NULL,
4200 $addressFields['civicrm_address']['group_bys'] = array(
4201 'street_address' => NULL,
4203 'postal_code' => NULL,
4204 'state_province_id' => array(
4205 'title' => ts('State/Province'),
4207 'country_id' => array(
4208 'title' => ts('Country'),
4210 'county_id' => array(
4211 'title' => ts('County'),
4215 return $addressFields;
4219 * Do AlterDisplay processing on Address Fields.
4222 * @param array $rows
4223 * @param int $rowNum
4224 * @param string $baseUrl
4225 * @param string $linkText
4229 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4230 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4231 $entryFound = FALSE;
4233 if (array_key_exists('civicrm_address_country_id', $row)) {
4234 if ($value = $row['civicrm_address_country_id']) {
4235 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4237 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4238 "reset=1&force=1&{$criteriaQueryParams}&" .
4239 "country_id_op=in&country_id_value={$value}",
4240 $this->_absoluteUrl
, $this->_id
4242 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4243 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4244 array(1 => $linkText)
4251 if (array_key_exists('civicrm_address_county_id', $row)) {
4252 if ($value = $row['civicrm_address_county_id']) {
4253 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4255 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4256 "reset=1&force=1&{$criteriaQueryParams}&" .
4257 "county_id_op=in&county_id_value={$value}",
4258 $this->_absoluteUrl
, $this->_id
4260 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4261 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4262 array(1 => $linkText)
4268 // handle state province
4269 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4270 if ($value = $row['civicrm_address_state_province_id']) {
4271 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4273 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4274 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4275 $this->_absoluteUrl
, $this->_id
4277 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4278 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4279 array(1 => $linkText)
4290 * Do AlterDisplay processing on Address Fields.
4293 * @param array $rows
4294 * @param int $rowNum
4295 * @param string $baseUrl
4296 * @param string $linkText
4300 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4301 $entryFound = FALSE;
4302 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4303 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4304 $addLinks = array('gender_id' => 'Gender');
4305 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4306 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4307 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4308 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4309 $rowLabels = array();
4310 foreach ($rowValues as $rowValue) {
4312 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4315 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4316 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4317 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4323 $yesNoFields = array(
4324 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4326 foreach ($yesNoFields as $fieldName) {
4327 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4328 // Since these are essentially 'negative fields' it feels like it
4329 // makes sense to only highlight the exceptions hence no 'No'.
4330 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4338 * Adjusts dates passed in to YEAR() for fiscal year.
4340 * @param string $fieldName
4344 public function fiscalYearOffset($fieldName) {
4345 $config = CRM_Core_Config
::singleton();
4346 $fy = $config->fiscalYearStart
;
4347 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4348 ($fy['d'] == 1 && $fy['M'] == 1)
4350 return "YEAR( $fieldName )";
4352 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4353 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4357 * Add Address into From Table if required.
4359 * @deprecated use joinAddressFromContact
4360 * (left here in case extensions use it).
4362 public function addAddressFromClause() {
4363 Civi
::log()->warning('Deprecated function addAddressFromClause. Use joinAddressFromContact.', array('civi.tag' => 'deprecated'));
4364 // include address field if address column is to be included
4365 if ((isset($this->_addressField
) &&
4366 $this->_addressField
4368 $this->isTableSelected('civicrm_address')
4371 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4372 ON ({$this->_aliases['civicrm_contact']}.id =
4373 {$this->_aliases['civicrm_address']}.contact_id) AND
4374 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4379 * Add Phone into From Table if required.
4381 * @deprecated use joinPhoneFromContact
4382 * (left here in case extensions use it).
4384 public function addPhoneFromClause() {
4386 Civi
::log()->warning('Deprecated function addPhoneFromClause. Use joinPhoneFromContact.', array('civi.tag' => 'deprecated'));
4387 // include address field if address column is to be included
4388 if ($this->isTableSelected('civicrm_phone')) {
4390 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4391 ON ({$this->_aliases['civicrm_contact']}.id =
4392 {$this->_aliases['civicrm_phone']}.contact_id) AND
4393 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4398 * Add Address into From Table if required.
4400 * Prefix will be added to both tables as
4401 * it is assumed you are using it to get address of a secondary contact.
4403 * @param string $prefix
4404 * @param array $extra Additional options.
4405 * Not currently used in core but may be used in override extensions.
4407 protected function joinAddressFromContact($prefix = '', $extra = array()) {
4408 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4409 $isJoinRequired = $this->_addressField
;
4410 foreach ($addressTables as $addressTable) {
4411 if ($this->isTableSelected($prefix . $addressTable)) {
4412 $isJoinRequired = TRUE;
4415 if ($isJoinRequired) {
4417 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4418 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4419 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id) AND
4420 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4425 * Add Country into From Table if required.
4427 * Prefix will be added to both tables as
4428 * it is assumed you are using it to get address of a secondary contact.
4430 * @param string $prefix
4431 * @param array $extra Additional options.
4432 * Not currently used in core but may be used in override extensions.
4434 protected function joinCountryFromAddress($prefix = '', $extra = array()) {
4435 // include country field if country column is to be included
4436 if ($this->isTableSelected($prefix . 'civicrm_country') ||
$this->isTableSelected($prefix . 'civicrm_worldregion')) {
4437 if (empty($this->_aliases
[$prefix . 'civicrm_country'])) {
4438 $this->_aliases
[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4441 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4442 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id AND
4443 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4448 * Add Phone into From Table if required.
4450 * Prefix will be added to both tables as
4451 * it is assumed you are using it to get address of a secondary contact.
4453 * @param string $prefix
4454 * @param array $extra Additional options.
4455 * Not currently used in core but may be used in override extensions.
4457 protected function joinPhoneFromContact($prefix = '', $extra = array()) {
4458 // include phone field if phone column is to be included
4459 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4461 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4462 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id AND
4463 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4468 * Add Email into From Table if required.
4470 * Prefix will be added to both tables as
4471 * it is assumed you are using it to get address of a secondary contact.
4473 * @param string $prefix
4474 * @param array $extra Additional options.
4475 * Not currently used in core but may be used in override extensions.
4477 protected function joinEmailFromContact($prefix = '', $extra = array()) {
4478 // include email field if email column is to be included
4479 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4481 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4482 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id AND
4483 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1) ";
4488 * Add Financial Transaction into From Table if required.
4490 public function addFinancialTrxnFromClause() {
4491 if ($this->isTableSelected('civicrm_financial_trxn')) {
4493 LEFT JOIN civicrm_entity_financial_trxn eftcc
4494 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4495 eftcc.entity_table = 'civicrm_contribution')
4496 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4497 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4502 * Get phone columns to add to array.
4504 * @param array $options
4505 * - prefix Prefix to add to table (in case of more than one instance of the table)
4506 * - prefix_label Label to give columns from this phone table instance
4509 * phone columns definition
4511 public function getPhoneColumns($options = array()) {
4512 $defaultOptions = array(
4514 'prefix_label' => '',
4517 $options = array_merge($defaultOptions, $options);
4520 $options['prefix'] . 'civicrm_phone' => array(
4521 'dao' => 'CRM_Core_DAO_Phone',
4523 $options['prefix'] . 'phone' => array(
4524 'title' => $options['prefix_label'] . ts('Phone'),
4534 * Get address columns to add to array.
4536 * @param array $options
4537 * - prefix Prefix to add to table (in case of more than one instance of the table)
4538 * - prefix_label Label to give columns from this address table instance
4541 * address columns definition
4543 public function getAddressColumns($options = array()) {
4546 'prefix_label' => '',
4550 'defaults' => array(),
4552 return $this->addAddressFields(
4553 $options['group_by'],
4554 $options['order_by'],
4555 $options['filters'],
4556 $options['defaults']
4561 * Get a standard set of contact fields.
4565 public function getBasicContactFields() {
4567 'sort_name' => array(
4568 'title' => ts('Contact Name'),
4573 'no_display' => TRUE,
4576 'prefix_id' => array(
4577 'title' => ts('Contact Prefix'),
4579 'first_name' => array(
4580 'title' => ts('First Name'),
4582 'nick_name' => array(
4583 'title' => ts('Nick Name'),
4585 'middle_name' => array(
4586 'title' => ts('Middle Name'),
4588 'last_name' => array(
4589 'title' => ts('Last Name'),
4591 'suffix_id' => array(
4592 'title' => ts('Contact Suffix'),
4594 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4595 'email_greeting_display' => array('title' => ts('Email Greeting')),
4596 'addressee_display' => array('title' => ts('Addressee')),
4597 'contact_type' => array(
4598 'title' => ts('Contact Type'),
4600 'contact_sub_type' => array(
4601 'title' => ts('Contact Subtype'),
4603 'gender_id' => array(
4604 'title' => ts('Gender'),
4606 'birth_date' => array(
4607 'title' => ts('Birth Date'),
4610 'title' => ts('Age'),
4611 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4613 'job_title' => array(
4614 'title' => ts('Contact Job title'),
4616 'organization_name' => array(
4617 'title' => ts('Organization Name'),
4619 'external_identifier' => array(
4620 'title' => ts('Contact identifier from external system'),
4622 'do_not_email' => array(),
4623 'do_not_phone' => array(),
4624 'do_not_mail' => array(),
4625 'do_not_sms' => array(),
4626 'is_opt_out' => array(),
4627 'is_deceased' => array(),
4628 'preferred_language' => array(),
4633 * Get a standard set of contact filters.
4637 public function getBasicContactFilters() {
4639 'sort_name' => array(
4640 'title' => ts('Contact Name'),
4643 'title' => ts('Contact Source'),
4644 'type' => CRM_Utils_Type
::T_STRING
,
4647 'title' => ts('Contact ID'),
4648 'no_display' => TRUE,
4650 'gender_id' => array(
4651 'title' => ts('Gender'),
4652 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4653 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4655 'birth_date' => array(
4656 'title' => ts('Birth Date'),
4657 'operatorType' => CRM_Report_Form
::OP_DATE
,
4659 'contact_type' => array(
4660 'title' => ts('Contact Type'),
4662 'contact_sub_type' => array(
4663 'title' => ts('Contact Subtype'),
4665 'modified_date' => array(
4666 'title' => ts('Contact Modified'),
4667 'operatorType' => CRM_Report_Form
::OP_DATE
,
4668 'type' => CRM_Utils_Type
::T_DATE
,
4670 'is_deceased' => array(
4671 'title' => ts('Deceased'),
4672 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4675 'do_not_email' => array(
4676 'title' => ts('Do not email'),
4677 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4679 'do_not_phone' => array(
4680 'title' => ts('Do not phone'),
4681 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4683 'do_not_mail' => array(
4684 'title' => ts('Do not mail'),
4685 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4687 'do_not_sms' => array(
4688 'title' => ts('Do not SMS'),
4689 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4691 'is_opt_out' => array(
4692 'title' => ts('Do not bulk email'),
4693 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4695 'preferred_language' => array(
4696 'title' => ts('Preferred Language'),
4698 'is_deleted' => array(
4699 'no_display' => TRUE,
4701 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4707 * Add contact to group.
4709 * @param int $groupID
4711 public function add2group($groupID) {
4712 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4713 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4714 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4715 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4716 $sql = str_replace('WITH ROLLUP', '', $sql);
4717 $dao = CRM_Core_DAO
::executeQuery($sql);
4719 $contact_ids = array();
4720 // Add resulting contacts to group
4721 while ($dao->fetch()) {
4722 if ($dao->addtogroup_contact_id
) {
4723 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4727 if (!empty($contact_ids)) {
4728 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4729 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4732 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4738 * Show charts on print screen.
4740 public static function uploadChartImage() {
4741 // upload strictly for '.png' images
4742 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4743 if (preg_match('/\.png$/', $name)) {
4745 // Get the RAW .png from the input.
4746 $httpRawPostData = file_get_contents("php://input");
4748 // prepare the directory
4749 $config = CRM_Core_Config
::singleton();
4751 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4753 if (!file_exists($defaultPath)) {
4754 mkdir($defaultPath, 0777, TRUE);
4757 // full path to the saved image including filename
4758 $destination = $defaultPath . $name;
4761 $jfh = fopen($destination, 'w') or die("can't open file");
4762 fwrite($jfh, $httpRawPostData);
4764 CRM_Utils_System
::civiExit();
4769 * Apply common settings to entityRef fields.
4771 * @param array $field
4772 * @param string $table
4774 private function setEntityRefDefaults(&$field, $table) {
4775 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4776 $field['attributes'] +
= array(
4777 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4779 'placeholder' => ts('- select -'),
4784 * Add link fields to the row.
4786 * Function adds the _link & _hover fields to the row.
4789 * @param string $baseUrl
4790 * @param string $linkText
4791 * @param string $value
4792 * @param string $fieldName
4793 * @param string $tablePrefix
4794 * @param string $fieldLabel
4798 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4799 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4800 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4801 "reset=1&force=1&{$criteriaQueryParams}&" .
4802 $fieldName . "_op=in&{$fieldName}_value={$value}",
4803 $this->_absoluteUrl
, $this->_id
4805 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4806 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4807 array(1 => $linkText, 2 => $fieldLabel)
4812 * Get label for show results buttons.
4816 public function getResultsLabel() {
4817 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4818 return $showResultsLabel;
4822 * Determine the output mode from the url or input.
4825 * - pdf : Render as pdf
4826 * - csv : Render as csv
4827 * - print : Render in print format
4828 * - save : save the report and display the new report
4829 * - copy : save the report as a new instance and display that.
4830 * - group : go to the add to group screen.
4832 * Potentially chart variations could also be included but the complexity
4833 * is that we might print a bar chart as a pdf.
4835 protected function setOutputMode() {
4836 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4839 CRM_Core_DAO
::$_nullObject,
4841 CRM_Utils_Array
::value('task', $this->_params
)
4843 // if contacts are added to group
4844 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4845 $this->_outputMode
= 'group';
4847 if (isset($this->_params
['task'])) {
4848 unset($this->_params
['task']);
4853 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4856 * @param $columnName
4858 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4859 // add new column with date value for the datetime field
4860 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4861 CRM_Core_DAO
::executeQuery($tempQuery);
4862 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4863 CRM_Core_DAO
::executeQuery($updateQuery);
4864 $this->_selectClauses
[] = "{$columnName}_date";
4865 $this->_select
.= ", {$columnName}_date";
4866 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4867 unset($this->_sections
["{$columnName}"]);
4868 $this->assign('sections', $this->_sections
);
4872 * Get an array of the columns that have been selected for display.
4876 public function getSelectColumns() {
4877 $selectColumns = array();
4878 foreach ($this->_columns
as $tableName => $table) {
4879 if (array_key_exists('fields', $table)) {
4880 foreach ($table['fields'] as $fieldName => $field) {
4881 if (!empty($field['required']) ||
4882 !empty($this->_params
['fields'][$fieldName])
4885 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4890 return $selectColumns;
4894 * Add location tables to the query if they are used for filtering.
4896 * This is for when we are running the query separately for filtering and retrieving display fields.
4898 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4899 if ($this->isTableFiltered('civicrm_email')) {
4901 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4902 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4903 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4905 if ($this->isTableFiltered('civicrm_phone')) {
4907 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4908 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4909 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4911 if ($this->isTableFiltered('civicrm_address')) {
4913 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4914 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4915 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4920 * Set the base table for the FROM clause.
4922 * Sets up the from clause, allowing for the possibility it might be a
4923 * temp table pre-filtered by groups if a group filter is in use.
4925 * @param string $baseTable
4926 * @param string $field
4927 * @param null $tableAlias
4929 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4931 $tableAlias = $this->_aliases
[$baseTable];
4933 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4934 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4935 $this->_from
.= " {$this->_aclFrom} ";
4939 * Join the temp table contacting contacts who are members of the filtered groups.
4941 * If we are using an IN filter we use an inner join, otherwise a left join.
4943 * @param string $baseTable
4944 * @param string $field
4945 * @param string $tableAlias
4947 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4948 if ($this->groupTempTable
) {
4949 if ($this->_params
['gid_op'] == 'in') {
4950 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4951 ON group_temp_table.id = $tableAlias.{$field} ";
4955 LEFT JOIN $this->groupTempTable group_temp_table
4956 ON $tableAlias.{$field} = group_temp_table.id ";
4962 * Get all labels for fields that are used in a group concat.
4964 * @param string $options
4965 * comma separated option values.
4966 * @param string $baoName
4967 * The BAO name for the field.
4968 * @param string $fieldName
4969 * The name of the field for which labels should be retrieved.
4973 public function getLabels($options, $baoName, $fieldName) {
4974 $types = explode(',', $options);
4976 foreach ($types as $value) {
4977 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
4979 return implode(', ', array_filter($labels));
4983 * Add statistics columns.
4985 * If a group by is in play then add columns for the statistics fields.
4987 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
4988 * column header field.
4990 * @param array $field
4991 * @param string $tableName
4992 * @param string $fieldName
4993 * @param array $select
4997 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
4998 foreach ($field['statistics'] as $stat => $label) {
4999 $alias = "{$tableName}_{$fieldName}_{$stat}";
5000 switch (strtolower($stat)) {
5003 $select[] = "$stat({$field['dbAlias']}) as $alias";
5004 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5005 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5006 $this->_statFields
[$label] = $alias;
5007 $this->_selectAliases
[] = $alias;
5011 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5012 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5013 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5014 $this->_statFields
[$label] = $alias;
5015 $this->_selectAliases
[] = $alias;
5018 case 'count_distinct':
5019 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5020 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5021 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
5022 $this->_statFields
[$label] = $alias;
5023 $this->_selectAliases
[] = $alias;
5027 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5028 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5029 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5030 $this->_statFields
[$label] = $alias;
5031 $this->_selectAliases
[] = $alias;
5039 * Add a basic field to the select clause.
5041 * @param string $tableName
5042 * @param string $fieldName
5043 * @param array $field
5044 * @param string $select
5047 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5048 $alias = "{$tableName}_{$fieldName}";
5049 $select[] = "{$field['dbAlias']} as $alias";
5050 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
5051 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
5052 $this->_selectAliases
[] = $alias;
5059 * @param array $table
5060 * @param string $tableName
5065 protected function setTableAlias($table, $tableName) {
5066 if (!isset($table['alias'])) {
5067 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
5071 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
5074 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
5075 return $this->_aliases
[$tableName];
5079 * Function to add columns to reports.
5081 * This is ported from extended reports, which also adds join filters to the options.
5083 * @param string $type
5084 * @param array $options
5085 * - prefix - A string to prepend to the table name
5086 * - prefix_label A string to prepend to the fields
5087 * - fields (bool) - should the fields for this table be made available
5088 * - group_by (bool) - should the group bys for this table be made available.
5089 * - order_by (bool) - should the group bys for this table be made available.
5090 * - filters (bool) - should the filters for this table by made available.
5091 * - fields_defaults (array) array of fields that should be displayed by default.
5092 * - filters_defaults (array) array of fields that should be filtered by default.
5093 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5094 * - join_fields (array) fields available from join (requires additional custom code).
5095 * - group_by_defaults (array) array of group bys that should be applied by default.
5096 * - order_by_defaults (array) array of order bys that should be applied by default.
5097 * - custom_fields (array) array of entity types for custom fields (not usually required).
5098 * - contact_type (string) optional restriction on contact type for some tables.
5099 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5103 protected function getColumns($type, $options = array()) {
5104 $defaultOptions = array(
5106 'prefix_label' => '',
5108 'group_bys' => FALSE,
5109 'order_bys' => TRUE,
5111 'join_filters' => FALSE,
5112 'fields_defaults' => array(),
5113 'filters_defaults' => array(),
5114 'group_bys_defaults' => array(),
5115 'order_bys_defaults' => array(),
5117 $options = array_merge($defaultOptions, $options);
5119 $fn = 'get' . $type . 'Columns';
5120 return $this->$fn($options);
5124 * Get columns for contact table.
5126 * @param array $options
5130 protected function getContactColumns($options = array()) {
5131 $defaultOptions = array(
5132 'custom_fields' => array('Individual', 'Contact', 'Organization'),
5133 'fields_defaults' => array('display_name', 'id'),
5134 'order_bys_defaults' => array('sort_name ASC'),
5135 'contact_type' => NULL,
5138 $options = array_merge($defaultOptions, $options);
5140 $tableAlias = $options['prefix'] . 'contact';
5143 $options['prefix'] . 'display_name' => array(
5144 'name' => 'display_name',
5145 'title' => $options['prefix_label'] . ts('Contact Name'),
5146 'is_fields' => TRUE,
5148 $options['prefix'] . 'sort_name' => array(
5149 'name' => 'sort_name',
5150 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5151 'is_fields' => TRUE,
5152 'is_filters' => TRUE,
5153 'is_order_bys' => TRUE,
5155 $options['prefix'] . 'id' => array(
5157 'title' => $options['prefix_label'] . ts('Contact ID'),
5158 'alter_display' => 'alterContactID',
5159 'type' => CRM_Utils_Type
::T_INT
,
5160 'is_order_bys' => TRUE,
5161 'is_group_bys' => TRUE,
5162 'is_fields' => TRUE,
5164 $options['prefix'] . 'external_identifier' => array(
5165 'name' => 'external_identifier',
5166 'title' => $options['prefix_label'] . ts('External ID'),
5167 'type' => CRM_Utils_Type
::T_INT
,
5168 'is_fields' => TRUE,
5170 $options['prefix'] . 'contact_type' => array(
5171 'title' => $options['prefix_label'] . ts('Contact Type'),
5172 'name' => 'contact_type',
5173 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5174 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5175 'is_fields' => TRUE,
5176 'is_filters' => TRUE,
5177 'is_group_bys' => TRUE,
5179 $options['prefix'] . 'contact_sub_type' => array(
5180 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5181 'name' => 'contact_sub_type',
5182 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5183 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5184 'is_fields' => TRUE,
5185 'is_filters' => TRUE,
5186 'is_group_bys' => TRUE,
5188 $options['prefix'] . 'is_deleted' => array(
5189 'title' => $options['prefix_label'] . ts('Is deleted'),
5190 'name' => 'is_deleted',
5191 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5192 'is_fields' => FALSE,
5193 'is_filters' => TRUE,
5194 'is_group_bys' => FALSE,
5197 $individualFields = array(
5198 $options['prefix'] . 'first_name' => array(
5199 'name' => 'first_name',
5200 'title' => $options['prefix_label'] . ts('First Name'),
5201 'is_fields' => TRUE,
5202 'is_filters' => TRUE,
5203 'is_order_bys' => TRUE,
5205 $options['prefix'] . 'middle_name' => array(
5206 'name' => 'middle_name',
5207 'title' => $options['prefix_label'] . ts('Middle Name'),
5208 'is_fields' => TRUE,
5210 $options['prefix'] . 'last_name' => array(
5211 'name' => 'last_name',
5212 'title' => $options['prefix_label'] . ts('Last Name'),
5213 'default_order' => 'ASC',
5214 'is_fields' => TRUE,
5216 $options['prefix'] . 'nick_name' => array(
5217 'name' => 'nick_name',
5218 'title' => $options['prefix_label'] . ts('Nick Name'),
5219 'is_fields' => TRUE,
5221 $options['prefix'] . 'gender_id' => array(
5222 'name' => 'gender_id',
5223 'title' => $options['prefix_label'] . ts('Gender'),
5224 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5225 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5226 'alter_display' => 'alterGenderID',
5227 'is_fields' => TRUE,
5228 'is_filters' => TRUE,
5230 'birth_date' => array(
5231 'title' => $options['prefix_label'] . ts('Birth Date'),
5232 'operatorType' => CRM_Report_Form
::OP_DATE
,
5233 'type' => CRM_Utils_Type
::T_DATE
,
5234 'is_fields' => TRUE,
5235 'is_filters' => TRUE,
5238 'title' => $options['prefix_label'] . ts('Age'),
5239 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '.birth_date, CURDATE())',
5240 'type' => CRM_Utils_Type
::T_INT
,
5241 'is_fields' => TRUE,
5243 $options['prefix'] . 'is_deceased' => array(
5244 'title' => $options['prefix_label'] . ts('Is deceased'),
5245 'name' => 'is_deceased',
5246 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5247 'is_fields' => FALSE,
5248 'is_filters' => TRUE,
5249 'is_group_bys' => FALSE,
5252 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5253 $spec = array_merge($spec, $individualFields);
5256 if (!empty($options['custom_fields'])) {
5257 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = array(
5258 'extends' => $options['custom_fields'],
5259 'title' => $options['prefix_label'],
5260 'filters' => $options['filters'],
5261 'prefix' => $options['prefix'],
5262 'prefix_label' => $options['prefix_label'],
5266 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5270 * Build the columns.
5272 * The normal report class needs you to remember to do a few things that are often erratic
5274 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5275 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5276 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5277 * means any saved filters / fields on saved report instances. This will mean that matching names from
5278 * different tables may be ambigious, but it will smooth any code transition.
5279 * - note that it assumes the value being passed in is the actual table field name
5281 * 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
5282 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5284 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5285 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5286 * the core classes can start to move towards that.
5288 * @param array $specs
5289 * @param string $tableName
5290 * @param string $daoName
5291 * @param string $tableAlias
5292 * @param array $defaults
5293 * @param array $options
5297 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = array(), $options = array()) {
5299 $tableAlias = str_replace('civicrm_', '', $tableName);
5301 $types = array('filters', 'group_bys', 'order_bys', 'join_filters');
5302 $columns = array($tableName => array_fill_keys($types, array()));
5303 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5304 $columns[$tableName]['dao'] = $daoName;
5305 $columns[$tableName]['alias'] = $tableAlias;
5307 foreach ($specs as $specName => $spec) {
5308 if (empty($spec['name'])) {
5309 $spec['name'] = $specName;
5312 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5313 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5314 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5315 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5316 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5319 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5320 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5323 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5324 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5327 foreach ($types as $type) {
5328 if ($options[$type] && !empty($spec['is_' . $type])) {
5329 $columns[$tableName][$type][$fieldAlias] = $spec;
5330 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5331 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5340 * Store group bys into array - so we can check elsewhere what is grouped.
5342 protected function storeGroupByArray() {
5344 if (!CRM_Utils_Array
::value('group_bys', $this->_params
)
5345 ||
!is_array($this->_params
['group_bys'])) {
5346 $this->_params
['group_bys'] = [];
5349 foreach ($this->_columns
as $tableName => $table) {
5350 $table = $this->_columns
[$tableName];
5351 if (array_key_exists('group_bys', $table)) {
5352 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5353 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5354 if (!empty($this->_params
['group_bys'][$fieldName]) ||
!empty($fieldData['required'])) {
5355 if (!empty($field['chart'])) {
5356 $this->assign('chartSupported', TRUE);
5359 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5360 !empty($this->_params
['group_bys_freq'][$fieldName])
5363 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5365 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5368 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
5371 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_{$this->_params['group_bys_freq'][$fieldName]} FROM {$field['dbAlias']})";
5376 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5377 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5392 protected function getDefaultsFromOptions($options) {
5394 'fields_defaults' => $options['fields_defaults'],
5395 'filters_defaults' => $options['filters_defaults'],
5396 'group_bys_defaults' => $options['group_bys_defaults'],
5397 'order_bys_defaults' => $options['order_bys_defaults'],
5403 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5405 * Full group by mode dictates that a field must either be in the group by function or
5406 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5409 * @param string $tableName
5410 * @param string $fieldName
5411 * @param string $field
5414 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5415 if ($this->groupConcatTested
&& (!empty($this->_groupByArray
) ||
$this->isForceGroupBy
)) {
5416 if ((empty($field['statistics']) ||
in_array('GROUP_CONCAT', $field['statistics']))) {
5417 $label = CRM_Utils_Array
::value('title', $field);
5418 $alias = "{$tableName}_{$fieldName}";
5419 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $label;
5420 $this->_selectAliases
[] = $alias;
5421 if (empty($this->_groupByArray
[$tableName . '_' . $fieldName])) {
5422 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5424 return "({$field['dbAlias']}) as $alias";