3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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;
207 * An attribute for checkbox/radio form field layout
211 protected $_fourColumnAttribute = array(
212 '</td><td width="25%">',
213 '</td><td width="25%">',
214 '</td><td width="25%">',
218 protected $_force = 1;
220 protected $_params = NULL;
221 protected $_formValues = NULL;
222 protected $_instanceValues = NULL;
224 protected $_instanceForm = FALSE;
225 protected $_criteriaForm = FALSE;
227 protected $_instanceButtonName = NULL;
228 protected $_createNewButtonName = NULL;
229 protected $_printButtonName = NULL;
230 protected $_pdfButtonName = NULL;
231 protected $_csvButtonName = NULL;
232 protected $_groupButtonName = NULL;
233 protected $_chartButtonName = NULL;
234 protected $_csvSupported = TRUE;
235 protected $_add2groupSupported = TRUE;
236 protected $_groups = NULL;
237 protected $_grandFlag = FALSE;
238 protected $_rowsFound = NULL;
239 protected $_selectAliases = array();
240 protected $_rollup = NULL;
243 * Table containing list of contact IDs within the group filter.
247 protected $groupTempTable = '';
252 protected $_aliases = array();
268 protected $_limit = NULL;
271 * This can be set to specify a limit to the number of rows
272 * Since it is currently envisaged as part of the api usage it is only being applied
273 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
274 * of the code (see limit() fn.
278 protected $_limitValue = NULL;
281 * This can be set to specify row offset
282 * See notes on _limitValue
285 protected $_offsetValue = NULL;
289 protected $_sections = NULL;
290 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
291 protected $_absoluteUrl = FALSE;
294 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
298 protected $_storeResultSet = FALSE;
301 * When _storeResultSet Flag is set use this var to store result set in form of array
305 protected $_resultSet = array();
308 * To what frequency group-by a date column
312 protected $_groupByDateFreq = array(
314 'YEARWEEK' => 'Week',
315 'QUARTER' => 'Quarter',
320 * Variables to hold the acl inner join and where clause
322 protected $_aclFrom = NULL;
323 protected $_aclWhere = NULL;
326 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
328 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
332 protected $_selectedTables = array();
335 * Array of DAO tables having columns included in WHERE or HAVING clause
339 protected $filteredTables;
342 * Output mode e.g 'print', 'csv', 'pdf'.
346 protected $_outputMode;
349 * Format of any chart in use.
351 * (it's unclear if this could be merged with outputMode at this stage)
357 public $_having = NULL;
358 public $_select = NULL;
359 public $_selectClauses = array();
360 public $_columnHeaders = array();
361 public $_orderBy = NULL;
362 public $_orderByFields = array();
363 public $_orderByArray = array();
364 public $_groupBy = NULL;
365 public $_whereClauses = array();
366 public $_havingClauses = array();
369 * DashBoardRowCount Dashboard row count
372 public $_dashBoardRowCount;
375 * Is this being called without a form controller (ie. the report is being render outside the normal form
376 * - e.g the api is retrieving the rows
379 public $noController = FALSE;
382 * Variable to hold the currency alias
384 protected $_currencyColumn = NULL;
389 protected $_interval;
394 protected $_sendmail;
407 * @var string Report description.
409 public $_description;
412 * @var bool Is an address field selected.
413 * This was intended to determine if the address table should be joined in
414 * The isTableSelected function is now preferred for this purpose
416 protected $_addressField;
419 * @var bool Is an email field selected.
420 * This was intended to determine if the email table should be joined in
421 * The isTableSelected function is now preferred for this purpose
423 protected $_emailField;
426 * @var bool Is a phone field selected.
427 * This was intended to determine if the phone table should be joined in
428 * The isTableSelected function is now preferred for this purpose
430 protected $_phoneField;
433 * @var bool Create new report instance? (or update existing) on save.
435 protected $_createNew;
438 * When a grand total row has calculated the status we pop it off to here.
440 * This allows us to access it from the stats function and avoid recalculating.
442 protected $rollupRow = array();
445 * @var string Database attributes - character set and collation
447 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
450 * SQL being run in this report.
452 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
460 * SQL being run in this report as an array.
462 * The sql in the report is stored in this variable in order to be returned to api & test calls.
471 public function __construct() {
472 parent
::__construct();
474 $this->addClass('crm-report-form');
476 if ($this->_tagFilter
) {
477 $this->buildTagFilter();
479 if ($this->_exposeContactID
) {
480 if (array_key_exists('civicrm_contact', $this->_columns
)) {
481 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
483 'title' => ts('Contact ID'),
489 if ($this->_groupFilter
) {
490 $this->buildGroupFilter();
493 // Get all custom groups
494 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
496 // Get the custom groupIds for which the user has VIEW permission
497 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
498 // and addCustomDataToColumns() will allow access to all custom groups.
499 $permCustomGroupIds = array();
500 if (!CRM_Core_Permission
::check('access all custom data')) {
501 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
502 // do not allow custom data for reports if user doesn't have
503 // permission to access custom data.
504 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
505 $this->_customGroupExtends
= array();
509 // merge custom data columns to _columns list, if any
510 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
512 // add / modify display columns, filters ..etc
513 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
515 //assign currencyColumn variable to tpl
516 $this->assign('currencyColumn', $this->_currencyColumn
);
520 * Shared pre-process function.
522 * If overriding preProcess function this should still be called.
526 public function preProcessCommon() {
527 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
529 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
531 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
533 $this->assign('section', $this->_section
);
534 CRM_Core_Region
::instance('page-header')->add(array(
535 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
537 if (!$this->noController
) {
538 $this->setID($this->get('instanceId'));
541 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
543 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
547 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
548 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
549 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
553 $this->assign('instanceId', $this->_id
);
554 $params = array('id' => $this->_id
);
555 $this->_instanceValues
= array();
556 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
558 $this->_instanceValues
560 if (empty($this->_instanceValues
)) {
561 CRM_Core_Error
::fatal("Report could not be loaded.");
563 $this->_title
= $this->_instanceValues
['title'];
564 if (!empty($this->_instanceValues
['permission']) &&
565 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
566 CRM_Core_Permission
::check('administer Reports')
569 CRM_Utils_System
::permissionDenied();
570 CRM_Utils_System
::civiExit();
573 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
575 $this->_formValues
= unserialize($formValues);
578 $this->_formValues
= NULL;
581 $this->setOutputMode();
583 if ($this->_outputMode
== 'copy') {
584 $this->_createNew
= TRUE;
585 $this->_params
= $this->_formValues
;
586 $this->_params
['view_mode'] = 'criteria';
587 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
588 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
589 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
591 // Do not pass go. Do not collect another chance to re-run the same query.
592 CRM_Report_Form_Instance
::postProcess($this);
595 // lets always do a force if reset is found in the url.
596 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
597 // in the comment line above these 2.
598 if (!empty($_REQUEST['reset'])
599 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
604 $this->assign('mode', 'instance');
606 elseif (!$this->noController
) {
607 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
608 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
609 if (($instanceCount > 0) && $optionValueID) {
610 $this->assign('instanceUrl',
611 CRM_Utils_System
::url('civicrm/report/list',
612 "reset=1&ovid=$optionValueID"
616 if ($optionValueID) {
617 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
621 $this->assign('mode', 'template');
624 // lets display the Report Settings section
625 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
627 // Do not display Report Settings section if administer Reports permission is absent OR
628 // if report instance is reserved and administer reserved reports absent
629 if (!CRM_Core_Permission
::check('administer Reports') ||
630 ($this->_instanceValues
['is_reserved'] &&
631 !CRM_Core_Permission
::check('administer reserved reports'))
633 $this->_instanceForm
= FALSE;
636 $this->assign('criteriaForm', FALSE);
637 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
638 if (CRM_Core_Permission
::check('administer Reports') ||
639 CRM_Core_Permission
::check('access Report Criteria')
641 if (!$this->_instanceValues
['is_reserved'] ||
642 CRM_Core_Permission
::check('administer reserved reports')
644 $this->assign('criteriaForm', TRUE);
645 $this->_criteriaForm
= TRUE;
649 // Special permissions check for private instance if it's not the current contact instance
651 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
652 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
653 if (!CRM_Core_Permission
::check('access all private reports')) {
654 $this->_instanceForm
= FALSE;
655 $this->assign('criteriaForm', FALSE);
659 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
660 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
661 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
662 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
668 public function addBreadCrumb() {
672 'title' => ts('Report Templates'),
673 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
677 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
681 * Pre process function.
683 * Called prior to build form.
685 public function preProcess() {
686 $this->preProcessCommon();
689 $this->addBreadCrumb();
692 foreach ($this->_columns
as $tableName => $table) {
694 if (!isset($table['alias'])) {
695 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
699 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
702 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
704 $expFields = array();
705 // higher preference to bao object
706 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
709 if (method_exists($daoOrBaoName, 'exportableFields')) {
710 $expFields = $daoOrBaoName::exportableFields();
713 $expFields = $daoOrBaoName::export();
717 $doNotCopy = array('required');
719 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
720 foreach ($fieldGroups as $fieldGrp) {
721 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
722 foreach ($table[$fieldGrp] as $fieldName => $field) {
723 // $name is the field name used to reference the BAO/DAO export fields array
724 $name = isset($field['name']) ?
$field['name'] : $fieldName;
726 // Sometimes the field name key in the BAO/DAO export fields array is
727 // different from the actual database field name.
728 // Unset $field['name'] so that actual database field name can be obtained
729 // from the BAO/DAO export fields array.
730 unset($field['name']);
732 if (array_key_exists($name, $expFields)) {
733 foreach ($doNotCopy as $dnc) {
734 // unset the values we don't want to be copied.
735 unset($expFields[$name][$dnc]);
738 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
741 foreach ($expFields[$name] as $property => $val) {
742 if (!array_key_exists($property, $field)) {
743 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
750 if (!empty($field['no_repeat'])) {
751 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
753 if (!empty($field['no_display'])) {
754 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
757 // set alias = table-name, unless already set
758 $alias = isset($field['alias']) ?
$field['alias'] : (
759 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
761 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
763 // set name = fieldName, unless already set
764 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
765 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
768 // set dbAlias = alias.name, unless already set
769 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
770 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
772 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
775 // a few auto fills for filters
776 if ($fieldGrp == 'filters') {
777 // fill operator types
778 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
779 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
780 case CRM_Utils_Type
::T_MONEY
:
781 case CRM_Utils_Type
::T_FLOAT
:
782 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
785 case CRM_Utils_Type
::T_INT
:
786 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
789 case CRM_Utils_Type
::T_DATE
:
790 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
793 case CRM_Utils_Type
::T_BOOLEAN
:
794 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
795 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
796 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
807 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
809 // with multiple options operator-type is generally multi-select
810 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
811 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
813 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
824 // copy filters to a separate handy variable
825 if (array_key_exists('filters', $table)) {
826 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
829 if (array_key_exists('group_bys', $table)) {
830 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
833 if (array_key_exists('fields', $table)) {
834 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
839 $this->setDefaultValues(FALSE);
842 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
843 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
844 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
845 CRM_Report_Utils_Get
::processChart($this->_defaults
);
848 $this->_formValues
= $this->_defaults
;
849 $this->postProcess();
854 * Set default values.
856 * @param bool $freeze
860 public function setDefaultValues($freeze = TRUE) {
861 $freezeGroup = array();
863 // FIXME: generalizing form field naming conventions would reduce
864 // Lots of lines below.
865 foreach ($this->_columns
as $tableName => $table) {
866 if (array_key_exists('fields', $table)) {
867 foreach ($table['fields'] as $fieldName => $field) {
868 if (empty($field['no_display'])) {
869 if (isset($field['required'])) {
871 $this->_defaults
['fields'][$fieldName] = 1;
874 // find element object, so that we could use quickform's freeze method
875 // for required elements
876 $obj = $this->getElementFromGroup("fields", $fieldName);
878 $freezeGroup[] = $obj;
882 elseif (isset($field['default'])) {
883 $this->_defaults
['fields'][$fieldName] = $field['default'];
889 if (array_key_exists('group_bys', $table)) {
890 foreach ($table['group_bys'] as $fieldName => $field) {
891 if (isset($field['default'])) {
892 if (!empty($field['frequency'])) {
893 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
895 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
899 if (array_key_exists('filters', $table)) {
900 foreach ($table['filters'] as $fieldName => $field) {
901 if (isset($field['default'])) {
902 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
904 if (is_array($field['default'])) {
905 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
906 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
907 $this->_defaults
["{$fieldName}_relative"] = 0;
910 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
914 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
915 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
916 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
918 $this->_defaults
["{$fieldName}_value"] = $field['default'];
921 //assign default value as "in" for multiselect
922 //operator, To freeze the select element
923 if (CRM_Utils_Array
::value('operatorType', $field) ==
924 CRM_Report_Form
::OP_MULTISELECT
926 $this->_defaults
["{$fieldName}_op"] = 'in';
928 if (CRM_Utils_Array
::value('operatorType', $field) ==
929 CRM_Report_Form
::OP_ENTITYREF
931 $this->_defaults
["{$fieldName}_op"] = 'in';
933 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
934 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
936 $this->_defaults
["{$fieldName}_op"] = 'mhas';
938 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
939 $this->_defaults
["{$fieldName}_op"] = $op;
945 empty($this->_formValues
['order_bys']) &&
946 (array_key_exists('order_bys', $table) &&
947 is_array($table['order_bys']))
949 if (!array_key_exists('order_bys', $this->_defaults
)) {
950 $this->_defaults
['order_bys'] = array();
952 foreach ($table['order_bys'] as $fieldName => $field) {
953 if (!empty($field['default']) ||
!empty($field['default_order']) ||
954 CRM_Utils_Array
::value('default_is_section', $field) ||
955 !empty($field['default_weight'])
958 'column' => $fieldName,
959 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
960 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
963 if (!empty($field['default_weight'])) {
964 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
967 array_unshift($this->_defaults
['order_bys'], $order_by);
973 foreach ($this->_options
as $fieldName => $field) {
974 if (isset($field['default'])) {
975 $this->_defaults
['options'][$fieldName] = $field['default'];
980 if (!empty($this->_submitValues
)) {
981 $this->preProcessOrderBy($this->_submitValues
);
984 $this->preProcessOrderBy($this->_defaults
);
987 // lets finish freezing task here itself
988 if (!empty($freezeGroup)) {
989 foreach ($freezeGroup as $elem) {
994 if ($this->_formValues
) {
995 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
998 if ($this->_instanceValues
) {
999 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1002 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1004 return $this->_defaults
;
1008 * Get element from group.
1010 * @param string $group
1011 * @param string $grpFieldName
1015 public function getElementFromGroup($group, $grpFieldName) {
1016 $eleObj = $this->getElement($group);
1017 foreach ($eleObj->_elements
as $index => $obj) {
1018 if ($grpFieldName == $obj->_attributes
['name']) {
1026 * Setter for $_params.
1028 * @param array $params
1030 public function setParams($params) {
1031 $this->_params
= $params;
1037 * @param int $instanceID
1039 public function setID($instanceID) {
1040 $this->_id
= $instanceID;
1044 * Setter for $_force.
1046 * @param bool $isForce
1048 public function setForce($isForce) {
1049 $this->_force
= $isForce;
1053 * Setter for $_limitValue.
1055 * @param int $_limitValue
1057 public function setLimitValue($_limitValue) {
1058 $this->_limitValue
= $_limitValue;
1062 * Setter for $_offsetValue.
1064 * @param int $_offsetValue
1066 public function setOffsetValue($_offsetValue) {
1067 $this->_offsetValue
= $_offsetValue;
1071 * Setter for $addPaging.
1073 * @param bool $value
1075 public function setAddPaging($value) {
1076 $this->addPaging
= $value;
1080 * Getter for $_defaultValues.
1084 public function getDefaultValues() {
1085 return $this->_defaults
;
1089 * Add columns to report.
1091 public function addColumns() {
1094 foreach ($this->_columns
as $tableName => $table) {
1095 if (array_key_exists('fields', $table)) {
1096 foreach ($table['fields'] as $fieldName => $field) {
1098 if (empty($field['no_display'])) {
1099 foreach (array('table', 'field') as $var) {
1100 if (!empty($
{$var}['grouping'])) {
1101 if (!is_array($
{$var}['grouping'])) {
1102 $tableName = $
{$var}['grouping'];
1105 $tableName = array_keys($
{$var}['grouping']);
1106 $tableName = $tableName[0];
1107 $groupTitle = array_values($
{$var}['grouping']);
1108 $groupTitle = $groupTitle[0];
1113 if (!$groupTitle && isset($table['group_title'])) {
1114 $groupTitle = $table['group_title'];
1115 // Having a group_title is secret code for being a custom group
1116 // which cryptically translates to needing an accordion.
1117 // here we make that explicit.
1118 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1121 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1122 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1123 $colGroups[$tableName]['group_title'] = $groupTitle;
1125 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1131 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1132 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1134 if (!empty($colGroups)) {
1135 $this->tabs
['FieldSelection'] = array(
1136 'title' => ts('Columns'),
1137 'tpl' => 'FieldSelection',
1138 'div_label' => 'col-groups',
1141 // Note this assignment is only really required in buildForm. It is being 'over-called'
1142 // to reduce risk of being missed due to overridden functions.
1143 $this->assign('tabs', $this->tabs
);
1146 $this->assign('colGroups', $colGroups);
1150 * Add filters to report.
1152 public function addFilters() {
1153 $filters = $filterGroups = array();
1156 foreach ($this->_filters
as $table => $attributes) {
1157 if (isset($this->_columns
[$table]['group_title'])) {
1158 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1159 // which magically means to 'display in an accordian'
1160 // here we make this explicit.
1161 $filterGroups[$table] = array(
1162 'group_title' => $this->_columns
[$table]['group_title'],
1163 'use_accordian_for_field_selection' => TRUE,
1167 foreach ($attributes as $fieldName => $field) {
1168 // get ready with option value pair
1169 // @ 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
1171 $operations = $this->getOperationPair(
1172 CRM_Utils_Array
::value('operatorType', $field),
1175 $filters[$table][$fieldName] = $field;
1177 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1178 case CRM_Report_Form
::OP_MONTH
:
1179 if (!array_key_exists('options', $field) ||
1180 !is_array($field['options']) ||
empty($field['options'])
1182 // If there's no option list for this filter, define one.
1183 $field['options'] = array(
1185 2 => ts('February'),
1192 9 => ts('September'),
1193 10 => ts('October'),
1194 11 => ts('November'),
1195 12 => ts('December'),
1197 // Add this option list to this column _columns. This is
1198 // required so that filter statistics show properly.
1199 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1201 case CRM_Report_Form
::OP_MULTISELECT
:
1202 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1203 // assume a multi-select field
1204 if (!empty($field['options']) ||
1205 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1207 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1208 if (count($operations) <= 1) {
1211 if ($fieldName == 'state_province_id' ||
1212 $fieldName == 'county_id'
1214 $this->addChainSelect($fieldName . '_value', array(
1221 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1222 'style' => 'min-width:250px',
1223 'class' => 'crm-select2 huge',
1225 'placeholder' => ts('- select -'),
1231 case CRM_Report_Form
::OP_SELECT
:
1232 // assume a select field
1233 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1234 if (!empty($field['options'])) {
1235 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1239 case CRM_Report_Form
::OP_ENTITYREF
:
1240 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1241 $this->setEntityRefDefaults($field, $table);
1242 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1245 case CRM_Report_Form
::OP_DATE
:
1246 // build datetime fields
1247 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1251 case CRM_Report_Form
::OP_DATETIME
:
1252 // build datetime fields
1253 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1257 case CRM_Report_Form
::OP_INT
:
1258 case CRM_Report_Form
::OP_FLOAT
:
1259 // and a min value input box
1260 $this->add('text', "{$fieldName}_min", ts('Min'));
1261 // and a max value input box
1262 $this->add('text', "{$fieldName}_max", ts('Max'));
1264 // default type is string
1265 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1266 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1268 // we need text box for value input
1269 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1274 if (!empty($filters)) {
1275 $this->tabs
['Filters'] = array(
1276 'title' => ts('Filters'),
1278 'div_label' => 'set-filters',
1281 $this->assign('filters', $filters);
1282 $this->assign('filterGroups', $filterGroups);
1286 * Function to assign the tabs to the template in the correct order.
1288 * We want the tabs to wind up in this order (if not overridden).
1296 protected function assignTabs() {
1304 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1305 $order = array_merge($order, $this->tabs
);
1306 $this->assign('tabs', $order);
1310 * The intent is to add a tab for developers to view the sql.
1312 * Currently using dpm.
1314 * @param string $sql
1316 protected function addToDeveloperTab($sql) {
1317 if (!CRM_Core_Permission
::check('view report sql')) {
1320 $this->tabs
['Developer'] = array(
1321 'title' => ts('Developer'),
1322 'tpl' => 'Developer',
1323 'div_label' => 'set-developer',
1326 $this->assignTabs();
1327 $this->sqlArray
[] = $sql;
1328 foreach ($this->sqlArray
as $sql) {
1329 foreach (array('LEFT JOIN') as $term) {
1330 $sql = str_replace($term, '<br>  ' . $term, $sql);
1332 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1333 $sql = str_replace($term, '<br><br>' . $term, $sql);
1335 $this->sqlFormattedArray
[] = $sql;
1336 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1341 * Add options defined in $this->_options to the report.
1343 public function addOptions() {
1344 if (!empty($this->_options
)) {
1345 // FIXME: For now lets build all elements as checkboxes.
1346 // Once we clear with the format we can build elements based on type
1348 foreach ($this->_options
as $fieldName => $field) {
1351 if ($field['type'] == 'select') {
1352 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1354 elseif ($field['type'] == 'checkbox') {
1355 $options[$field['title']] = $fieldName;
1356 $this->addCheckBox($fieldName, NULL,
1358 NULL, NULL, NULL, $this->_fourColumnAttribute
1363 if (!empty($this->_options
) &&
1365 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1367 $this->tabs
['ReportOptions'] = array(
1368 'title' => ts('Display Options'),
1369 'tpl' => 'ReportOptions',
1370 'div_label' => 'other-options',
1373 $this->assign('otherOptions', $this->_options
);
1377 * Add chart options to the report.
1379 public function addChartOptions() {
1380 if (!empty($this->_charts
)) {
1381 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1382 $this->assign('charts', $this->_charts
);
1383 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1388 * Add group by options to the report.
1390 public function addGroupBys() {
1391 $options = $freqElements = array();
1393 foreach ($this->_columns
as $tableName => $table) {
1394 if (array_key_exists('group_bys', $table)) {
1395 foreach ($table['group_bys'] as $fieldName => $field) {
1396 if (!empty($field)) {
1397 $options[$field['title']] = $fieldName;
1398 if (!empty($field['frequency'])) {
1399 $freqElements[$field['title']] = $fieldName;
1405 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1406 NULL, NULL, NULL, $this->_fourColumnAttribute
1408 $this->assign('groupByElements', $options);
1409 if (!empty($options)) {
1410 $this->tabs
['GroupBy'] = array(
1411 'title' => ts('Grouping'),
1413 'div_label' => 'group-by-elements',
1417 foreach ($freqElements as $name) {
1418 $this->addElement('select', "group_bys_freq[$name]",
1419 ts('Frequency'), $this->_groupByDateFreq
1425 * Add data for order by tab.
1427 public function addOrderBys() {
1429 foreach ($this->_columns
as $tableName => $table) {
1431 // Report developer may define any column to order by; include these as order-by options.
1432 if (array_key_exists('order_bys', $table)) {
1433 foreach ($table['order_bys'] as $fieldName => $field) {
1434 if (!empty($field)) {
1435 $options[$fieldName] = $field['title'];
1440 // Add searchable custom fields as order-by options, if so requested
1441 // (These are already indexed, so allowing to order on them is cheap.)
1443 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1444 array_key_exists('extends', $table) && !empty($table['extends'])
1446 foreach ($table['fields'] as $fieldName => $field) {
1447 if (empty($field['no_display'])) {
1448 $options[$fieldName] = $field['title'];
1456 $this->assign('orderByOptions', $options);
1457 if (!empty($options)) {
1458 $this->tabs
['OrderBy'] = array(
1459 'title' => ts('Sorting'),
1461 'div_label' => 'order-by-elements',
1465 if (!empty($options)) {
1467 '-' => ' - none - ',
1469 for ($i = 1; $i <= 5; $i++
) {
1470 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1471 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1472 'ASC' => ts('Ascending'),
1473 'DESC' => ts('Descending'),
1475 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1476 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1482 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1484 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1485 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1488 public function buildInstanceAndButtons() {
1489 CRM_Report_Form_Instance
::buildForm($this);
1490 $this->_actionButtonName
= $this->getButtonName('submit');
1491 $this->addTaskMenu($this->getActions($this->_id
));
1493 $this->assign('instanceForm', $this->_instanceForm
);
1495 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1496 $permission = CRM_Core_Permission
::getPermission();
1497 if ($permission == CRM_Core_Permission
::EDIT
&&
1498 $this->_add2groupSupported
1500 $this->addElement('select', 'groups', ts('Group'),
1501 array('' => ts('Add Contacts to Group')) +
1502 CRM_Core_PseudoConstant
::nestedGroup(),
1503 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1505 $this->assign('group', TRUE);
1508 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1510 $this->addChartOptions();
1511 $showResultsLabel = $this->getResultsLabel();
1512 $this->addButtons(array(
1515 'name' => $showResultsLabel,
1516 'isDefault' => TRUE,
1523 * Has this form been submitted already?
1527 public function resultsDisplayed() {
1528 $buttonName = $this->controller
->getButtonName();
1529 return ($buttonName ||
$this->_outputMode
);
1533 * Get the actions for this report instance.
1535 * @param int $instanceId
1539 protected function getActions($instanceId) {
1540 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1541 if (empty($instanceId)) {
1542 $actions['report_instance.save'] = array(
1543 'title' => ts('Create Report'),
1545 'is_confirm' => TRUE,
1546 'confirm_title' => ts('Create Report'),
1547 'confirm_refresh_fields' => json_encode(array(
1548 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1549 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1555 if (!$this->_csvSupported
) {
1556 unset($actions['report_instance.csv']);
1563 * Main build form function.
1565 public function buildQuickForm() {
1566 $this->addColumns();
1568 $this->addFilters();
1570 $this->addOptions();
1572 $this->addGroupBys();
1574 $this->addOrderBys();
1576 $this->buildInstanceAndButtons();
1578 // Add form rule for report.
1579 if (is_callable(array(
1583 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1585 $this->assignTabs();
1589 * A form rule function for custom data.
1591 * The rule ensures that fields selected in group_by if any) should only be the ones
1592 * present in display/select fields criteria;
1593 * note: works if and only if any custom field selected in group_by.
1595 * @param array $fields
1596 * @param array $ignoreFields
1600 public function customDataFormRule($fields, $ignoreFields = array()) {
1602 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1603 !empty($fields['group_bys'])
1605 foreach ($this->_columns
as $tableName => $table) {
1606 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1607 substr($tableName, 0, 12) == 'custom_value') &&
1608 !empty($this->_columns
[$tableName]['fields'])
1610 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1611 if (array_key_exists($fieldName, $fields['group_bys']) &&
1612 !array_key_exists($fieldName, $fields['fields'])
1614 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1616 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1617 foreach ($fields['fields'] as $fld => $val) {
1618 if (!array_key_exists($fld, $fields['group_bys']) &&
1619 !in_array($fld, $ignoreFields)
1621 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1633 * Get operators to display on form.
1635 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1637 * @param string $type
1638 * @param string $fieldName
1642 public function getOperationPair($type = "string", $fieldName = NULL) {
1643 // FIXME: At some point we should move these key-val pairs
1644 // to option_group and option_value table.
1646 case CRM_Report_Form
::OP_INT
:
1647 case CRM_Report_Form
::OP_FLOAT
:
1650 'lte' => ts('Is less than or equal to'),
1651 'gte' => ts('Is greater than or equal to'),
1652 'bw' => ts('Is between'),
1653 'eq' => ts('Is equal to'),
1654 'lt' => ts('Is less than'),
1655 'gt' => ts('Is greater than'),
1656 'neq' => ts('Is not equal to'),
1657 'nbw' => ts('Is not between'),
1658 'nll' => ts('Is empty (Null)'),
1659 'nnll' => ts('Is not empty (Null)'),
1663 case CRM_Report_Form
::OP_SELECT
:
1665 'eq' => ts('Is equal to'),
1669 case CRM_Report_Form
::OP_MONTH
:
1670 case CRM_Report_Form
::OP_MULTISELECT
:
1671 case CRM_Report_Form
::OP_ENTITYREF
:
1674 'in' => ts('Is one of'),
1675 'notin' => ts('Is not one of'),
1679 case CRM_Report_Form
::OP_DATE
:
1682 'nll' => ts('Is empty (Null)'),
1683 'nnll' => ts('Is not empty (Null)'),
1687 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1688 // use this operator for the values, concatenated with separator. For e.g if
1689 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1691 'mhas' => ts('Is one of'),
1692 'mnot' => ts('Is not one of'),
1699 'has' => ts('Contains'),
1700 'sw' => ts('Starts with'),
1701 'ew' => ts('Ends with'),
1702 'nhas' => ts('Does not contain'),
1703 'eq' => ts('Is equal to'),
1704 'neq' => ts('Is not equal to'),
1705 'nll' => ts('Is empty (Null)'),
1706 'nnll' => ts('Is not empty (Null)'),
1713 * Build the tag filter field to display on the filters tab.
1715 public function buildTagFilter() {
1716 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1717 if (!empty($contactTags)) {
1718 $this->_columns
['civicrm_tag'] = array(
1719 'dao' => 'CRM_Core_DAO_Tag',
1723 'title' => ts('Tag'),
1724 'type' => CRM_Utils_Type
::T_INT
,
1726 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1727 'options' => $contactTags,
1735 * Adds group filters to _columns (called from _Construct).
1737 public function buildGroupFilter() {
1738 $this->_columns
['civicrm_group']['filters'] = array(
1740 'name' => 'group_id',
1741 'title' => ts('Group'),
1742 'type' => CRM_Utils_Type
::T_INT
,
1743 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1745 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1748 if (empty($this->_columns
['civicrm_group']['dao'])) {
1749 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1751 if (empty($this->_columns
['civicrm_group']['alias'])) {
1752 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1757 * Get SQL operator from form text version.
1759 * @param string $operator
1763 public function getSQLOperator($operator = "like") {
1764 switch ($operator) {
1797 return 'IS NOT NULL';
1806 * Generate where clause.
1808 * This can be overridden in reports for special treatment of a field
1810 * @param array $field Field specifications
1811 * @param string $op Query operator (not an exact match to sql)
1812 * @param mixed $value
1816 * @return null|string
1818 public function whereClause(&$field, $op, $value, $min, $max) {
1820 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1822 // CRM-18010: Ensure type of each report filters
1824 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1831 if (($min !== NULL && strlen($min) > 0) ||
1832 ($max !== NULL && strlen($max) > 0)
1836 $min = CRM_Utils_Type
::escape($min, $type);
1838 $clauses[] = "( {$field['dbAlias']} >= $min )";
1841 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1845 $max = CRM_Utils_Type
::escape($max, $type);
1847 $clauses[] = "( {$field['dbAlias']} <= $max )";
1850 $clauses[] = "( {$field['dbAlias']} > $max )";
1854 if (!empty($clauses)) {
1856 $clause = implode(' AND ', $clauses);
1859 $clause = '(' . implode('OR', $clauses) . ')';
1867 if ($value !== NULL && strlen($value) > 0) {
1868 $value = CRM_Utils_Type
::escape($value, $type);
1869 if (strpos($value, '%') === FALSE) {
1870 $value = "'%{$value}%'";
1873 $value = "'{$value}'";
1875 $sqlOP = $this->getSQLOperator($op);
1876 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1882 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1883 $value = explode(',', $value);
1885 if ($value !== NULL && is_array($value) && count($value) > 0) {
1886 $sqlOP = $this->getSQLOperator($op);
1887 if (CRM_Utils_Array
::value('type', $field) ==
1888 CRM_Utils_Type
::T_STRING
1890 //cycle through selections and escape values
1891 foreach ($value as $key => $selection) {
1892 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1895 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1899 // for numerical values
1900 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1903 if ($op == 'notin') {
1904 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1907 $clause = "( " . $clause . " )";
1914 // multiple has or multiple not
1915 if ($value !== NULL && count($value) > 0) {
1916 $value = CRM_Utils_Type
::escapeAll($value, $type);
1917 $operator = $op == 'mnot' ?
'NOT' : '';
1918 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1919 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1925 if ($value !== NULL && strlen($value) > 0) {
1926 $value = CRM_Utils_Type
::escape($value, $type);
1927 if (strpos($value, '%') === FALSE) {
1929 $value = "'{$value}%'";
1932 $value = "'%{$value}'";
1936 $value = "'{$value}'";
1938 $sqlOP = $this->getSQLOperator($op);
1939 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1945 $sqlOP = $this->getSQLOperator($op);
1946 $clause = "( {$field['dbAlias']} $sqlOP )";
1952 //CRM-18457: some custom field passes value in array format against binary operator
1953 if (is_array($value) && count($value)) {
1958 if ($value !== NULL && $value !== '') {
1959 if (isset($field['clause'])) {
1960 // FIXME: we not doing escape here. Better solution is to use two
1961 // different types - data-type and filter-type
1962 $clause = $field['clause'];
1964 elseif (!is_array($value)) {
1965 $value = CRM_Utils_Type
::escape($value, $type);
1966 $sqlOP = $this->getSQLOperator($op);
1967 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1968 $value = "'{$value}'";
1970 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1976 if (!empty($field['group']) && $clause) {
1977 $clause = $this->whereGroupClause($field, $value, $op);
1979 elseif (!empty($field['tag']) && $clause) {
1980 // not using left join in query because if any contact
1981 // belongs to more than one tag, results duplicate
1983 $clause = $this->whereTagClause($field, $value, $op);
1985 elseif (!empty($field['membership_org']) && $clause) {
1986 $clause = $this->whereMembershipOrgClause($value, $op);
1988 elseif (!empty($field['membership_type']) && $clause) {
1989 $clause = $this->whereMembershipTypeClause($value, $op);
1995 * Get SQL where clause for a date field.
1997 * @param string $fieldName
1998 * @param string $relative
1999 * @param string $from
2001 * @param string $type
2002 * @param string $fromTime
2003 * @param string $toTime
2005 * @return null|string
2007 public function dateClause(
2009 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2012 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2013 $sqlOP = $this->getSQLOperator($relative);
2014 return "( {$fieldName} {$sqlOP} )";
2017 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2020 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2021 $clauses[] = "( {$fieldName} >= $from )";
2025 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2026 $clauses[] = "( {$fieldName} <= {$to} )";
2029 if (!empty($clauses)) {
2030 return implode(' AND ', $clauses);
2037 * Get values for from and to for date ranges.
2039 * @param bool $relative
2040 * @param string $from
2042 * @param string $fromTime
2043 * @param string $toTime
2047 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2048 if (empty($toTime)) {
2051 //FIX ME not working for relative
2053 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2054 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2055 $from = substr($dateRange['from'], 0, 8);
2056 //Take only Date Part, Sometime Time part is also present in 'to'
2057 $to = substr($dateRange['to'], 0, 8);
2059 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2060 $to = CRM_Utils_Date
::processDate($to, $toTime);
2061 return array($from, $to);
2065 * Alter display of rows.
2067 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2068 * such as rendering contacts as links.
2070 * @param array $rows
2071 * Rows generated by SQL, with an array for each row.
2073 public function alterDisplay(&$rows) {
2077 * Alter the way in which custom data fields are displayed.
2079 * @param array $rows
2081 public function alterCustomDataDisplay(&$rows) {
2082 // custom code to alter rows having custom values
2083 if (empty($this->_customGroupExtends
)) {
2087 $customFields = array();
2088 $customFieldIds = array();
2089 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2090 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2091 $customFieldIds[$fieldAlias] = $fieldId;
2094 if (empty($customFieldIds)) {
2098 // skip for type date and ContactReference since date format is already handled
2100 SELECT cg.table_name, cf.id
2101 FROM civicrm_custom_field cf
2102 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2103 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2104 cg.is_active = 1 AND
2105 cf.is_active = 1 AND
2106 cf.is_searchable = 1 AND
2107 cf.data_type NOT IN ('ContactReference', 'Date') AND
2108 cf.id IN (" . implode(",", $customFieldIds) . ")";
2110 $dao = CRM_Core_DAO
::executeQuery($query);
2111 while ($dao->fetch()) {
2112 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2116 $entryFound = FALSE;
2117 foreach ($rows as $rowNum => $row) {
2118 foreach ($row as $tableCol => $val) {
2119 if (array_key_exists($tableCol, $customFields)) {
2120 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2125 // skip looking further in rows, if first row itself doesn't
2126 // have the column we need
2134 * Remove duplicate rows.
2136 * @param array $rows
2138 public function removeDuplicates(&$rows) {
2139 if (empty($this->_noRepeats
)) {
2142 $checkList = array();
2144 foreach ($rows as $key => $list) {
2145 foreach ($list as $colName => $colVal) {
2146 if (array_key_exists($colName, $checkList) &&
2147 $checkList[$colName] == $colVal
2149 $rows[$key][$colName] = "";
2151 if (in_array($colName, $this->_noRepeats
)) {
2152 $checkList[$colName] = $colVal;
2159 * Fix subtotal display.
2162 * @param array $fields
2163 * @param bool $subtotal
2165 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2166 foreach ($row as $colName => $colVal) {
2167 if (in_array($colName, $fields)) {
2169 elseif (isset($this->_columnHeaders
[$colName])) {
2171 $row[$colName] = 'Subtotal';
2175 unset($row[$colName]);
2182 * Calculate grant total.
2184 * @param array $rows
2188 public function grandTotal(&$rows) {
2189 if (!$this->_rollup ||
count($rows) == 1) {
2193 $this->moveSummaryColumnsToTheRightHandSide();
2195 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2199 $this->rollupRow
= array_pop($rows);
2201 foreach ($this->_columnHeaders
as $fld => $val) {
2202 if (!in_array($fld, $this->_statFields
)) {
2203 if (!$this->_grandFlag
) {
2204 $this->rollupRow
[$fld] = ts('Grand Total');
2205 $this->_grandFlag
= TRUE;
2208 $this->rollupRow
[$fld] = "";
2213 $this->assign('grandStat', $this->rollupRow
);
2218 * Format display output.
2220 * @param array $rows
2221 * @param bool $pager
2223 public function formatDisplay(&$rows, $pager = TRUE) {
2224 // set pager based on if any limit was applied in the query.
2229 // allow building charts if any
2230 if (!empty($this->_params
['charts']) && !empty($rows)) {
2231 $this->buildChart($rows);
2232 $this->assign('chartEnabled', TRUE);
2233 $this->_chartId
= "{$this->_params['charts']}_" .
2234 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2236 $this->assign('chartId', $this->_chartId
);
2239 // unset columns not to be displayed.
2240 foreach ($this->_columnHeaders
as $key => $value) {
2241 if (!empty($value['no_display'])) {
2242 unset($this->_columnHeaders
[$key]);
2246 // unset columns not to be displayed.
2247 if (!empty($rows)) {
2248 foreach ($this->_noDisplay
as $noDisplayField) {
2249 foreach ($rows as $rowNum => $row) {
2250 unset($this->_columnHeaders
[$noDisplayField]);
2255 // build array of section totals
2256 $this->sectionTotals();
2258 // process grand-total row
2259 $this->grandTotal($rows);
2261 // use this method for formatting rows for display purpose.
2262 $this->alterDisplay($rows);
2263 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2265 // use this method for formatting custom rows for display purpose.
2266 $this->alterCustomDataDisplay($rows);
2272 * @param array $rows
2274 public function buildChart(&$rows) {
2275 // override this method for building charts.
2278 // select() method below has been added recently (v3.3), and many of the report templates might
2279 // still be having their own select() method. We should fix them as and when encountered and move
2280 // towards generalizing the select() method below.
2283 * Generate the SELECT clause and set class variable $_select.
2285 public function select() {
2286 $select = $this->_selectAliases
= array();
2288 foreach ($this->_columns
as $tableName => $table) {
2289 if (array_key_exists('fields', $table)) {
2290 foreach ($table['fields'] as $fieldName => $field) {
2291 if ($tableName == 'civicrm_address') {
2292 // deprecated, use $this->isTableSelected.
2293 $this->_addressField
= TRUE;
2295 if ($tableName == 'civicrm_email') {
2296 $this->_emailField
= TRUE;
2298 if ($tableName == 'civicrm_phone') {
2299 $this->_phoneField
= TRUE;
2302 if (!empty($field['required']) ||
2303 !empty($this->_params
['fields'][$fieldName])
2306 // 1. In many cases we want select clause to be built in slightly different way
2307 // for a particular field of a particular type.
2308 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2310 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2311 if ($selectClause) {
2312 $select[] = $selectClause;
2316 // include statistics columns only if set
2317 if (!empty($field['statistics'])) {
2318 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2321 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2327 // select for group bys
2328 if (array_key_exists('group_bys', $table)) {
2329 foreach ($table['group_bys'] as $fieldName => $field) {
2331 if ($tableName == 'civicrm_address') {
2332 $this->_addressField
= TRUE;
2334 if ($tableName == 'civicrm_email') {
2335 $this->_emailField
= TRUE;
2337 if ($tableName == 'civicrm_phone') {
2338 $this->_phoneField
= TRUE;
2340 // 1. In many cases we want select clause to be built in slightly different way
2341 // for a particular field of a particular type.
2342 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2344 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2345 if ($selectClause) {
2346 $select[] = $selectClause;
2350 if (!empty($this->_params
['group_bys']) &&
2351 !empty($this->_params
['group_bys'][$fieldName]) &&
2352 !empty($this->_params
['group_bys_freq'])
2354 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2356 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2357 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2358 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2359 $field['title'] = 'Week';
2363 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2364 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2365 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2366 $field['title'] = 'Year';
2370 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2371 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2372 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2373 $field['title'] = 'Month';
2377 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2378 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2379 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2380 $field['title'] = 'Quarter';
2383 // for graphs and charts -
2384 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2385 $this->_interval
= $field['title'];
2386 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2387 = $field['title'] . ' Beginning';
2388 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2389 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2391 // just to make sure these values are transferred to rows.
2392 // since we 'll need them for calculation purpose,
2393 // e.g making subtotals look nicer or graphs
2394 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2395 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2402 $this->_selectClauses
= $select;
2403 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2407 * Build select clause for a single field.
2409 * @param string $tableName
2410 * @param string $tableKey
2411 * @param string $fieldName
2412 * @param string $field
2416 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2421 * Build where clause.
2423 public function where() {
2424 $this->storeWhereHavingClauseArray();
2426 if (empty($this->_whereClauses
)) {
2427 $this->_where
= "WHERE ( 1 ) ";
2428 $this->_having
= "";
2431 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2434 if ($this->_aclWhere
) {
2435 $this->_where
.= " AND {$this->_aclWhere} ";
2438 if (!empty($this->_havingClauses
)) {
2439 // use this clause to construct group by clause.
2440 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2445 * Store Where clauses into an array.
2447 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2448 * temp table that may not be part of the final where clause or added
2449 * in other functions
2451 public function storeWhereHavingClauseArray() {
2452 foreach ($this->_columns
as $tableName => $table) {
2453 if (array_key_exists('filters', $table)) {
2454 foreach ($table['filters'] as $fieldName => $field) {
2455 // respect pseudofield to filter spec so fields can be marked as
2456 // not to be handled here
2457 if (!empty($field['pseudofield'])) {
2461 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2462 if (CRM_Utils_Array
::value('operatorType', $field) ==
2463 CRM_Report_Form
::OP_MONTH
2465 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2466 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2467 if (is_array($value) && !empty($value)) {
2469 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2474 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2475 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2476 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2477 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2478 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2479 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2483 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2485 $clause = $this->whereClause($field,
2487 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2488 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2489 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2494 if (!empty($clause)) {
2495 if (!empty($field['having'])) {
2496 $this->_havingClauses
[] = $clause;
2499 $this->_whereClauses
[] = $clause;
2511 public function processReportMode() {
2512 $this->setOutputMode();
2515 = CRM_Utils_Request
::retrieve(
2518 CRM_Core_DAO
::$_nullObject
2521 $this->_absoluteUrl
= FALSE;
2523 $this->assign('printOnly', FALSE);
2525 if ($this->_outputMode
== 'print' ||
2526 ($this->_sendmail
&& !$this->_outputMode
)
2528 $this->assign('printOnly', TRUE);
2530 $this->addPaging
= FALSE;
2531 $this->assign('outputMode', 'print');
2532 $this->_outputMode
= 'print';
2533 if ($this->_sendmail
) {
2534 $this->_absoluteUrl
= TRUE;
2537 elseif ($this->_outputMode
== 'pdf') {
2539 $this->addPaging
= FALSE;
2540 $this->_absoluteUrl
= TRUE;
2542 elseif ($this->_outputMode
== 'csv') {
2544 $this->_absoluteUrl
= TRUE;
2545 $this->addPaging
= FALSE;
2547 elseif ($this->_outputMode
== 'group') {
2548 $this->assign('outputMode', 'group');
2550 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2551 $this->assign('outputMode', 'create_report');
2553 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2554 $this->_createNew
= TRUE;
2557 $this->assign('outputMode', $this->_outputMode
);
2558 $this->assign('printOnly', $printOnly);
2559 // Get today's date to include in printed reports
2561 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2562 $this->assign('reportDate', $reportDate);
2567 * Post Processing function for Form.
2569 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2570 * This function is not accessed when the api calls the report.
2572 public function beginPostProcess() {
2573 $this->setParams($this->controller
->exportValues($this->_name
));
2574 if (empty($this->_params
) &&
2577 $this->setParams($this->_formValues
);
2580 // hack to fix params when submitted from dashboard, CRM-8532
2581 // fields array is missing because form building etc is skipped
2582 // in dashboard mode for report
2583 //@todo - this could be done in the dashboard no we have a setter
2584 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2585 $this->setParams($this->_formValues
);
2588 $this->processReportMode();
2590 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2591 $this->_createNew
= ($this->_outputMode
== 'copy');
2592 CRM_Report_Form_Instance
::postProcess($this);
2594 if ($this->_outputMode
== 'delete') {
2595 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2598 $this->_formValues
= $this->_params
;
2600 $this->beginPostProcessCommon();
2604 * BeginPostProcess function run in both report mode and non-report mode (api).
2606 public function beginPostProcessCommon() {
2610 * Build the report query.
2612 * @param bool $applyLimit
2616 public function buildQuery($applyLimit = TRUE) {
2617 $this->buildGroupTempTable();
2620 $this->customDataFrom();
2621 $this->buildPermissionClause();
2623 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2624 $this->getPermissionedFTQuery($this);
2629 // order_by columns not selected for display need to be included in SELECT
2630 $unselectedSectionColumns = $this->unselectedSectionColumns();
2631 foreach ($unselectedSectionColumns as $alias => $section) {
2632 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2635 if ($applyLimit && empty($this->_params
['charts'])) {
2638 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2640 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2641 $this->addToDeveloperTab($sql);
2646 * Build group by clause.
2648 public function groupBy() {
2649 $groupBys = array();
2650 if (!empty($this->_params
['group_bys']) &&
2651 is_array($this->_params
['group_bys'])
2653 foreach ($this->_columns
as $tableName => $table) {
2654 if (array_key_exists('group_bys', $table)) {
2655 foreach ($table['group_bys'] as $fieldName => $field) {
2656 if (!empty($this->_params
['group_bys'][$fieldName])) {
2657 $groupBys[] = $field['dbAlias'];
2664 if (!empty($groupBys)) {
2665 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBys);
2670 * Build order by clause.
2672 public function orderBy() {
2673 $this->_orderBy
= "";
2674 $this->_sections
= array();
2675 $this->storeOrderByArray();
2676 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2677 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2679 $this->assign('sections', $this->_sections
);
2683 * Extract order by fields and store as an array.
2685 * In some cases other functions want to know which fields are selected for ordering by
2686 * Separating this into a separate function allows it to be called separately from constructing
2687 * the order by clause
2689 public function storeOrderByArray() {
2690 $orderBys = array();
2692 if (!empty($this->_params
['order_bys']) &&
2693 is_array($this->_params
['order_bys']) &&
2694 !empty($this->_params
['order_bys'])
2697 // Process order_bys in user-specified order
2698 foreach ($this->_params
['order_bys'] as $orderBy) {
2699 $orderByField = array();
2700 foreach ($this->_columns
as $tableName => $table) {
2701 if (array_key_exists('order_bys', $table)) {
2702 // For DAO columns defined in $this->_columns
2703 $fields = $table['order_bys'];
2705 elseif (array_key_exists('extends', $table)) {
2706 // For custom fields referenced in $this->_customGroupExtends
2707 $fields = CRM_Utils_Array
::value('fields', $table, array());
2712 if (!empty($fields) && is_array($fields)) {
2713 foreach ($fields as $fieldName => $field) {
2714 if ($fieldName == $orderBy['column']) {
2715 $orderByField = array_merge($field, $orderBy);
2716 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2723 if (!empty($orderByField)) {
2724 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2725 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2727 // Record any section headers for assignment to the template
2728 if (!empty($orderBy['section'])) {
2729 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2730 $this->_sections
[$orderByField['tplField']] = $orderByField;
2736 $this->_orderByArray
= $orderBys;
2738 $this->assign('sections', $this->_sections
);
2742 * Determine unselected columns.
2746 public function unselectedSectionColumns() {
2747 if (is_array($this->_sections
)) {
2748 return array_diff_key($this->_sections
, $this->getSelectColumns());
2756 * Build output rows.
2758 * @param string $sql
2759 * @param array $rows
2761 public function buildRows($sql, &$rows) {
2762 $dao = CRM_Core_DAO
::executeQuery($sql);
2763 if (!is_array($rows)) {
2767 // use this method to modify $this->_columnHeaders
2768 $this->modifyColumnHeaders();
2770 $unselectedSectionColumns = $this->unselectedSectionColumns();
2772 while ($dao->fetch()) {
2774 foreach ($this->_columnHeaders
as $key => $value) {
2775 if (property_exists($dao, $key)) {
2776 $row[$key] = $dao->$key;
2780 // section headers not selected for display need to be added to row
2781 foreach ($unselectedSectionColumns as $key => $values) {
2782 if (property_exists($dao, $key)) {
2783 $row[$key] = $dao->$key;
2792 * Calculate section totals.
2794 * When "order by" fields are marked as sections, this assigns to the template
2795 * an array of total counts for each section. This data is used by the Smarty
2796 * plugin {sectionTotal}.
2798 public function sectionTotals() {
2800 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2801 if (empty($this->_selectAliases
)) {
2805 if (!empty($this->_sections
)) {
2806 // build the query with no LIMIT clause
2807 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2808 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2810 // pull section aliases out of $this->_sections
2811 $sectionAliases = array_keys($this->_sections
);
2814 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2815 $ifnulls[] = "ifnull($alias, '') as $alias";
2817 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2818 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2820 // Group (un-limited) report by all aliases and get counts. This might
2821 // be done more efficiently when the contents of $sql are known, ie. by
2822 // overriding this method in the report class.
2824 $query = $this->_select
.
2825 ", count(*) as ct from ($sql) as subquery group by " .
2826 implode(", ", $sectionAliases);
2828 // initialize array of total counts
2830 $dao = CRM_Core_DAO
::executeQuery($query);
2831 while ($dao->fetch()) {
2833 // let $this->_alterDisplay translate any integer ids to human-readable values.
2834 $rows[0] = $dao->toArray();
2835 $this->alterDisplay($rows);
2838 // add totals for all permutations of section values
2841 $aliasCount = count($sectionAliases);
2842 foreach ($sectionAliases as $alias) {
2843 $values[] = $row[$alias];
2844 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2845 if ($i == $aliasCount) {
2846 // the last alias is the lowest-level section header; use count as-is
2847 $totals[$key] = $dao->ct
;
2850 // other aliases are higher level; roll count into their total
2851 $totals[$key] +
= $dao->ct
;
2855 $this->assign('sectionTotals', $totals);
2860 * Modify column headers.
2862 public function modifyColumnHeaders() {
2863 // use this method to modify $this->_columnHeaders
2867 * Move totals columns to the right edge of the table.
2869 * It seems like a more logical layout to have any totals columns on the far right regardless of
2870 * the location of the rest of their table.
2872 public function moveSummaryColumnsToTheRightHandSide() {
2873 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2874 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2878 * Assign rows to the template.
2880 * @param array $rows
2882 public function doTemplateAssignment(&$rows) {
2883 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2884 $this->assign_by_ref('rows', $rows);
2885 $this->assign('statistics', $this->statistics($rows));
2889 * Build report statistics.
2891 * Override this method to build your own statistics.
2893 * @param array $rows
2897 public function statistics(&$rows) {
2898 $statistics = array();
2900 $count = count($rows);
2901 // Why do we increment the count for rollup seems to artificially inflate the count.
2902 // It seems perhaps intentional to include the summary row in the count of results - although
2903 // this just seems odd.
2904 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2908 $this->countStat($statistics, $count);
2910 $this->groupByStat($statistics);
2912 $this->filterStat($statistics);
2918 * Add count statistics.
2920 * @param array $statistics
2923 public function countStat(&$statistics, $count) {
2924 $statistics['counts']['rowCount'] = array(
2925 'title' => ts('Row(s) Listed'),
2929 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2930 $statistics['counts']['rowsFound'] = array(
2931 'title' => ts('Total Row(s)'),
2932 'value' => $this->_rowsFound
,
2938 * Add group by statistics.
2940 * @param array $statistics
2942 public function groupByStat(&$statistics) {
2943 if (!empty($this->_params
['group_bys']) &&
2944 is_array($this->_params
['group_bys']) &&
2945 !empty($this->_params
['group_bys'])
2947 foreach ($this->_columns
as $tableName => $table) {
2948 if (array_key_exists('group_bys', $table)) {
2949 foreach ($table['group_bys'] as $fieldName => $field) {
2950 if (!empty($this->_params
['group_bys'][$fieldName])) {
2951 $combinations[] = $field['title'];
2956 $statistics['groups'][] = array(
2957 'title' => ts('Grouping(s)'),
2958 'value' => implode(' & ', $combinations),
2964 * Filter statistics.
2966 * @param array $statistics
2968 public function filterStat(&$statistics) {
2969 foreach ($this->_columns
as $tableName => $table) {
2970 if (array_key_exists('filters', $table)) {
2971 foreach ($table['filters'] as $fieldName => $field) {
2972 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2973 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2974 CRM_Utils_Array
::value('operatorType', $field) !=
2975 CRM_Report_Form
::OP_MONTH
2979 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2980 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2981 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2982 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2983 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2985 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2986 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2988 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2989 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2992 $statistics['filters'][] = array(
2993 'title' => $field['title'],
2994 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2997 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2998 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3000 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3001 $statistics['filters'][] = array(
3002 'title' => $field['title'],
3003 'value' => $pair[$rel],
3008 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3011 $pair = $this->getOperationPair(
3012 CRM_Utils_Array
::value('operatorType', $field),
3015 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3016 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3017 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3018 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3019 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3021 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3022 $this->setEntityRefDefaults($field, $tableName);
3023 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3024 array('id' => $val) +
3025 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3027 foreach ($result['values'] as $v) {
3028 $values[] = $v['label'];
3030 $value = "{$pair[$op]} " . implode(', ', $values);
3032 elseif ($op == 'nll' ||
$op == 'nnll') {
3033 $value = $pair[$op];
3035 elseif (is_array($val) && (!empty($val))) {
3036 $options = CRM_Utils_Array
::value('options', $field, array());
3037 foreach ($val as $key => $valIds) {
3038 if (isset($options[$valIds])) {
3039 $val[$key] = $options[$valIds];
3042 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3043 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3044 $val = implode(', ', $val);
3045 $value = "{$pair[$op]} " . $val;
3047 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3048 isset($field['options']) &&
3049 is_array($field['options']) && !empty($field['options'])
3051 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3052 CRM_Utils_Array
::value($val, $field['options'], $val);
3055 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3059 $statistics['filters'][] = array(
3060 'title' => CRM_Utils_Array
::value('title', $field),
3071 * End post processing.
3073 * @param array|null $rows
3075 public function endPostProcess(&$rows = NULL) {
3076 $this->assign('report_class', get_class($this));
3077 if ($this->_storeResultSet
) {
3078 $this->_resultSet
= $rows;
3081 if ($this->_outputMode
== 'print' ||
3082 $this->_outputMode
== 'pdf' ||
3086 $content = $this->compileContent();
3087 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3091 if ($this->_sendmail
) {
3092 $config = CRM_Core_Config
::singleton();
3093 $attachments = array();
3095 if ($this->_outputMode
== 'csv') {
3097 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3098 ": {$url}</p>" . '<p>' .
3099 ts('The report is attached as a CSV file.') . '</p>' .
3100 $this->_formValues
['report_footer'];
3102 $csvFullFilename = $config->templateCompileDir
.
3103 CRM_Utils_File
::makeFileName('CiviReport.csv');
3104 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3105 file_put_contents($csvFullFilename, $csvContent);
3106 $attachments[] = array(
3107 'fullPath' => $csvFullFilename,
3108 'mime_type' => 'text/csv',
3109 'cleanName' => 'CiviReport.csv',
3112 if ($this->_outputMode
== 'pdf') {
3113 // generate PDF content
3114 $pdfFullFilename = $config->templateCompileDir
.
3115 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3116 file_put_contents($pdfFullFilename,
3117 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3118 TRUE, array('orientation' => 'landscape')
3121 // generate Email Content
3123 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3124 ": {$url}</p>" . '<p>' .
3125 ts('The report is attached as a PDF file.') . '</p>' .
3126 $this->_formValues
['report_footer'];
3128 $attachments[] = array(
3129 'fullPath' => $pdfFullFilename,
3130 'mime_type' => 'application/pdf',
3131 'cleanName' => 'CiviReport.pdf',
3135 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3136 $this->_outputMode
, $attachments
3139 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3142 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3146 elseif ($this->_outputMode
== 'print') {
3150 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3151 $config = CRM_Core_Config
::singleton();
3152 //get chart image name
3153 $chartImg = $this->_chartId
. '.png';
3154 //get image url path
3156 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3158 $uploadUrl .= $chartImg;
3159 //get image doc path to overwrite
3161 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3162 'openFlashChart/' . $chartImg;
3164 $chart = imagecreatefrompng($uploadUrl);
3165 //convert it into formatted png
3166 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3167 //overwrite with same image
3168 imagepng($chart, $uploadImg);
3170 imagedestroy($chart);
3172 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3174 CRM_Utils_System
::civiExit();
3176 elseif ($this->_outputMode
== 'csv') {
3177 CRM_Report_Utils_Report
::export2csv($this, $rows);
3179 elseif ($this->_outputMode
== 'group') {
3180 $group = $this->_params
['groups'];
3181 $this->add2group($group);
3186 * Set store result set indicator to TRUE.
3188 * @todo explain what this does
3190 public function storeResultSet() {
3191 $this->_storeResultSet
= TRUE;
3199 public function getResultSet() {
3200 return $this->_resultSet
;
3204 * Get the sql used to generate the report.
3208 public function getReportSql() {
3209 return $this->sqlArray
;
3213 * Use the form name to create the tpl file name.
3217 public function getTemplateFileName() {
3218 $defaultTpl = parent
::getTemplateFileName();
3219 $template = CRM_Core_Smarty
::singleton();
3220 if (!$template->template_exists($defaultTpl)) {
3221 $defaultTpl = 'CRM/Report/Form.tpl';
3227 * Compile the report content.
3229 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3233 public function compileContent() {
3234 $templateFile = $this->getHookedTemplateFileName();
3235 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3236 CRM_Core_Form
::$_template->fetch($templateFile) .
3237 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3242 * Post process function.
3244 public function postProcess() {
3245 // get ready with post process params
3246 $this->beginPostProcess();
3249 $sql = $this->buildQuery();
3251 // build array of result based on column headers. This method also allows
3252 // modifying column headers before using it to build result set i.e $rows.
3254 $this->buildRows($sql, $rows);
3256 // format result set.
3257 $this->formatDisplay($rows);
3259 // assign variables to templates
3260 $this->doTemplateAssignment($rows);
3262 // do print / pdf / instance stuff if needed
3263 $this->endPostProcess($rows);
3269 * @param int $rowCount
3273 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3274 // lets do the pager if in html mode
3275 $this->_limit
= NULL;
3277 // CRM-14115, over-ride row count if rowCount is specified in URL
3278 if ($this->_dashBoardRowCount
) {
3279 $rowCount = $this->_dashBoardRowCount
;
3281 if ($this->addPaging
) {
3282 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3284 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3286 // @todo all http vars should be extracted in the preProcess
3287 // - not randomly in the class
3288 if (!$pageId && !empty($_POST)) {
3289 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3290 $pageId = max((int) $_POST['crmPID_B'], 1);
3292 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3293 $pageId = max((int) $_POST['crmPID'], 1);
3295 unset($_POST['crmPID_B'], $_POST['crmPID']);
3298 $pageId = $pageId ?
$pageId : 1;
3299 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3300 $offset = ($pageId - 1) * $rowCount;
3302 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3303 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3305 $this->_limit
= " LIMIT $offset, $rowCount";
3306 return array($offset, $rowCount);
3308 if ($this->_limitValue
) {
3309 if ($this->_offsetValue
) {
3310 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3313 $this->_limit
= " LIMIT " . $this->_limitValue
;
3321 * @param int $rowCount
3323 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3324 // CRM-14115, over-ride row count if rowCount is specified in URL
3325 if ($this->_dashBoardRowCount
) {
3326 $rowCount = $this->_dashBoardRowCount
;
3329 if ($this->_limit
&& ($this->_limit
!= '')) {
3330 if (!$this->_rowsFound
) {
3331 $sql = "SELECT FOUND_ROWS();";
3332 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3335 'total' => $this->_rowsFound
,
3336 'rowCount' => $rowCount,
3337 'status' => ts('Records') . ' %%StatusMessage%%',
3338 'buttonBottom' => 'PagerBottomButton',
3339 'buttonTop' => 'PagerTopButton',
3341 if (!empty($this->controller
)) {
3342 // This happens when being called from the api Really we want the api to be able to
3343 // pass paging parameters, but at this stage just preventing test crashes.
3344 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3347 $pager = new CRM_Utils_Pager($params);
3348 $this->assign_by_ref('pager', $pager);
3349 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3354 * Build a group filter with contempt for large data sets.
3356 * This function has been retained as it takes time to migrate the reports over
3357 * to the new method which will not crash on large datasets.
3361 * @param string $field
3362 * @param mixed $value
3367 public function legacySlowGroupFilterClause($field, $value, $op) {
3368 $smartGroupQuery = "";
3370 $group = new CRM_Contact_DAO_Group();
3371 $group->is_active
= 1;
3373 $smartGroups = array();
3374 while ($group->fetch()) {
3375 if (in_array($group->id
, $this->_params
['gid_value']) &&
3376 $group->saved_search_id
3378 $smartGroups[] = $group->id
;
3382 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3384 $smartGroupQuery = '';
3385 if (!empty($smartGroups)) {
3386 $smartGroups = implode(',', $smartGroups);
3387 $smartGroupQuery = " UNION DISTINCT
3388 SELECT DISTINCT smartgroup_contact.contact_id
3389 FROM civicrm_group_contact_cache smartgroup_contact
3390 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3393 $sqlOp = $this->getSQLOperator($op);
3394 if (!is_array($value)) {
3395 $value = array($value);
3397 //include child groups if any
3398 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3400 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3402 $contactAlias = $this->_aliases
['civicrm_contact'];
3403 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3404 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3406 return " {$contactAlias}.id {$sqlOp} (
3407 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3408 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3409 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3410 {$smartGroupQuery} ) ";
3414 * Build where clause for groups.
3416 * @param string $field
3417 * @param mixed $value
3422 public function whereGroupClause($field, $value, $op) {
3423 if ($this->groupFilterNotOptimised
) {
3424 return $this->legacySlowGroupFilterClause($field, $value, $op);
3426 if ($op === 'notin') {
3427 return " group_temp_table.id IS NULL ";
3429 // We will have used an inner join instead.
3435 * Create a table of the contact ids included by the group filter.
3437 * This function is called by both the api (tests) and the UI.
3439 public function buildGroupTempTable() {
3440 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3443 $filteredGroups = (array) $this->_params
['gid_value'];
3445 $groups = civicrm_api3('Group', 'get', array(
3447 'id' => array('IN' => $filteredGroups),
3448 'saved_search_id' => array('>' => 0),
3451 $smartGroups = array_keys($groups['values']);
3454 SELECT group_contact.contact_id as id
3455 FROM civicrm_group_contact group_contact
3456 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3457 AND group_contact.status = 'Added' ";
3459 if (!empty($smartGroups)) {
3460 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3461 $smartGroups = implode(',', $smartGroups);
3464 SELECT smartgroup_contact.contact_id as id
3465 FROM civicrm_group_contact_cache smartgroup_contact
3466 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3469 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3470 $this->executeReportQuery("
3471 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3474 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3478 * Execute query and add it to the developer tab.
3480 * @param string $query
3481 * @param array $params
3483 * @return \CRM_Core_DAO|object
3485 protected function executeReportQuery($query, $params = array()) {
3486 $this->addToDeveloperTab($query);
3487 return CRM_Core_DAO
::executeQuery($query, $params);
3491 * Build where clause for tags.
3493 * @param string $field
3494 * @param mixed $value
3499 public function whereTagClause($field, $value, $op) {
3500 // not using left join in query because if any contact
3501 // belongs to more than one tag, results duplicate
3503 $sqlOp = $this->getSQLOperator($op);
3504 if (!is_array($value)) {
3505 $value = array($value);
3507 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3508 $entity_table = $this->_tagFilterTable
;
3509 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3510 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3511 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3512 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3516 * Generate membership organization clause.
3518 * @param mixed $value
3519 * @param string $op SQL Operator
3523 public function whereMembershipOrgClause($value, $op) {
3524 $sqlOp = $this->getSQLOperator($op);
3525 if (!is_array($value)) {
3526 $value = array($value);
3529 $tmp_membership_org_sql_list = implode(', ', $value);
3530 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3531 SELECT DISTINCT mem.contact_id
3532 FROM civicrm_membership mem
3533 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3534 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3535 WHERE mt.member_of_contact_id IN (" .
3536 $tmp_membership_org_sql_list . ")
3537 AND mt.is_active = '1'
3538 AND mem_status.is_current_member = '1'
3539 AND mem_status.is_active = '1' ) ";
3543 * Generate Membership Type SQL Clause.
3545 * @param mixed $value
3551 public function whereMembershipTypeClause($value, $op) {
3552 $sqlOp = $this->getSQLOperator($op);
3553 if (!is_array($value)) {
3554 $value = array($value);
3557 $tmp_membership_sql_list = implode(', ', $value);
3558 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3559 SELECT DISTINCT mem.contact_id
3560 FROM civicrm_membership mem
3561 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3562 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3563 WHERE mem.membership_type_id IN (" .
3564 $tmp_membership_sql_list . ")
3565 AND mt.is_active = '1'
3566 AND mem_status.is_current_member = '1'
3567 AND mem_status.is_active = '1' ) ";
3571 * Buld contact acl clause
3572 * @deprecated in favor of buildPermissionClause
3574 * @param string $tableAlias
3576 public function buildACLClause($tableAlias = 'contact_a') {
3577 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3581 * Build the permision clause for all entities in this report
3583 public function buildPermissionClause() {
3585 foreach ($this->selectedTables() as $tableName) {
3586 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3587 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3588 $tableAlias = $this->_columns
[$tableName]['alias'];
3589 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3590 foreach ($clauses as $field => $clause) {
3591 // Skip contact_id field if redundant
3592 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3593 $ret["$tableName.$field"] = $clause;
3598 // Override output from buildACLClause
3599 $this->_aclFrom
= NULL;
3600 $this->_aclWhere
= implode(' AND ', $ret);
3604 * Add custom data to the columns.
3606 * @param bool $addFields
3607 * @param array $permCustomGroupIds
3609 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3610 if (empty($this->_customGroupExtends
)) {
3613 if (!is_array($this->_customGroupExtends
)) {
3614 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3616 $customGroupWhere = '';
3617 if (!empty($permCustomGroupIds)) {
3618 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3622 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3623 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3624 FROM civicrm_custom_group cg
3625 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3626 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3628 cg.is_active = 1 AND
3629 cf.is_active = 1 AND
3630 cf.is_searchable = 1
3631 ORDER BY cg.weight, cf.weight";
3632 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3635 while ($customDAO->fetch()) {
3636 if ($customDAO->table_name
!= $curTable) {
3637 $curTable = $customDAO->table_name
;
3638 $curFields = $curFilters = array();
3641 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3642 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3643 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3644 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3646 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3647 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3648 $this->_columns
[$curTable][$colKey] = array();
3652 $fieldName = 'custom_' . $customDAO->cf_id
;
3655 // this makes aliasing work in favor
3656 $curFields[$fieldName] = array(
3657 'name' => $customDAO->column_name
,
3658 'title' => $customDAO->label
,
3659 'dataType' => $customDAO->data_type
,
3660 'htmlType' => $customDAO->html_type
,
3663 if ($this->_customGroupFilters
) {
3664 // this makes aliasing work in favor
3665 $curFilters[$fieldName] = array(
3666 'name' => $customDAO->column_name
,
3667 'title' => $customDAO->label
,
3668 'dataType' => $customDAO->data_type
,
3669 'htmlType' => $customDAO->html_type
,
3673 switch ($customDAO->data_type
) {
3676 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3677 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3678 // CRM-6946, show time part for datetime date fields
3679 if ($customDAO->time_format
) {
3680 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3685 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3686 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3687 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3691 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3692 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3696 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3697 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3698 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3702 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3703 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3707 case 'StateProvince':
3709 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3711 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3712 if ($options !== FALSE) {
3713 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3714 $curFilters[$fieldName]['options'] = $options;
3718 case 'ContactReference':
3719 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3720 $curFilters[$fieldName]['name'] = 'display_name';
3721 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3723 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3724 $curFields[$fieldName]['name'] = 'display_name';
3725 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3729 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3730 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3734 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3735 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3736 if ($options !== FALSE) {
3737 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3738 $curFilters[$fieldName]['options'] = $options;
3742 if (!array_key_exists('type', $curFields[$fieldName])) {
3743 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3747 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3749 if ($this->_customGroupFilters
) {
3750 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3752 if ($this->_customGroupGroupBy
) {
3753 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3759 * Build custom data from clause.
3761 * @param bool $joinsForFiltersOnly
3762 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3764 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3765 if (empty($this->_customGroupExtends
)) {
3768 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3769 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3770 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3771 $customTables = array();
3772 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3773 while ($customTablesDAO->fetch()) {
3774 $customTables[] = $customTablesDAO->table_name
;
3777 foreach ($this->_columns
as $table => $prop) {
3778 if (in_array($table, $customTables)) {
3779 $extendsTable = $mapper[$prop['extends']];
3780 // Check field is required for rendering the report.
3781 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3784 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3786 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3788 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3789 // handle for ContactReference
3790 if (array_key_exists('fields', $prop)) {
3791 foreach ($prop['fields'] as $fieldName => $field) {
3792 if (CRM_Utils_Array
::value('dataType', $field) ==
3795 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3797 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3806 * Check if the field is selected.
3808 * @param string $prop
3812 public function isFieldSelected($prop) {
3817 if (!empty($this->_params
['fields'])) {
3818 foreach (array_keys($prop['fields']) as $fieldAlias) {
3819 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3820 if ($customFieldId) {
3821 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3825 //might be survey response field.
3826 if (!empty($this->_params
['fields']['survey_response']) &&
3827 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3835 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3836 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3837 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3838 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3845 if (!empty($this->_params
['order_bys'])) {
3846 foreach (array_keys($prop['fields']) as $fieldAlias) {
3847 foreach ($this->_params
['order_bys'] as $orderBy) {
3848 if ($fieldAlias == $orderBy['column'] &&
3849 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3856 return $this->isFieldFiltered($prop);
3861 * Check if the field is used as a filter.
3863 * @param string $prop
3867 protected function isFieldFiltered($prop) {
3868 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3869 foreach ($prop['filters'] as $fieldAlias => $val) {
3878 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3879 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3880 ||
($attach != 'relative' &&
3881 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3887 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3888 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3899 * Check for empty order_by configurations and remove them.
3901 * Also set template to hide them.
3903 * @param array $formValues
3905 public function preProcessOrderBy(&$formValues) {
3906 // Object to show/hide form elements
3907 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3909 $_showHide->addShow('optionField_1');
3911 // Cycle through order_by options; skip any empty ones, and hide them as well
3914 if (!empty($formValues['order_bys'])) {
3915 foreach ($formValues['order_bys'] as $order_by) {
3916 if ($order_by['column'] && $order_by['column'] != '-') {
3917 $_showHide->addShow('optionField_' . $n);
3918 $orderBys[$n] = $order_by;
3923 for ($i = $n; $i <= 5; $i++
) {
3925 $_showHide->addHide('optionField_' . $i);
3929 // overwrite order_by options with modified values
3930 if (!empty($orderBys)) {
3931 $formValues['order_bys'] = $orderBys;
3934 $formValues['order_bys'] = array(1 => array('column' => '-'));
3937 // assign show/hide data to template
3938 $_showHide->addToTemplate();
3942 * Check if table name has columns in SELECT clause.
3944 * @param string $tableName
3945 * Name of table (index of $this->_columns array).
3949 public function isTableSelected($tableName) {
3950 return in_array($tableName, $this->selectedTables());
3954 * Check if table name has columns in WHERE or HAVING clause.
3956 * @param string $tableName
3957 * Name of table (index of $this->_columns array).
3961 public function isTableFiltered($tableName) {
3962 // Cause the array to be generated if not previously done.
3963 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3964 $this->selectedTables();
3966 return in_array($tableName, $this->filteredTables
);
3970 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3972 * If the array is unset it will be built.
3977 public function selectedTables() {
3978 if (!$this->_selectedTables
) {
3979 $orderByColumns = array();
3980 if (array_key_exists('order_bys', $this->_params
) &&
3981 is_array($this->_params
['order_bys'])
3983 foreach ($this->_params
['order_bys'] as $orderBy) {
3984 $orderByColumns[] = $orderBy['column'];
3988 foreach ($this->_columns
as $tableName => $table) {
3989 if (array_key_exists('fields', $table)) {
3990 foreach ($table['fields'] as $fieldName => $field) {
3991 if (!empty($field['required']) ||
3992 !empty($this->_params
['fields'][$fieldName])
3994 $this->_selectedTables
[] = $tableName;
3999 if (array_key_exists('order_bys', $table)) {
4000 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4001 if (in_array($orderByName, $orderByColumns)) {
4002 $this->_selectedTables
[] = $tableName;
4007 if (array_key_exists('filters', $table)) {
4008 foreach ($table['filters'] as $filterName => $filter) {
4009 if (!empty($this->_params
["{$filterName}_value"]) ||
4010 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4012 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4015 $this->_selectedTables
[] = $tableName;
4016 $this->filteredTables
[] = $tableName;
4023 return $this->_selectedTables
;
4027 * Add address fields.
4029 * @deprecated - use getAddressColumns which is a more accurate description
4030 * and also accepts an array of options rather than a long list
4032 * adding address fields to construct function in reports
4034 * @param bool $groupBy
4035 * Add GroupBy? Not appropriate for detail report.
4036 * @param bool $orderBy
4037 * Add GroupBy? Not appropriate for detail report.
4038 * @param bool $filters
4039 * @param array $defaults
4042 * address fields for construct clause
4044 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4045 $defaultAddressFields = array(
4046 'street_address' => ts('Street Address'),
4047 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4048 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4049 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4050 'street_number' => ts('Street Number'),
4051 'street_name' => ts('Street Name'),
4052 'street_unit' => ts('Street Unit'),
4053 'city' => ts('City'),
4054 'postal_code' => ts('Postal Code'),
4055 'postal_code_suffix' => ts('Postal Code Suffix'),
4056 'country_id' => ts('Country'),
4057 'state_province_id' => ts('State/Province'),
4058 'county_id' => ts('County'),
4060 $addressFields = array(
4061 'civicrm_address' => array(
4062 'dao' => 'CRM_Core_DAO_Address',
4064 'address_name' => array(
4065 'title' => ts('Address Name'),
4066 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4070 'grouping' => 'location-fields',
4073 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4074 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4075 'title' => $fieldLabel,
4076 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4080 $street_address_filters = $general_address_filters = array();
4082 // Address filter depends on whether street address parsing is enabled.
4084 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4087 if ($addressOptions['street_address_parsing']) {
4088 $street_address_filters = array(
4089 'street_number' => array(
4090 'title' => ts('Street Number'),
4091 'type' => CRM_Utils_Type
::T_INT
,
4092 'name' => 'street_number',
4094 'street_name' => array(
4095 'title' => ts('Street Name'),
4096 'name' => 'street_name',
4097 'type' => CRM_Utils_Type
::T_STRING
,
4102 $street_address_filters = array(
4103 'street_address' => array(
4104 'title' => ts('Street Address'),
4105 'type' => CRM_Utils_Type
::T_STRING
,
4106 'name' => 'street_address',
4110 $general_address_filters = array(
4111 'postal_code' => array(
4112 'title' => ts('Postal Code'),
4113 'type' => CRM_Utils_Type
::T_STRING
,
4114 'name' => 'postal_code',
4117 'title' => ts('City'),
4118 'type' => CRM_Utils_Type
::T_STRING
,
4121 'country_id' => array(
4122 'name' => 'country_id',
4123 'title' => ts('Country'),
4124 'type' => CRM_Utils_Type
::T_INT
,
4125 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4126 'options' => CRM_Core_PseudoConstant
::country(),
4128 'state_province_id' => array(
4129 'name' => 'state_province_id',
4130 'title' => ts('State/Province'),
4131 'type' => CRM_Utils_Type
::T_INT
,
4132 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4133 'options' => array(),
4135 'county_id' => array(
4136 'name' => 'county_id',
4137 'title' => ts('County'),
4138 'type' => CRM_Utils_Type
::T_INT
,
4139 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4140 'options' => array(),
4144 $addressFields['civicrm_address']['filters'] = array_merge(
4145 $street_address_filters,
4146 $general_address_filters);
4149 $addressFields['civicrm_address']['order_bys'] = array(
4150 'street_name' => array('title' => ts('Street Name')),
4151 'street_number' => array('title' => ts('Odd / Even Street Number')),
4152 'street_address' => NULL,
4154 'postal_code' => NULL,
4159 $addressFields['civicrm_address']['group_bys'] = array(
4160 'street_address' => NULL,
4162 'postal_code' => NULL,
4163 'state_province_id' => array(
4164 'title' => ts('State/Province'),
4166 'country_id' => array(
4167 'title' => ts('Country'),
4169 'county_id' => array(
4170 'title' => ts('County'),
4174 return $addressFields;
4178 * Do AlterDisplay processing on Address Fields.
4181 * @param array $rows
4182 * @param int $rowNum
4183 * @param string $baseUrl
4184 * @param string $linkText
4188 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4189 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4190 $entryFound = FALSE;
4192 if (array_key_exists('civicrm_address_country_id', $row)) {
4193 if ($value = $row['civicrm_address_country_id']) {
4194 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4196 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4197 "reset=1&force=1&{$criteriaQueryParams}&" .
4198 "country_id_op=in&country_id_value={$value}",
4199 $this->_absoluteUrl
, $this->_id
4201 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4202 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4203 array(1 => $linkText)
4210 if (array_key_exists('civicrm_address_county_id', $row)) {
4211 if ($value = $row['civicrm_address_county_id']) {
4212 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4214 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4215 "reset=1&force=1&{$criteriaQueryParams}&" .
4216 "county_id_op=in&county_id_value={$value}",
4217 $this->_absoluteUrl
, $this->_id
4219 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4220 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4221 array(1 => $linkText)
4227 // handle state province
4228 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4229 if ($value = $row['civicrm_address_state_province_id']) {
4230 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4232 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4233 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4234 $this->_absoluteUrl
, $this->_id
4236 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4237 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4238 array(1 => $linkText)
4249 * Do AlterDisplay processing on Address Fields.
4252 * @param array $rows
4253 * @param int $rowNum
4254 * @param string $baseUrl
4255 * @param string $linkText
4259 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4260 $entryFound = FALSE;
4261 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4262 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4263 $addLinks = array('gender_id' => 'Gender');
4264 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4265 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4266 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4267 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4268 $rowLabels = array();
4269 foreach ($rowValues as $rowValue) {
4271 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4274 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4275 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4276 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4282 $yesNoFields = array(
4283 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4285 foreach ($yesNoFields as $fieldName) {
4286 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4287 // Since these are essentially 'negative fields' it feels like it
4288 // makes sense to only highlight the exceptions hence no 'No'.
4289 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4297 * Adjusts dates passed in to YEAR() for fiscal year.
4299 * @param string $fieldName
4303 public function fiscalYearOffset($fieldName) {
4304 $config = CRM_Core_Config
::singleton();
4305 $fy = $config->fiscalYearStart
;
4306 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4307 ($fy['d'] == 1 && $fy['M'] == 1)
4309 return "YEAR( $fieldName )";
4311 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4312 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4316 * Add Address into From Table if required.
4318 public function addAddressFromClause() {
4319 // include address field if address column is to be included
4320 if ((isset($this->_addressField
) &&
4321 $this->_addressField
4323 $this->isTableSelected('civicrm_address')
4326 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4327 ON ({$this->_aliases['civicrm_contact']}.id =
4328 {$this->_aliases['civicrm_address']}.contact_id) AND
4329 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4334 * Add Phone into From Table if required.
4336 public function addPhoneFromClause() {
4337 // include address field if address column is to be included
4338 if ($this->isTableSelected('civicrm_phone')) {
4340 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4341 ON ({$this->_aliases['civicrm_contact']}.id =
4342 {$this->_aliases['civicrm_phone']}.contact_id) AND
4343 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4348 * Add Financial Transaction into From Table if required.
4350 public function addFinancialTrxnFromClause() {
4351 if ($this->isTableSelected('civicrm_financial_trxn')) {
4353 LEFT JOIN civicrm_entity_financial_trxn eftcc
4354 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4355 eftcc.entity_table = 'civicrm_contribution')
4356 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4357 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4362 * Get phone columns to add to array.
4364 * @param array $options
4365 * - prefix Prefix to add to table (in case of more than one instance of the table)
4366 * - prefix_label Label to give columns from this phone table instance
4369 * phone columns definition
4371 public function getPhoneColumns($options = array()) {
4372 $defaultOptions = array(
4374 'prefix_label' => '',
4377 $options = array_merge($defaultOptions, $options);
4380 $options['prefix'] . 'civicrm_phone' => array(
4381 'dao' => 'CRM_Core_DAO_Phone',
4383 $options['prefix'] . 'phone' => array(
4384 'title' => ts($options['prefix_label'] . 'Phone'),
4394 * Get address columns to add to array.
4396 * @param array $options
4397 * - prefix Prefix to add to table (in case of more than one instance of the table)
4398 * - prefix_label Label to give columns from this address table instance
4401 * address columns definition
4403 public function getAddressColumns($options = array()) {
4406 'prefix_label' => '',
4410 'defaults' => array(),
4412 return $this->addAddressFields(
4413 $options['group_by'],
4414 $options['order_by'],
4415 $options['filters'],
4416 $options['defaults']
4421 * Get a standard set of contact fields.
4425 public function getBasicContactFields() {
4427 'sort_name' => array(
4428 'title' => ts('Contact Name'),
4433 'no_display' => TRUE,
4436 'prefix_id' => array(
4437 'title' => ts('Contact Prefix'),
4439 'first_name' => array(
4440 'title' => ts('First Name'),
4442 'nick_name' => array(
4443 'title' => ts('Nick Name'),
4445 'middle_name' => array(
4446 'title' => ts('Middle Name'),
4448 'last_name' => array(
4449 'title' => ts('Last Name'),
4451 'suffix_id' => array(
4452 'title' => ts('Contact Suffix'),
4454 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4455 'email_greeting_display' => array('title' => ts('Email Greeting')),
4456 'addressee_display' => array('title' => ts('Addressee')),
4457 'contact_type' => array(
4458 'title' => ts('Contact Type'),
4460 'contact_sub_type' => array(
4461 'title' => ts('Contact Subtype'),
4463 'gender_id' => array(
4464 'title' => ts('Gender'),
4466 'birth_date' => array(
4467 'title' => ts('Birth Date'),
4470 'title' => ts('Age'),
4471 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4473 'job_title' => array(
4474 'title' => ts('Contact Job title'),
4476 'organization_name' => array(
4477 'title' => ts('Organization Name'),
4479 'external_identifier' => array(
4480 'title' => ts('Contact identifier from external system'),
4482 'do_not_email' => array(),
4483 'do_not_phone' => array(),
4484 'do_not_mail' => array(),
4485 'do_not_sms' => array(),
4486 'is_opt_out' => array(),
4487 'is_deceased' => array(),
4488 'preferred_language' => array(),
4493 * Get a standard set of contact filters.
4497 public function getBasicContactFilters() {
4499 'sort_name' => array(
4500 'title' => ts('Contact Name'),
4503 'title' => ts('Contact Source'),
4504 'type' => CRM_Utils_Type
::T_STRING
,
4507 'title' => ts('Contact ID'),
4508 'no_display' => TRUE,
4510 'gender_id' => array(
4511 'title' => ts('Gender'),
4512 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4513 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4515 'birth_date' => array(
4516 'title' => ts('Birth Date'),
4517 'operatorType' => CRM_Report_Form
::OP_DATE
,
4519 'contact_type' => array(
4520 'title' => ts('Contact Type'),
4522 'contact_sub_type' => array(
4523 'title' => ts('Contact Subtype'),
4525 'modified_date' => array(
4526 'title' => ts('Contact Modified'),
4527 'operatorType' => CRM_Report_Form
::OP_DATE
,
4528 'type' => CRM_Utils_Type
::T_DATE
,
4530 'is_deceased' => array(
4531 'title' => ts('Deceased'),
4532 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4535 'do_not_email' => array(
4536 'title' => ts('Do not email'),
4537 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4539 'do_not_phone' => array(
4540 'title' => ts('Do not phone'),
4541 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4543 'do_not_mail' => array(
4544 'title' => ts('Do not mail'),
4545 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4547 'do_not_sms' => array(
4548 'title' => ts('Do not SMS'),
4549 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4551 'is_opt_out' => array(
4552 'title' => ts('Do not bulk email'),
4553 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4555 'preferred_language' => array(
4556 'title' => ts('Preferred Language'),
4562 * Add contact to group.
4564 * @param int $groupID
4566 public function add2group($groupID) {
4567 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4568 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4569 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4570 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4571 $sql = str_replace('WITH ROLLUP', '', $sql);
4572 $dao = CRM_Core_DAO
::executeQuery($sql);
4574 $contact_ids = array();
4575 // Add resulting contacts to group
4576 while ($dao->fetch()) {
4577 if ($dao->addtogroup_contact_id
) {
4578 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4582 if (!empty($contact_ids)) {
4583 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4584 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4587 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4593 * Show charts on print screen.
4595 public static function uploadChartImage() {
4596 // upload strictly for '.png' images
4597 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4598 if (preg_match('/\.png$/', $name)) {
4600 // Get the RAW .png from the input.
4601 $httpRawPostData = file_get_contents("php://input");
4603 // prepare the directory
4604 $config = CRM_Core_Config
::singleton();
4606 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4608 if (!file_exists($defaultPath)) {
4609 mkdir($defaultPath, 0777, TRUE);
4612 // full path to the saved image including filename
4613 $destination = $defaultPath . $name;
4616 $jfh = fopen($destination, 'w') or die("can't open file");
4617 fwrite($jfh, $httpRawPostData);
4619 CRM_Utils_System
::civiExit();
4624 * Apply common settings to entityRef fields.
4626 * @param array $field
4627 * @param string $table
4629 private function setEntityRefDefaults(&$field, $table) {
4630 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4631 $field['attributes'] +
= array(
4632 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4634 'placeholder' => ts('- select -'),
4639 * Add link fields to the row.
4641 * Function adds the _link & _hover fields to the row.
4644 * @param string $baseUrl
4645 * @param string $linkText
4646 * @param string $value
4647 * @param string $fieldName
4648 * @param string $tablePrefix
4649 * @param string $fieldLabel
4653 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4654 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4655 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4656 "reset=1&force=1&{$criteriaQueryParams}&" .
4657 $fieldName . "_op=in&{$fieldName}_value={$value}",
4658 $this->_absoluteUrl
, $this->_id
4660 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4661 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4662 array(1 => $linkText, 2 => $fieldLabel)
4667 * Generate temporary table to hold all contributions with permissioned FTs.
4669 * @param object $query
4670 * @param string $alias
4671 * @param bool $return
4675 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4676 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4679 $financialTypes = NULL;
4680 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4681 if (empty($financialTypes)) {
4683 $liFTs = implode(',', array_keys(CRM_Contribute_PseudoConstant
::financialType()));
4686 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4688 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4690 $query->_aliases
['civicrm_line_item'] = $alias;
4693 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4695 if (empty($query->_where
)) {
4696 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4698 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4699 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp {$this->_databaseAttributes} AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4700 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4701 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4702 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4703 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4705 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4706 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4707 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4708 CRM_Core_DAO
::executeQuery($sql);
4710 $query->_aliases
['civicrm_line_item'] = $temp;
4712 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4716 $query->_from
.= $from;
4720 * Get label for show results buttons.
4724 public function getResultsLabel() {
4725 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4726 return $showResultsLabel;
4730 * Determine the output mode from the url or input.
4733 * - pdf : Render as pdf
4734 * - csv : Render as csv
4735 * - print : Render in print format
4736 * - save : save the report and display the new report
4737 * - copy : save the report as a new instance and display that.
4738 * - group : go to the add to group screen.
4740 * Potentially chart variations could also be included but the complexity
4741 * is that we might print a bar chart as a pdf.
4743 protected function setOutputMode() {
4744 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4747 CRM_Core_DAO
::$_nullObject,
4749 CRM_Utils_Array
::value('task', $this->_params
)
4751 // if contacts are added to group
4752 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4753 $this->_outputMode
= 'group';
4755 if (isset($this->_params
['task'])) {
4756 unset($this->_params
['task']);
4761 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4764 * @param $columnName
4766 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4767 // add new column with date value for the datetime field
4768 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4769 CRM_Core_DAO
::executeQuery($tempQuery);
4770 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4771 CRM_Core_DAO
::executeQuery($updateQuery);
4772 $this->_selectClauses
[] = "{$columnName}_date";
4773 $this->_select
.= ", {$columnName}_date";
4774 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4775 unset($this->_sections
["{$columnName}"]);
4776 $this->assign('sections', $this->_sections
);
4780 * Get an array of the columns that have been selected for display.
4784 public function getSelectColumns() {
4785 $selectColumns = array();
4786 foreach ($this->_columns
as $tableName => $table) {
4787 if (array_key_exists('fields', $table)) {
4788 foreach ($table['fields'] as $fieldName => $field) {
4789 if (!empty($field['required']) ||
4790 !empty($this->_params
['fields'][$fieldName])
4793 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4798 return $selectColumns;
4802 * Add location tables to the query if they are used for filtering.
4804 * This is for when we are running the query separately for filtering and retrieving display fields.
4806 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4807 if ($this->isTableFiltered('civicrm_email')) {
4809 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4810 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4811 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4813 if ($this->isTableFiltered('civicrm_phone')) {
4815 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4816 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4817 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4819 if ($this->isTableFiltered('civicrm_address')) {
4821 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4822 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4823 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4828 * Set the base table for the FROM clause.
4830 * Sets up the from clause, allowing for the possibility it might be a
4831 * temp table pre-filtered by groups if a group filter is in use.
4833 * @param string $baseTable
4834 * @param string $field
4835 * @param null $tableAlias
4837 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4839 $tableAlias = $this->_aliases
[$baseTable];
4841 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4842 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4843 $this->_from
.= " {$this->_aclFrom} ";
4847 * Join the temp table contacting contacts who are members of the filtered groups.
4849 * If we are using an IN filter we use an inner join, otherwise a left join.
4851 * @param string $baseTable
4852 * @param string $field
4853 * @param string $tableAlias
4855 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4856 if ($this->groupTempTable
) {
4857 if ($this->_params
['gid_op'] == 'in') {
4858 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4859 ON group_temp_table.id = $tableAlias.{$field} ";
4863 LEFT JOIN $this->groupTempTable group_temp_table
4864 ON $tableAlias.{$field} = group_temp_table.id ";
4870 * Get all labels for fields that are used in a group concat.
4872 * @param string $options
4873 * comma separated option values.
4874 * @param string $baoName
4875 * The BAO name for the field.
4876 * @param string $fieldName
4877 * The name of the field for which labels should be retrieved.
4881 public function getLabels($options, $baoName, $fieldName) {
4882 $types = explode(',', $options);
4884 foreach ($types as $value) {
4885 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
4887 return implode(', ', array_filter($labels));
4891 * Add statistics columns.
4893 * If a group by is in play then add columns for the statistics fields.
4895 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
4896 * column header field.
4898 * @param array $field
4899 * @param string $tableName
4900 * @param string $fieldName
4901 * @param array $select
4905 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
4906 foreach ($field['statistics'] as $stat => $label) {
4907 $alias = "{$tableName}_{$fieldName}_{$stat}";
4908 switch (strtolower($stat)) {
4911 $select[] = "$stat({$field['dbAlias']}) as $alias";
4912 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4913 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4914 $this->_statFields
[$label] = $alias;
4915 $this->_selectAliases
[] = $alias;
4919 $select[] = "COUNT({$field['dbAlias']}) as $alias";
4920 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4921 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4922 $this->_statFields
[$label] = $alias;
4923 $this->_selectAliases
[] = $alias;
4926 case 'count_distinct':
4927 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
4928 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4929 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4930 $this->_statFields
[$label] = $alias;
4931 $this->_selectAliases
[] = $alias;
4935 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
4936 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4937 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4938 $this->_statFields
[$label] = $alias;
4939 $this->_selectAliases
[] = $alias;
4947 * Add a basic field to the select clause.
4949 * @param string $tableName
4950 * @param string $fieldName
4951 * @param array $field
4952 * @param string $select
4955 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
4956 $alias = "{$tableName}_{$fieldName}";
4957 $select[] = "{$field['dbAlias']} as $alias";
4958 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
4959 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
4960 $this->_selectAliases
[] = $alias;