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();
365 * Array of clauses to group by.
369 protected $_groupByArray = array();
370 public $_groupBy = NULL;
371 public $_whereClauses = array();
372 public $_havingClauses = array();
375 * DashBoardRowCount Dashboard row count
378 public $_dashBoardRowCount;
381 * Is this being called without a form controller (ie. the report is being render outside the normal form
382 * - e.g the api is retrieving the rows
385 public $noController = FALSE;
388 * Variable to hold the currency alias
390 protected $_currencyColumn = NULL;
395 protected $_interval;
400 protected $_sendmail;
413 * @var string Report description.
415 public $_description;
418 * @var bool Is an address field selected.
419 * This was intended to determine if the address table should be joined in
420 * The isTableSelected function is now preferred for this purpose
422 protected $_addressField;
425 * @var bool Is an email field selected.
426 * This was intended to determine if the email table should be joined in
427 * The isTableSelected function is now preferred for this purpose
429 protected $_emailField;
432 * @var bool Is a phone field selected.
433 * This was intended to determine if the phone table should be joined in
434 * The isTableSelected function is now preferred for this purpose
436 protected $_phoneField;
439 * @var bool Create new report instance? (or update existing) on save.
441 protected $_createNew;
444 * When a grand total row has calculated the status we pop it off to here.
446 * This allows us to access it from the stats function and avoid recalculating.
448 protected $rollupRow = array();
451 * @var string Database attributes - character set and collation
453 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
456 * SQL being run in this report.
458 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
466 * SQL being run in this report as an array.
468 * The sql in the report is stored in this variable in order to be returned to api & test calls.
477 public function __construct() {
478 parent
::__construct();
480 $this->addClass('crm-report-form');
482 if ($this->_tagFilter
) {
483 $this->buildTagFilter();
485 if ($this->_exposeContactID
) {
486 if (array_key_exists('civicrm_contact', $this->_columns
)) {
487 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
489 'title' => ts('Contact ID'),
495 if ($this->_groupFilter
) {
496 $this->buildGroupFilter();
499 // Get all custom groups
500 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
502 // Get the custom groupIds for which the user has VIEW permission
503 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
504 // and addCustomDataToColumns() will allow access to all custom groups.
505 $permCustomGroupIds = array();
506 if (!CRM_Core_Permission
::check('access all custom data')) {
507 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
508 // do not allow custom data for reports if user doesn't have
509 // permission to access custom data.
510 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
511 $this->_customGroupExtends
= array();
515 // merge custom data columns to _columns list, if any
516 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
518 // add / modify display columns, filters ..etc
519 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
521 //assign currencyColumn variable to tpl
522 $this->assign('currencyColumn', $this->_currencyColumn
);
526 * Shared pre-process function.
528 * If overriding preProcess function this should still be called.
532 public function preProcessCommon() {
533 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
535 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
537 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
539 $this->assign('section', $this->_section
);
540 CRM_Core_Region
::instance('page-header')->add(array(
541 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
543 if (!$this->noController
) {
544 $this->setID($this->get('instanceId'));
547 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
549 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
553 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
554 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
555 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
559 $this->assign('instanceId', $this->_id
);
560 $params = array('id' => $this->_id
);
561 $this->_instanceValues
= array();
562 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
564 $this->_instanceValues
566 if (empty($this->_instanceValues
)) {
567 CRM_Core_Error
::fatal("Report could not be loaded.");
569 $this->_title
= $this->_instanceValues
['title'];
570 if (!empty($this->_instanceValues
['permission']) &&
571 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
572 CRM_Core_Permission
::check('administer Reports')
575 CRM_Utils_System
::permissionDenied();
576 CRM_Utils_System
::civiExit();
579 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
581 $this->_formValues
= unserialize($formValues);
584 $this->_formValues
= NULL;
587 $this->setOutputMode();
589 if ($this->_outputMode
== 'copy') {
590 $this->_createNew
= TRUE;
591 $this->_params
= $this->_formValues
;
592 $this->_params
['view_mode'] = 'criteria';
593 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
594 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
595 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
597 // Do not pass go. Do not collect another chance to re-run the same query.
598 CRM_Report_Form_Instance
::postProcess($this);
601 // lets always do a force if reset is found in the url.
602 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
603 // in the comment line above these 2.
604 if (!empty($_REQUEST['reset'])
605 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
610 $this->assign('mode', 'instance');
612 elseif (!$this->noController
) {
613 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
614 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
615 if (($instanceCount > 0) && $optionValueID) {
616 $this->assign('instanceUrl',
617 CRM_Utils_System
::url('civicrm/report/list',
618 "reset=1&ovid=$optionValueID"
622 if ($optionValueID) {
623 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
627 $this->assign('mode', 'template');
630 // lets display the Report Settings section
631 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
633 // Do not display Report Settings section if administer Reports permission is absent OR
634 // if report instance is reserved and administer reserved reports absent
635 if (!CRM_Core_Permission
::check('administer Reports') ||
636 ($this->_instanceValues
['is_reserved'] &&
637 !CRM_Core_Permission
::check('administer reserved reports'))
639 $this->_instanceForm
= FALSE;
642 $this->assign('criteriaForm', FALSE);
643 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
644 if (CRM_Core_Permission
::check('administer Reports') ||
645 CRM_Core_Permission
::check('access Report Criteria')
647 if (!$this->_instanceValues
['is_reserved'] ||
648 CRM_Core_Permission
::check('administer reserved reports')
650 $this->assign('criteriaForm', TRUE);
651 $this->_criteriaForm
= TRUE;
655 // Special permissions check for private instance if it's not the current contact instance
657 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
658 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
659 if (!CRM_Core_Permission
::check('access all private reports')) {
660 $this->_instanceForm
= FALSE;
661 $this->assign('criteriaForm', FALSE);
665 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
666 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
667 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
668 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
674 public function addBreadCrumb() {
678 'title' => ts('Report Templates'),
679 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
683 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
687 * Pre process function.
689 * Called prior to build form.
691 public function preProcess() {
692 $this->preProcessCommon();
695 $this->addBreadCrumb();
698 foreach ($this->_columns
as $tableName => $table) {
699 $this->setTableAlias($table, $tableName);
701 $expFields = array();
702 // higher preference to bao object
703 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
706 if (method_exists($daoOrBaoName, 'exportableFields')) {
707 $expFields = $daoOrBaoName::exportableFields();
710 $expFields = $daoOrBaoName::export();
714 $doNotCopy = array('required', 'default');
716 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
717 foreach ($fieldGroups as $fieldGrp) {
718 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
719 foreach ($table[$fieldGrp] as $fieldName => $field) {
720 // $name is the field name used to reference the BAO/DAO export fields array
721 $name = isset($field['name']) ?
$field['name'] : $fieldName;
723 // Sometimes the field name key in the BAO/DAO export fields array is
724 // different from the actual database field name.
725 // Unset $field['name'] so that actual database field name can be obtained
726 // from the BAO/DAO export fields array.
727 unset($field['name']);
729 if (array_key_exists($name, $expFields)) {
730 foreach ($doNotCopy as $dnc) {
731 // unset the values we don't want to be copied.
732 unset($expFields[$name][$dnc]);
735 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
738 foreach ($expFields[$name] as $property => $val) {
739 if (!array_key_exists($property, $field)) {
740 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
747 if (!empty($field['no_repeat'])) {
748 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
750 if (!empty($field['no_display'])) {
751 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
754 // set alias = table-name, unless already set
755 $alias = isset($field['alias']) ?
$field['alias'] : (
756 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
758 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
760 // set name = fieldName, unless already set
761 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
762 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
765 // set dbAlias = alias.name, unless already set
766 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
767 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
769 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
772 // a few auto fills for filters
773 if ($fieldGrp == 'filters') {
774 // fill operator types
775 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
776 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
777 case CRM_Utils_Type
::T_MONEY
:
778 case CRM_Utils_Type
::T_FLOAT
:
779 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
782 case CRM_Utils_Type
::T_INT
:
783 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
786 case CRM_Utils_Type
::T_DATE
:
787 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
790 case CRM_Utils_Type
::T_BOOLEAN
:
791 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
792 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
793 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
804 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
806 // with multiple options operator-type is generally multi-select
807 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
808 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
810 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
821 // copy filters to a separate handy variable
822 if (array_key_exists('filters', $table)) {
823 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
826 if (array_key_exists('group_bys', $table)) {
827 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
830 if (array_key_exists('fields', $table)) {
831 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
836 $this->setDefaultValues(FALSE);
839 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
840 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
841 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
842 CRM_Report_Utils_Get
::processChart($this->_defaults
);
845 $this->_formValues
= $this->_defaults
;
846 $this->postProcess();
851 * Set default values.
853 * @param bool $freeze
857 public function setDefaultValues($freeze = TRUE) {
858 $freezeGroup = array();
860 // FIXME: generalizing form field naming conventions would reduce
861 // Lots of lines below.
862 foreach ($this->_columns
as $tableName => $table) {
863 if (array_key_exists('fields', $table)) {
864 foreach ($table['fields'] as $fieldName => $field) {
865 if (empty($field['no_display'])) {
866 if (isset($field['required'])) {
868 $this->_defaults
['fields'][$fieldName] = 1;
871 // find element object, so that we could use quickform's freeze method
872 // for required elements
873 $obj = $this->getElementFromGroup("fields", $fieldName);
875 $freezeGroup[] = $obj;
879 elseif (isset($field['default'])) {
880 $this->_defaults
['fields'][$fieldName] = $field['default'];
886 if (array_key_exists('group_bys', $table)) {
887 foreach ($table['group_bys'] as $fieldName => $field) {
888 if (isset($field['default'])) {
889 if (!empty($field['frequency'])) {
890 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
892 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
896 if (array_key_exists('filters', $table)) {
897 foreach ($table['filters'] as $fieldName => $field) {
898 if (isset($field['default'])) {
899 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
901 if (is_array($field['default'])) {
902 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
903 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
904 $this->_defaults
["{$fieldName}_relative"] = 0;
907 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
911 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
912 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
913 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
915 $this->_defaults
["{$fieldName}_value"] = $field['default'];
918 //assign default value as "in" for multiselect
919 //operator, To freeze the select element
920 if (CRM_Utils_Array
::value('operatorType', $field) ==
921 CRM_Report_Form
::OP_MULTISELECT
923 $this->_defaults
["{$fieldName}_op"] = 'in';
925 if (CRM_Utils_Array
::value('operatorType', $field) ==
926 CRM_Report_Form
::OP_ENTITYREF
928 $this->_defaults
["{$fieldName}_op"] = 'in';
930 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
931 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
933 $this->_defaults
["{$fieldName}_op"] = 'mhas';
935 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
936 $this->_defaults
["{$fieldName}_op"] = $op;
942 empty($this->_formValues
['order_bys']) &&
943 (array_key_exists('order_bys', $table) &&
944 is_array($table['order_bys']))
946 if (!array_key_exists('order_bys', $this->_defaults
)) {
947 $this->_defaults
['order_bys'] = array();
949 foreach ($table['order_bys'] as $fieldName => $field) {
950 if (!empty($field['default']) ||
!empty($field['default_order']) ||
951 CRM_Utils_Array
::value('default_is_section', $field) ||
952 !empty($field['default_weight'])
955 'column' => $fieldName,
956 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
957 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
960 if (!empty($field['default_weight'])) {
961 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
964 array_unshift($this->_defaults
['order_bys'], $order_by);
970 foreach ($this->_options
as $fieldName => $field) {
971 if (isset($field['default'])) {
972 $this->_defaults
['options'][$fieldName] = $field['default'];
977 if (!empty($this->_submitValues
)) {
978 $this->preProcessOrderBy($this->_submitValues
);
981 $this->preProcessOrderBy($this->_defaults
);
984 // lets finish freezing task here itself
985 if (!empty($freezeGroup)) {
986 foreach ($freezeGroup as $elem) {
991 if ($this->_formValues
) {
992 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
995 if ($this->_instanceValues
) {
996 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
999 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1001 return $this->_defaults
;
1005 * Get element from group.
1007 * @param string $group
1008 * @param string $grpFieldName
1012 public function getElementFromGroup($group, $grpFieldName) {
1013 $eleObj = $this->getElement($group);
1014 foreach ($eleObj->_elements
as $index => $obj) {
1015 if ($grpFieldName == $obj->_attributes
['name']) {
1023 * Setter for $_params.
1025 * @param array $params
1027 public function setParams($params) {
1028 $this->_params
= $params;
1034 * @param int $instanceID
1036 public function setID($instanceID) {
1037 $this->_id
= $instanceID;
1041 * Setter for $_force.
1043 * @param bool $isForce
1045 public function setForce($isForce) {
1046 $this->_force
= $isForce;
1050 * Setter for $_limitValue.
1052 * @param int $_limitValue
1054 public function setLimitValue($_limitValue) {
1055 $this->_limitValue
= $_limitValue;
1059 * Setter for $_offsetValue.
1061 * @param int $_offsetValue
1063 public function setOffsetValue($_offsetValue) {
1064 $this->_offsetValue
= $_offsetValue;
1068 * Setter for $addPaging.
1070 * @param bool $value
1072 public function setAddPaging($value) {
1073 $this->addPaging
= $value;
1077 * Getter for $_defaultValues.
1081 public function getDefaultValues() {
1082 return $this->_defaults
;
1086 * Add columns to report.
1088 public function addColumns() {
1091 foreach ($this->_columns
as $tableName => $table) {
1092 if (array_key_exists('fields', $table)) {
1093 foreach ($table['fields'] as $fieldName => $field) {
1095 if (empty($field['no_display'])) {
1096 foreach (array('table', 'field') as $var) {
1097 if (!empty($
{$var}['grouping'])) {
1098 if (!is_array($
{$var}['grouping'])) {
1099 $tableName = $
{$var}['grouping'];
1102 $tableName = array_keys($
{$var}['grouping']);
1103 $tableName = $tableName[0];
1104 $groupTitle = array_values($
{$var}['grouping']);
1105 $groupTitle = $groupTitle[0];
1110 if (!$groupTitle && isset($table['group_title'])) {
1111 $groupTitle = $table['group_title'];
1112 // Having a group_title is secret code for being a custom group
1113 // which cryptically translates to needing an accordion.
1114 // here we make that explicit.
1115 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1118 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1119 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1120 $colGroups[$tableName]['group_title'] = $groupTitle;
1122 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1128 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1129 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1131 if (!empty($colGroups)) {
1132 $this->tabs
['FieldSelection'] = array(
1133 'title' => ts('Columns'),
1134 'tpl' => 'FieldSelection',
1135 'div_label' => 'col-groups',
1138 // Note this assignment is only really required in buildForm. It is being 'over-called'
1139 // to reduce risk of being missed due to overridden functions.
1140 $this->assign('tabs', $this->tabs
);
1143 $this->assign('colGroups', $colGroups);
1147 * Add filters to report.
1149 public function addFilters() {
1150 $filters = $filterGroups = array();
1153 foreach ($this->_filters
as $table => $attributes) {
1154 if (isset($this->_columns
[$table]['group_title'])) {
1155 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1156 // which magically means to 'display in an accordian'
1157 // here we make this explicit.
1158 $filterGroups[$table] = array(
1159 'group_title' => $this->_columns
[$table]['group_title'],
1160 'use_accordian_for_field_selection' => TRUE,
1164 foreach ($attributes as $fieldName => $field) {
1165 // get ready with option value pair
1166 // @ 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
1168 $operations = $this->getOperationPair(
1169 CRM_Utils_Array
::value('operatorType', $field),
1172 $filters[$table][$fieldName] = $field;
1174 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1175 case CRM_Report_Form
::OP_MONTH
:
1176 if (!array_key_exists('options', $field) ||
1177 !is_array($field['options']) ||
empty($field['options'])
1179 // If there's no option list for this filter, define one.
1180 $field['options'] = array(
1182 2 => ts('February'),
1189 9 => ts('September'),
1190 10 => ts('October'),
1191 11 => ts('November'),
1192 12 => ts('December'),
1194 // Add this option list to this column _columns. This is
1195 // required so that filter statistics show properly.
1196 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1198 case CRM_Report_Form
::OP_MULTISELECT
:
1199 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1200 // assume a multi-select field
1201 if (!empty($field['options']) ||
1202 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1204 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1205 if (count($operations) <= 1) {
1208 if ($fieldName == 'state_province_id' ||
1209 $fieldName == 'county_id'
1211 $this->addChainSelect($fieldName . '_value', array(
1218 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1219 'style' => 'min-width:250px',
1220 'class' => 'crm-select2 huge',
1222 'placeholder' => ts('- select -'),
1228 case CRM_Report_Form
::OP_SELECT
:
1229 // assume a select field
1230 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1231 if (!empty($field['options'])) {
1232 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1236 case CRM_Report_Form
::OP_ENTITYREF
:
1237 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1238 $this->setEntityRefDefaults($field, $table);
1239 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1242 case CRM_Report_Form
::OP_DATE
:
1243 // build datetime fields
1244 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1248 case CRM_Report_Form
::OP_DATETIME
:
1249 // build datetime fields
1250 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1254 case CRM_Report_Form
::OP_INT
:
1255 case CRM_Report_Form
::OP_FLOAT
:
1256 // and a min value input box
1257 $this->add('text', "{$fieldName}_min", ts('Min'));
1258 // and a max value input box
1259 $this->add('text', "{$fieldName}_max", ts('Max'));
1261 // default type is string
1262 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1263 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1265 // we need text box for value input
1266 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1271 if (!empty($filters)) {
1272 $this->tabs
['Filters'] = array(
1273 'title' => ts('Filters'),
1275 'div_label' => 'set-filters',
1278 $this->assign('filters', $filters);
1279 $this->assign('filterGroups', $filterGroups);
1283 * Function to assign the tabs to the template in the correct order.
1285 * We want the tabs to wind up in this order (if not overridden).
1293 protected function assignTabs() {
1301 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1302 $order = array_merge($order, $this->tabs
);
1303 $this->assign('tabs', $order);
1307 * The intent is to add a tab for developers to view the sql.
1309 * Currently using dpm.
1311 * @param string $sql
1313 protected function addToDeveloperTab($sql) {
1314 if (!CRM_Core_Permission
::check('view report sql')) {
1317 $this->tabs
['Developer'] = array(
1318 'title' => ts('Developer'),
1319 'tpl' => 'Developer',
1320 'div_label' => 'set-developer',
1323 $this->assignTabs();
1324 $this->sqlArray
[] = $sql;
1325 foreach ($this->sqlArray
as $sql) {
1326 foreach (array('LEFT JOIN') as $term) {
1327 $sql = str_replace($term, '<br>  ' . $term, $sql);
1329 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1330 $sql = str_replace($term, '<br><br>' . $term, $sql);
1332 $this->sqlFormattedArray
[] = $sql;
1333 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1338 * Add options defined in $this->_options to the report.
1340 public function addOptions() {
1341 if (!empty($this->_options
)) {
1342 // FIXME: For now lets build all elements as checkboxes.
1343 // Once we clear with the format we can build elements based on type
1345 foreach ($this->_options
as $fieldName => $field) {
1348 if ($field['type'] == 'select') {
1349 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1351 elseif ($field['type'] == 'checkbox') {
1352 $options[$field['title']] = $fieldName;
1353 $this->addCheckBox($fieldName, NULL,
1355 NULL, NULL, NULL, $this->_fourColumnAttribute
1360 if (!empty($this->_options
) &&
1362 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1364 $this->tabs
['ReportOptions'] = array(
1365 'title' => ts('Display Options'),
1366 'tpl' => 'ReportOptions',
1367 'div_label' => 'other-options',
1370 $this->assign('otherOptions', $this->_options
);
1374 * Add chart options to the report.
1376 public function addChartOptions() {
1377 if (!empty($this->_charts
)) {
1378 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1379 $this->assign('charts', $this->_charts
);
1380 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1385 * Add group by options to the report.
1387 public function addGroupBys() {
1388 $options = $freqElements = array();
1390 foreach ($this->_columns
as $tableName => $table) {
1391 if (array_key_exists('group_bys', $table)) {
1392 foreach ($table['group_bys'] as $fieldName => $field) {
1393 if (!empty($field)) {
1394 $options[$field['title']] = $fieldName;
1395 if (!empty($field['frequency'])) {
1396 $freqElements[$field['title']] = $fieldName;
1402 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1403 NULL, NULL, NULL, $this->_fourColumnAttribute
1405 $this->assign('groupByElements', $options);
1406 if (!empty($options)) {
1407 $this->tabs
['GroupBy'] = array(
1408 'title' => ts('Grouping'),
1410 'div_label' => 'group-by-elements',
1414 foreach ($freqElements as $name) {
1415 $this->addElement('select', "group_bys_freq[$name]",
1416 ts('Frequency'), $this->_groupByDateFreq
1422 * Add data for order by tab.
1424 public function addOrderBys() {
1426 foreach ($this->_columns
as $tableName => $table) {
1428 // Report developer may define any column to order by; include these as order-by options.
1429 if (array_key_exists('order_bys', $table)) {
1430 foreach ($table['order_bys'] as $fieldName => $field) {
1431 if (!empty($field)) {
1432 $options[$fieldName] = $field['title'];
1437 // Add searchable custom fields as order-by options, if so requested
1438 // (These are already indexed, so allowing to order on them is cheap.)
1440 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1441 array_key_exists('extends', $table) && !empty($table['extends'])
1443 foreach ($table['fields'] as $fieldName => $field) {
1444 if (empty($field['no_display'])) {
1445 $options[$fieldName] = $field['title'];
1453 $this->assign('orderByOptions', $options);
1454 if (!empty($options)) {
1455 $this->tabs
['OrderBy'] = array(
1456 'title' => ts('Sorting'),
1458 'div_label' => 'order-by-elements',
1462 if (!empty($options)) {
1464 '-' => ' - none - ',
1466 for ($i = 1; $i <= 5; $i++
) {
1467 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1468 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1469 'ASC' => ts('Ascending'),
1470 'DESC' => ts('Descending'),
1472 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1473 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1479 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1481 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1482 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1485 public function buildInstanceAndButtons() {
1486 CRM_Report_Form_Instance
::buildForm($this);
1487 $this->_actionButtonName
= $this->getButtonName('submit');
1488 $this->addTaskMenu($this->getActions($this->_id
));
1490 $this->assign('instanceForm', $this->_instanceForm
);
1492 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1493 $permission = CRM_Core_Permission
::getPermission();
1494 if ($permission == CRM_Core_Permission
::EDIT
&&
1495 $this->_add2groupSupported
1497 $this->addElement('select', 'groups', ts('Group'),
1498 array('' => ts('Add Contacts to Group')) +
1499 CRM_Core_PseudoConstant
::nestedGroup(),
1500 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1502 $this->assign('group', TRUE);
1505 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1507 $this->addChartOptions();
1508 $showResultsLabel = $this->getResultsLabel();
1509 $this->addButtons(array(
1512 'name' => $showResultsLabel,
1513 'isDefault' => TRUE,
1520 * Has this form been submitted already?
1524 public function resultsDisplayed() {
1525 $buttonName = $this->controller
->getButtonName();
1526 return ($buttonName ||
$this->_outputMode
);
1530 * Get the actions for this report instance.
1532 * @param int $instanceId
1536 protected function getActions($instanceId) {
1537 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1538 if (empty($instanceId)) {
1539 $actions['report_instance.save'] = array(
1540 'title' => ts('Create Report'),
1542 'is_confirm' => TRUE,
1543 'confirm_title' => ts('Create Report'),
1544 'confirm_refresh_fields' => json_encode(array(
1545 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1546 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1552 if (!$this->_csvSupported
) {
1553 unset($actions['report_instance.csv']);
1560 * Main build form function.
1562 public function buildQuickForm() {
1563 $this->addColumns();
1565 $this->addFilters();
1567 $this->addOptions();
1569 $this->addGroupBys();
1571 $this->addOrderBys();
1573 $this->buildInstanceAndButtons();
1575 // Add form rule for report.
1576 if (is_callable(array(
1580 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1582 $this->assignTabs();
1586 * A form rule function for custom data.
1588 * The rule ensures that fields selected in group_by if any) should only be the ones
1589 * present in display/select fields criteria;
1590 * note: works if and only if any custom field selected in group_by.
1592 * @param array $fields
1593 * @param array $ignoreFields
1597 public function customDataFormRule($fields, $ignoreFields = array()) {
1599 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1600 !empty($fields['group_bys'])
1602 foreach ($this->_columns
as $tableName => $table) {
1603 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1604 substr($tableName, 0, 12) == 'custom_value') &&
1605 !empty($this->_columns
[$tableName]['fields'])
1607 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1608 if (array_key_exists($fieldName, $fields['group_bys']) &&
1609 !array_key_exists($fieldName, $fields['fields'])
1611 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1613 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1614 foreach ($fields['fields'] as $fld => $val) {
1615 if (!array_key_exists($fld, $fields['group_bys']) &&
1616 !in_array($fld, $ignoreFields)
1618 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1630 * Get operators to display on form.
1632 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1634 * @param string $type
1635 * @param string $fieldName
1639 public function getOperationPair($type = "string", $fieldName = NULL) {
1640 // FIXME: At some point we should move these key-val pairs
1641 // to option_group and option_value table.
1643 case CRM_Report_Form
::OP_INT
:
1644 case CRM_Report_Form
::OP_FLOAT
:
1647 'lte' => ts('Is less than or equal to'),
1648 'gte' => ts('Is greater than or equal to'),
1649 'bw' => ts('Is between'),
1650 'eq' => ts('Is equal to'),
1651 'lt' => ts('Is less than'),
1652 'gt' => ts('Is greater than'),
1653 'neq' => ts('Is not equal to'),
1654 'nbw' => ts('Is not between'),
1655 'nll' => ts('Is empty (Null)'),
1656 'nnll' => ts('Is not empty (Null)'),
1660 case CRM_Report_Form
::OP_SELECT
:
1662 'eq' => ts('Is equal to'),
1666 case CRM_Report_Form
::OP_MONTH
:
1667 case CRM_Report_Form
::OP_MULTISELECT
:
1668 case CRM_Report_Form
::OP_ENTITYREF
:
1671 'in' => ts('Is one of'),
1672 'notin' => ts('Is not one of'),
1676 case CRM_Report_Form
::OP_DATE
:
1679 'nll' => ts('Is empty (Null)'),
1680 'nnll' => ts('Is not empty (Null)'),
1684 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1685 // use this operator for the values, concatenated with separator. For e.g if
1686 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1688 'mhas' => ts('Is one of'),
1689 'mnot' => ts('Is not one of'),
1696 'has' => ts('Contains'),
1697 'sw' => ts('Starts with'),
1698 'ew' => ts('Ends with'),
1699 'nhas' => ts('Does not contain'),
1700 'eq' => ts('Is equal to'),
1701 'neq' => ts('Is not equal to'),
1702 'nll' => ts('Is empty (Null)'),
1703 'nnll' => ts('Is not empty (Null)'),
1710 * Build the tag filter field to display on the filters tab.
1712 public function buildTagFilter() {
1713 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1714 if (!empty($contactTags)) {
1715 $this->_columns
['civicrm_tag'] = array(
1716 'dao' => 'CRM_Core_DAO_Tag',
1720 'title' => ts('Tag'),
1721 'type' => CRM_Utils_Type
::T_INT
,
1723 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1724 'options' => $contactTags,
1732 * Adds group filters to _columns (called from _Construct).
1734 public function buildGroupFilter() {
1735 $this->_columns
['civicrm_group']['filters'] = array(
1737 'name' => 'group_id',
1738 'title' => ts('Group'),
1739 'type' => CRM_Utils_Type
::T_INT
,
1740 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1742 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1745 if (empty($this->_columns
['civicrm_group']['dao'])) {
1746 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1748 if (empty($this->_columns
['civicrm_group']['alias'])) {
1749 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1754 * Get SQL operator from form text version.
1756 * @param string $operator
1760 public function getSQLOperator($operator = "like") {
1761 switch ($operator) {
1794 return 'IS NOT NULL';
1803 * Generate where clause.
1805 * This can be overridden in reports for special treatment of a field
1807 * @param array $field Field specifications
1808 * @param string $op Query operator (not an exact match to sql)
1809 * @param mixed $value
1813 * @return null|string
1815 public function whereClause(&$field, $op, $value, $min, $max) {
1817 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1819 // CRM-18010: Ensure type of each report filters
1821 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1828 if (($min !== NULL && strlen($min) > 0) ||
1829 ($max !== NULL && strlen($max) > 0)
1833 $min = CRM_Utils_Type
::escape($min, $type);
1835 $clauses[] = "( {$field['dbAlias']} >= $min )";
1838 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1842 $max = CRM_Utils_Type
::escape($max, $type);
1844 $clauses[] = "( {$field['dbAlias']} <= $max )";
1847 $clauses[] = "( {$field['dbAlias']} > $max )";
1851 if (!empty($clauses)) {
1853 $clause = implode(' AND ', $clauses);
1856 $clause = '(' . implode('OR', $clauses) . ')';
1864 if ($value !== NULL && strlen($value) > 0) {
1865 $value = CRM_Utils_Type
::escape($value, $type);
1866 if (strpos($value, '%') === FALSE) {
1867 $value = "'%{$value}%'";
1870 $value = "'{$value}'";
1872 $sqlOP = $this->getSQLOperator($op);
1873 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1879 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1880 $value = explode(',', $value);
1882 if ($value !== NULL && is_array($value) && count($value) > 0) {
1883 $sqlOP = $this->getSQLOperator($op);
1884 if (CRM_Utils_Array
::value('type', $field) ==
1885 CRM_Utils_Type
::T_STRING
1887 //cycle through selections and escape values
1888 foreach ($value as $key => $selection) {
1889 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1892 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1896 // for numerical values
1897 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1900 if ($op == 'notin') {
1901 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1904 $clause = "( " . $clause . " )";
1911 // multiple has or multiple not
1912 if ($value !== NULL && count($value) > 0) {
1913 $value = CRM_Utils_Type
::escapeAll($value, $type);
1914 $operator = $op == 'mnot' ?
'NOT' : '';
1915 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1916 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1922 if ($value !== NULL && strlen($value) > 0) {
1923 $value = CRM_Utils_Type
::escape($value, $type);
1924 if (strpos($value, '%') === FALSE) {
1926 $value = "'{$value}%'";
1929 $value = "'%{$value}'";
1933 $value = "'{$value}'";
1935 $sqlOP = $this->getSQLOperator($op);
1936 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1942 $sqlOP = $this->getSQLOperator($op);
1943 $clause = "( {$field['dbAlias']} $sqlOP )";
1949 //CRM-18457: some custom field passes value in array format against binary operator
1950 if (is_array($value) && count($value)) {
1955 if ($value !== NULL && $value !== '') {
1956 if (isset($field['clause'])) {
1957 // FIXME: we not doing escape here. Better solution is to use two
1958 // different types - data-type and filter-type
1959 $clause = $field['clause'];
1961 elseif (!is_array($value)) {
1962 $value = CRM_Utils_Type
::escape($value, $type);
1963 $sqlOP = $this->getSQLOperator($op);
1964 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1965 $value = "'{$value}'";
1967 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1973 if (!empty($field['group']) && $clause) {
1974 $clause = $this->whereGroupClause($field, $value, $op);
1976 elseif (!empty($field['tag']) && $clause) {
1977 // not using left join in query because if any contact
1978 // belongs to more than one tag, results duplicate
1980 $clause = $this->whereTagClause($field, $value, $op);
1982 elseif (!empty($field['membership_org']) && $clause) {
1983 $clause = $this->whereMembershipOrgClause($value, $op);
1985 elseif (!empty($field['membership_type']) && $clause) {
1986 $clause = $this->whereMembershipTypeClause($value, $op);
1992 * Get SQL where clause for a date field.
1994 * @param string $fieldName
1995 * @param string $relative
1996 * @param string $from
1998 * @param string $type
1999 * @param string $fromTime
2000 * @param string $toTime
2002 * @return null|string
2004 public function dateClause(
2006 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2009 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2010 $sqlOP = $this->getSQLOperator($relative);
2011 return "( {$fieldName} {$sqlOP} )";
2014 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2017 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2018 $clauses[] = "( {$fieldName} >= $from )";
2022 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2023 $clauses[] = "( {$fieldName} <= {$to} )";
2026 if (!empty($clauses)) {
2027 return implode(' AND ', $clauses);
2034 * Get values for from and to for date ranges.
2036 * @param bool $relative
2037 * @param string $from
2039 * @param string $fromTime
2040 * @param string $toTime
2044 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2045 if (empty($toTime)) {
2048 //FIX ME not working for relative
2050 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2051 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2052 $from = substr($dateRange['from'], 0, 8);
2053 //Take only Date Part, Sometime Time part is also present in 'to'
2054 $to = substr($dateRange['to'], 0, 8);
2056 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2057 $to = CRM_Utils_Date
::processDate($to, $toTime);
2058 return array($from, $to);
2062 * Alter display of rows.
2064 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2065 * such as rendering contacts as links.
2067 * @param array $rows
2068 * Rows generated by SQL, with an array for each row.
2070 public function alterDisplay(&$rows) {
2074 * Alter the way in which custom data fields are displayed.
2076 * @param array $rows
2078 public function alterCustomDataDisplay(&$rows) {
2079 // custom code to alter rows having custom values
2080 if (empty($this->_customGroupExtends
)) {
2084 $customFields = array();
2085 $customFieldIds = array();
2086 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2087 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2088 $customFieldIds[$fieldAlias] = $fieldId;
2091 if (empty($customFieldIds)) {
2095 // skip for type date and ContactReference since date format is already handled
2097 SELECT cg.table_name, cf.id
2098 FROM civicrm_custom_field cf
2099 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2100 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2101 cg.is_active = 1 AND
2102 cf.is_active = 1 AND
2103 cf.is_searchable = 1 AND
2104 cf.data_type NOT IN ('ContactReference', 'Date') AND
2105 cf.id IN (" . implode(",", $customFieldIds) . ")";
2107 $dao = CRM_Core_DAO
::executeQuery($query);
2108 while ($dao->fetch()) {
2109 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2113 $entryFound = FALSE;
2114 foreach ($rows as $rowNum => $row) {
2115 foreach ($row as $tableCol => $val) {
2116 if (array_key_exists($tableCol, $customFields)) {
2117 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2122 // skip looking further in rows, if first row itself doesn't
2123 // have the column we need
2131 * Remove duplicate rows.
2133 * @param array $rows
2135 public function removeDuplicates(&$rows) {
2136 if (empty($this->_noRepeats
)) {
2139 $checkList = array();
2141 foreach ($rows as $key => $list) {
2142 foreach ($list as $colName => $colVal) {
2143 if (array_key_exists($colName, $checkList) &&
2144 $checkList[$colName] == $colVal
2146 $rows[$key][$colName] = "";
2148 if (in_array($colName, $this->_noRepeats
)) {
2149 $checkList[$colName] = $colVal;
2156 * Fix subtotal display.
2159 * @param array $fields
2160 * @param bool $subtotal
2162 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2163 foreach ($row as $colName => $colVal) {
2164 if (in_array($colName, $fields)) {
2166 elseif (isset($this->_columnHeaders
[$colName])) {
2168 $row[$colName] = 'Subtotal';
2172 unset($row[$colName]);
2179 * Calculate grant total.
2181 * @param array $rows
2185 public function grandTotal(&$rows) {
2186 if (!$this->_rollup ||
count($rows) == 1) {
2190 $this->moveSummaryColumnsToTheRightHandSide();
2192 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2196 $this->rollupRow
= array_pop($rows);
2198 foreach ($this->_columnHeaders
as $fld => $val) {
2199 if (!in_array($fld, $this->_statFields
)) {
2200 if (!$this->_grandFlag
) {
2201 $this->rollupRow
[$fld] = ts('Grand Total');
2202 $this->_grandFlag
= TRUE;
2205 $this->rollupRow
[$fld] = "";
2210 $this->assign('grandStat', $this->rollupRow
);
2215 * Format display output.
2217 * @param array $rows
2218 * @param bool $pager
2220 public function formatDisplay(&$rows, $pager = TRUE) {
2221 // set pager based on if any limit was applied in the query.
2226 // allow building charts if any
2227 if (!empty($this->_params
['charts']) && !empty($rows)) {
2228 $this->buildChart($rows);
2229 $this->assign('chartEnabled', TRUE);
2230 $this->_chartId
= "{$this->_params['charts']}_" .
2231 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2233 $this->assign('chartId', $this->_chartId
);
2236 // unset columns not to be displayed.
2237 foreach ($this->_columnHeaders
as $key => $value) {
2238 if (!empty($value['no_display'])) {
2239 unset($this->_columnHeaders
[$key]);
2243 // unset columns not to be displayed.
2244 if (!empty($rows)) {
2245 foreach ($this->_noDisplay
as $noDisplayField) {
2246 foreach ($rows as $rowNum => $row) {
2247 unset($this->_columnHeaders
[$noDisplayField]);
2252 // build array of section totals
2253 $this->sectionTotals();
2255 // process grand-total row
2256 $this->grandTotal($rows);
2258 // use this method for formatting rows for display purpose.
2259 $this->alterDisplay($rows);
2260 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2262 // use this method for formatting custom rows for display purpose.
2263 $this->alterCustomDataDisplay($rows);
2269 * @param array $rows
2271 public function buildChart(&$rows) {
2272 // override this method for building charts.
2275 // select() method below has been added recently (v3.3), and many of the report templates might
2276 // still be having their own select() method. We should fix them as and when encountered and move
2277 // towards generalizing the select() method below.
2280 * Generate the SELECT clause and set class variable $_select.
2282 public function select() {
2283 $select = $this->_selectAliases
= array();
2285 foreach ($this->_columns
as $tableName => $table) {
2286 if (array_key_exists('fields', $table)) {
2287 foreach ($table['fields'] as $fieldName => $field) {
2288 if ($tableName == 'civicrm_address') {
2289 // deprecated, use $this->isTableSelected.
2290 $this->_addressField
= TRUE;
2292 if ($tableName == 'civicrm_email') {
2293 $this->_emailField
= TRUE;
2295 if ($tableName == 'civicrm_phone') {
2296 $this->_phoneField
= TRUE;
2299 if (!empty($field['required']) ||
2300 !empty($this->_params
['fields'][$fieldName])
2303 // 1. In many cases we want select clause to be built in slightly different way
2304 // for a particular field of a particular type.
2305 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2307 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2308 if ($selectClause) {
2309 $select[] = $selectClause;
2313 // include statistics columns only if set
2314 if (!empty($field['statistics'])) {
2315 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2318 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2324 // select for group bys
2325 if (array_key_exists('group_bys', $table)) {
2326 foreach ($table['group_bys'] as $fieldName => $field) {
2328 if ($tableName == 'civicrm_address') {
2329 $this->_addressField
= TRUE;
2331 if ($tableName == 'civicrm_email') {
2332 $this->_emailField
= TRUE;
2334 if ($tableName == 'civicrm_phone') {
2335 $this->_phoneField
= TRUE;
2337 // 1. In many cases we want select clause to be built in slightly different way
2338 // for a particular field of a particular type.
2339 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2341 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2342 if ($selectClause) {
2343 $select[] = $selectClause;
2347 if (!empty($this->_params
['group_bys']) &&
2348 !empty($this->_params
['group_bys'][$fieldName]) &&
2349 !empty($this->_params
['group_bys_freq'])
2351 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2353 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2354 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2355 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2356 $field['title'] = 'Week';
2360 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2361 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2362 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2363 $field['title'] = 'Year';
2367 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2368 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2369 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2370 $field['title'] = 'Month';
2374 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2375 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2376 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2377 $field['title'] = 'Quarter';
2380 // for graphs and charts -
2381 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2382 $this->_interval
= $field['title'];
2383 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2384 = $field['title'] . ' Beginning';
2385 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2386 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2388 // just to make sure these values are transferred to rows.
2389 // since we 'll need them for calculation purpose,
2390 // e.g making subtotals look nicer or graphs
2391 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2392 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2399 $this->_selectClauses
= $select;
2400 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2404 * Build select clause for a single field.
2406 * @param string $tableName
2407 * @param string $tableKey
2408 * @param string $fieldName
2409 * @param string $field
2413 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2418 * Build where clause.
2420 public function where() {
2421 $this->storeWhereHavingClauseArray();
2423 if (empty($this->_whereClauses
)) {
2424 $this->_where
= "WHERE ( 1 ) ";
2425 $this->_having
= "";
2428 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2431 if ($this->_aclWhere
) {
2432 $this->_where
.= " AND {$this->_aclWhere} ";
2435 if (!empty($this->_havingClauses
)) {
2436 // use this clause to construct group by clause.
2437 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2442 * Store Where clauses into an array.
2444 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2445 * temp table that may not be part of the final where clause or added
2446 * in other functions
2448 public function storeWhereHavingClauseArray() {
2449 foreach ($this->_columns
as $tableName => $table) {
2450 if (array_key_exists('filters', $table)) {
2451 foreach ($table['filters'] as $fieldName => $field) {
2452 // respect pseudofield to filter spec so fields can be marked as
2453 // not to be handled here
2454 if (!empty($field['pseudofield'])) {
2458 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2459 if (CRM_Utils_Array
::value('operatorType', $field) ==
2460 CRM_Report_Form
::OP_MONTH
2462 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2463 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2464 if (is_array($value) && !empty($value)) {
2466 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2471 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2472 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2473 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2474 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2475 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2476 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2480 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2482 $clause = $this->whereClause($field,
2484 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2485 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2486 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2491 if (!empty($clause)) {
2492 if (!empty($field['having'])) {
2493 $this->_havingClauses
[] = $clause;
2496 $this->_whereClauses
[] = $clause;
2508 public function processReportMode() {
2509 $this->setOutputMode();
2512 = CRM_Utils_Request
::retrieve(
2515 CRM_Core_DAO
::$_nullObject
2518 $this->_absoluteUrl
= FALSE;
2520 $this->assign('printOnly', FALSE);
2522 if ($this->_outputMode
== 'print' ||
2523 ($this->_sendmail
&& !$this->_outputMode
)
2525 $this->assign('printOnly', TRUE);
2527 $this->addPaging
= FALSE;
2528 $this->assign('outputMode', 'print');
2529 $this->_outputMode
= 'print';
2530 if ($this->_sendmail
) {
2531 $this->_absoluteUrl
= TRUE;
2534 elseif ($this->_outputMode
== 'pdf') {
2536 $this->addPaging
= FALSE;
2537 $this->_absoluteUrl
= TRUE;
2539 elseif ($this->_outputMode
== 'csv') {
2541 $this->_absoluteUrl
= TRUE;
2542 $this->addPaging
= FALSE;
2544 elseif ($this->_outputMode
== 'group') {
2545 $this->assign('outputMode', 'group');
2547 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2548 $this->assign('outputMode', 'create_report');
2550 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2551 $this->_createNew
= TRUE;
2554 $this->assign('outputMode', $this->_outputMode
);
2555 $this->assign('printOnly', $printOnly);
2556 // Get today's date to include in printed reports
2558 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2559 $this->assign('reportDate', $reportDate);
2564 * Post Processing function for Form.
2566 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2567 * This function is not accessed when the api calls the report.
2569 public function beginPostProcess() {
2570 $this->setParams($this->controller
->exportValues($this->_name
));
2571 if (empty($this->_params
) &&
2574 $this->setParams($this->_formValues
);
2577 // hack to fix params when submitted from dashboard, CRM-8532
2578 // fields array is missing because form building etc is skipped
2579 // in dashboard mode for report
2580 //@todo - this could be done in the dashboard no we have a setter
2581 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2582 $this->setParams($this->_formValues
);
2585 $this->processReportMode();
2587 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2588 $this->_createNew
= ($this->_outputMode
== 'copy');
2589 CRM_Report_Form_Instance
::postProcess($this);
2591 if ($this->_outputMode
== 'delete') {
2592 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2595 $this->_formValues
= $this->_params
;
2597 $this->beginPostProcessCommon();
2601 * BeginPostProcess function run in both report mode and non-report mode (api).
2603 public function beginPostProcessCommon() {
2607 * Build the report query.
2609 * @param bool $applyLimit
2613 public function buildQuery($applyLimit = TRUE) {
2614 $this->buildGroupTempTable();
2617 $this->customDataFrom();
2618 $this->buildPermissionClause();
2620 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2621 $this->getPermissionedFTQuery($this);
2626 // order_by columns not selected for display need to be included in SELECT
2627 $unselectedSectionColumns = $this->unselectedSectionColumns();
2628 foreach ($unselectedSectionColumns as $alias => $section) {
2629 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2632 if ($applyLimit && empty($this->_params
['charts'])) {
2635 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2637 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2638 $this->addToDeveloperTab($sql);
2643 * Build group by clause.
2645 public function groupBy() {
2646 if (!empty($this->_params
['group_bys']) &&
2647 is_array($this->_params
['group_bys'])
2649 foreach ($this->_columns
as $tableName => $table) {
2650 if (array_key_exists('group_bys', $table)) {
2651 foreach ($table['group_bys'] as $fieldName => $field) {
2652 if (!empty($this->_params
['group_bys'][$fieldName])) {
2653 $this->_groupByArray
[] = $field['dbAlias'];
2660 if (!empty($this->_groupByArray
)) {
2661 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2666 * Build order by clause.
2668 public function orderBy() {
2669 $this->_orderBy
= "";
2670 $this->_sections
= array();
2671 $this->storeOrderByArray();
2672 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2673 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2675 $this->assign('sections', $this->_sections
);
2679 * Extract order by fields and store as an array.
2681 * In some cases other functions want to know which fields are selected for ordering by
2682 * Separating this into a separate function allows it to be called separately from constructing
2683 * the order by clause
2685 public function storeOrderByArray() {
2686 $orderBys = array();
2688 if (!empty($this->_params
['order_bys']) &&
2689 is_array($this->_params
['order_bys']) &&
2690 !empty($this->_params
['order_bys'])
2693 // Process order_bys in user-specified order
2694 foreach ($this->_params
['order_bys'] as $orderBy) {
2695 $orderByField = array();
2696 foreach ($this->_columns
as $tableName => $table) {
2697 if (array_key_exists('order_bys', $table)) {
2698 // For DAO columns defined in $this->_columns
2699 $fields = $table['order_bys'];
2701 elseif (array_key_exists('extends', $table)) {
2702 // For custom fields referenced in $this->_customGroupExtends
2703 $fields = CRM_Utils_Array
::value('fields', $table, array());
2708 if (!empty($fields) && is_array($fields)) {
2709 foreach ($fields as $fieldName => $field) {
2710 if ($fieldName == $orderBy['column']) {
2711 $orderByField = array_merge($field, $orderBy);
2712 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2719 if (!empty($orderByField)) {
2720 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2721 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2723 // Record any section headers for assignment to the template
2724 if (!empty($orderBy['section'])) {
2725 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2726 $this->_sections
[$orderByField['tplField']] = $orderByField;
2732 $this->_orderByArray
= $orderBys;
2734 $this->assign('sections', $this->_sections
);
2738 * Determine unselected columns.
2742 public function unselectedSectionColumns() {
2743 if (is_array($this->_sections
)) {
2744 return array_diff_key($this->_sections
, $this->getSelectColumns());
2752 * Build output rows.
2754 * @param string $sql
2755 * @param array $rows
2757 public function buildRows($sql, &$rows) {
2758 $dao = CRM_Core_DAO
::executeQuery($sql);
2759 if (!is_array($rows)) {
2763 // use this method to modify $this->_columnHeaders
2764 $this->modifyColumnHeaders();
2766 $unselectedSectionColumns = $this->unselectedSectionColumns();
2768 while ($dao->fetch()) {
2770 foreach ($this->_columnHeaders
as $key => $value) {
2771 if (property_exists($dao, $key)) {
2772 $row[$key] = $dao->$key;
2776 // section headers not selected for display need to be added to row
2777 foreach ($unselectedSectionColumns as $key => $values) {
2778 if (property_exists($dao, $key)) {
2779 $row[$key] = $dao->$key;
2788 * Calculate section totals.
2790 * When "order by" fields are marked as sections, this assigns to the template
2791 * an array of total counts for each section. This data is used by the Smarty
2792 * plugin {sectionTotal}.
2794 public function sectionTotals() {
2796 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2797 if (empty($this->_selectAliases
)) {
2801 if (!empty($this->_sections
)) {
2802 // build the query with no LIMIT clause
2803 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2804 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2806 // pull section aliases out of $this->_sections
2807 $sectionAliases = array_keys($this->_sections
);
2810 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2811 $ifnulls[] = "ifnull($alias, '') as $alias";
2813 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2814 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2816 // Group (un-limited) report by all aliases and get counts. This might
2817 // be done more efficiently when the contents of $sql are known, ie. by
2818 // overriding this method in the report class.
2820 $query = $this->_select
.
2821 ", count(*) as ct from ($sql) as subquery group by " .
2822 implode(", ", $sectionAliases);
2824 // initialize array of total counts
2826 $dao = CRM_Core_DAO
::executeQuery($query);
2827 while ($dao->fetch()) {
2829 // let $this->_alterDisplay translate any integer ids to human-readable values.
2830 $rows[0] = $dao->toArray();
2831 $this->alterDisplay($rows);
2834 // add totals for all permutations of section values
2837 $aliasCount = count($sectionAliases);
2838 foreach ($sectionAliases as $alias) {
2839 $values[] = $row[$alias];
2840 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2841 if ($i == $aliasCount) {
2842 // the last alias is the lowest-level section header; use count as-is
2843 $totals[$key] = $dao->ct
;
2846 // other aliases are higher level; roll count into their total
2847 $totals[$key] +
= $dao->ct
;
2851 $this->assign('sectionTotals', $totals);
2856 * Modify column headers.
2858 public function modifyColumnHeaders() {
2859 // use this method to modify $this->_columnHeaders
2863 * Move totals columns to the right edge of the table.
2865 * It seems like a more logical layout to have any totals columns on the far right regardless of
2866 * the location of the rest of their table.
2868 public function moveSummaryColumnsToTheRightHandSide() {
2869 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2870 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2874 * Assign rows to the template.
2876 * @param array $rows
2878 public function doTemplateAssignment(&$rows) {
2879 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2880 $this->assign_by_ref('rows', $rows);
2881 $this->assign('statistics', $this->statistics($rows));
2885 * Build report statistics.
2887 * Override this method to build your own statistics.
2889 * @param array $rows
2893 public function statistics(&$rows) {
2894 $statistics = array();
2896 $count = count($rows);
2897 // Why do we increment the count for rollup seems to artificially inflate the count.
2898 // It seems perhaps intentional to include the summary row in the count of results - although
2899 // this just seems odd.
2900 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2904 $this->countStat($statistics, $count);
2906 $this->groupByStat($statistics);
2908 $this->filterStat($statistics);
2914 * Add count statistics.
2916 * @param array $statistics
2919 public function countStat(&$statistics, $count) {
2920 $statistics['counts']['rowCount'] = array(
2921 'title' => ts('Row(s) Listed'),
2925 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2926 $statistics['counts']['rowsFound'] = array(
2927 'title' => ts('Total Row(s)'),
2928 'value' => $this->_rowsFound
,
2934 * Add group by statistics.
2936 * @param array $statistics
2938 public function groupByStat(&$statistics) {
2939 if (!empty($this->_params
['group_bys']) &&
2940 is_array($this->_params
['group_bys']) &&
2941 !empty($this->_params
['group_bys'])
2943 foreach ($this->_columns
as $tableName => $table) {
2944 if (array_key_exists('group_bys', $table)) {
2945 foreach ($table['group_bys'] as $fieldName => $field) {
2946 if (!empty($this->_params
['group_bys'][$fieldName])) {
2947 $combinations[] = $field['title'];
2952 $statistics['groups'][] = array(
2953 'title' => ts('Grouping(s)'),
2954 'value' => implode(' & ', $combinations),
2960 * Filter statistics.
2962 * @param array $statistics
2964 public function filterStat(&$statistics) {
2965 foreach ($this->_columns
as $tableName => $table) {
2966 if (array_key_exists('filters', $table)) {
2967 foreach ($table['filters'] as $fieldName => $field) {
2968 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2969 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2970 CRM_Utils_Array
::value('operatorType', $field) !=
2971 CRM_Report_Form
::OP_MONTH
2975 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2976 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2977 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2978 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2979 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2981 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2982 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2984 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2985 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2988 $statistics['filters'][] = array(
2989 'title' => $field['title'],
2990 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2993 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2994 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2996 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2997 $statistics['filters'][] = array(
2998 'title' => $field['title'],
2999 'value' => $pair[$rel],
3004 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3007 $pair = $this->getOperationPair(
3008 CRM_Utils_Array
::value('operatorType', $field),
3011 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3012 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3013 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3014 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3015 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3017 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3018 $this->setEntityRefDefaults($field, $tableName);
3019 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3020 array('id' => $val) +
3021 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3023 foreach ($result['values'] as $v) {
3024 $values[] = $v['label'];
3026 $value = "{$pair[$op]} " . implode(', ', $values);
3028 elseif ($op == 'nll' ||
$op == 'nnll') {
3029 $value = $pair[$op];
3031 elseif (is_array($val) && (!empty($val))) {
3032 $options = CRM_Utils_Array
::value('options', $field, array());
3033 foreach ($val as $key => $valIds) {
3034 if (isset($options[$valIds])) {
3035 $val[$key] = $options[$valIds];
3038 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3039 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3040 $val = implode(', ', $val);
3041 $value = "{$pair[$op]} " . $val;
3043 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3044 isset($field['options']) &&
3045 is_array($field['options']) && !empty($field['options'])
3047 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3048 CRM_Utils_Array
::value($val, $field['options'], $val);
3051 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3055 $statistics['filters'][] = array(
3056 'title' => CRM_Utils_Array
::value('title', $field),
3067 * End post processing.
3069 * @param array|null $rows
3071 public function endPostProcess(&$rows = NULL) {
3072 $this->assign('report_class', get_class($this));
3073 if ($this->_storeResultSet
) {
3074 $this->_resultSet
= $rows;
3077 if ($this->_outputMode
== 'print' ||
3078 $this->_outputMode
== 'pdf' ||
3082 $content = $this->compileContent();
3083 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3087 if ($this->_sendmail
) {
3088 $config = CRM_Core_Config
::singleton();
3089 $attachments = array();
3091 if ($this->_outputMode
== 'csv') {
3093 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3094 ": {$url}</p>" . '<p>' .
3095 ts('The report is attached as a CSV file.') . '</p>' .
3096 $this->_formValues
['report_footer'];
3098 $csvFullFilename = $config->templateCompileDir
.
3099 CRM_Utils_File
::makeFileName('CiviReport.csv');
3100 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3101 file_put_contents($csvFullFilename, $csvContent);
3102 $attachments[] = array(
3103 'fullPath' => $csvFullFilename,
3104 'mime_type' => 'text/csv',
3105 'cleanName' => 'CiviReport.csv',
3108 if ($this->_outputMode
== 'pdf') {
3109 // generate PDF content
3110 $pdfFullFilename = $config->templateCompileDir
.
3111 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3112 file_put_contents($pdfFullFilename,
3113 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3114 TRUE, array('orientation' => 'landscape')
3117 // generate Email Content
3119 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3120 ": {$url}</p>" . '<p>' .
3121 ts('The report is attached as a PDF file.') . '</p>' .
3122 $this->_formValues
['report_footer'];
3124 $attachments[] = array(
3125 'fullPath' => $pdfFullFilename,
3126 'mime_type' => 'application/pdf',
3127 'cleanName' => 'CiviReport.pdf',
3131 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3132 $this->_outputMode
, $attachments
3135 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3138 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3142 elseif ($this->_outputMode
== 'print') {
3146 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3147 $config = CRM_Core_Config
::singleton();
3148 //get chart image name
3149 $chartImg = $this->_chartId
. '.png';
3150 //get image url path
3152 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3154 $uploadUrl .= $chartImg;
3155 //get image doc path to overwrite
3157 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3158 'openFlashChart/' . $chartImg;
3160 $chart = imagecreatefrompng($uploadUrl);
3161 //convert it into formatted png
3162 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3163 //overwrite with same image
3164 imagepng($chart, $uploadImg);
3166 imagedestroy($chart);
3168 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3170 CRM_Utils_System
::civiExit();
3172 elseif ($this->_outputMode
== 'csv') {
3173 CRM_Report_Utils_Report
::export2csv($this, $rows);
3175 elseif ($this->_outputMode
== 'group') {
3176 $group = $this->_params
['groups'];
3177 $this->add2group($group);
3182 * Set store result set indicator to TRUE.
3184 * @todo explain what this does
3186 public function storeResultSet() {
3187 $this->_storeResultSet
= TRUE;
3195 public function getResultSet() {
3196 return $this->_resultSet
;
3200 * Get the sql used to generate the report.
3204 public function getReportSql() {
3205 return $this->sqlArray
;
3209 * Use the form name to create the tpl file name.
3213 public function getTemplateFileName() {
3214 $defaultTpl = parent
::getTemplateFileName();
3215 $template = CRM_Core_Smarty
::singleton();
3216 if (!$template->template_exists($defaultTpl)) {
3217 $defaultTpl = 'CRM/Report/Form.tpl';
3223 * Compile the report content.
3225 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3229 public function compileContent() {
3230 $templateFile = $this->getHookedTemplateFileName();
3231 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3232 CRM_Core_Form
::$_template->fetch($templateFile) .
3233 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3238 * Post process function.
3240 public function postProcess() {
3241 // get ready with post process params
3242 $this->beginPostProcess();
3245 $sql = $this->buildQuery();
3247 // build array of result based on column headers. This method also allows
3248 // modifying column headers before using it to build result set i.e $rows.
3250 $this->buildRows($sql, $rows);
3252 // format result set.
3253 $this->formatDisplay($rows);
3255 // assign variables to templates
3256 $this->doTemplateAssignment($rows);
3258 // do print / pdf / instance stuff if needed
3259 $this->endPostProcess($rows);
3265 * @param int $rowCount
3269 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3270 // lets do the pager if in html mode
3271 $this->_limit
= NULL;
3273 // CRM-14115, over-ride row count if rowCount is specified in URL
3274 if ($this->_dashBoardRowCount
) {
3275 $rowCount = $this->_dashBoardRowCount
;
3277 if ($this->addPaging
) {
3278 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3280 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3282 // @todo all http vars should be extracted in the preProcess
3283 // - not randomly in the class
3284 if (!$pageId && !empty($_POST)) {
3285 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3286 $pageId = max((int) $_POST['crmPID_B'], 1);
3288 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3289 $pageId = max((int) $_POST['crmPID'], 1);
3291 unset($_POST['crmPID_B'], $_POST['crmPID']);
3294 $pageId = $pageId ?
$pageId : 1;
3295 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3296 $offset = ($pageId - 1) * $rowCount;
3298 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3299 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3301 $this->_limit
= " LIMIT $offset, $rowCount";
3302 return array($offset, $rowCount);
3304 if ($this->_limitValue
) {
3305 if ($this->_offsetValue
) {
3306 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3309 $this->_limit
= " LIMIT " . $this->_limitValue
;
3317 * @param int $rowCount
3319 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3320 // CRM-14115, over-ride row count if rowCount is specified in URL
3321 if ($this->_dashBoardRowCount
) {
3322 $rowCount = $this->_dashBoardRowCount
;
3325 if ($this->_limit
&& ($this->_limit
!= '')) {
3326 if (!$this->_rowsFound
) {
3327 $sql = "SELECT FOUND_ROWS();";
3328 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3331 'total' => $this->_rowsFound
,
3332 'rowCount' => $rowCount,
3333 'status' => ts('Records') . ' %%StatusMessage%%',
3334 'buttonBottom' => 'PagerBottomButton',
3335 'buttonTop' => 'PagerTopButton',
3337 if (!empty($this->controller
)) {
3338 // This happens when being called from the api Really we want the api to be able to
3339 // pass paging parameters, but at this stage just preventing test crashes.
3340 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3343 $pager = new CRM_Utils_Pager($params);
3344 $this->assign_by_ref('pager', $pager);
3345 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3350 * Build a group filter with contempt for large data sets.
3352 * This function has been retained as it takes time to migrate the reports over
3353 * to the new method which will not crash on large datasets.
3357 * @param string $field
3358 * @param mixed $value
3363 public function legacySlowGroupFilterClause($field, $value, $op) {
3364 $smartGroupQuery = "";
3366 $group = new CRM_Contact_DAO_Group();
3367 $group->is_active
= 1;
3369 $smartGroups = array();
3370 while ($group->fetch()) {
3371 if (in_array($group->id
, $this->_params
['gid_value']) &&
3372 $group->saved_search_id
3374 $smartGroups[] = $group->id
;
3378 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3380 $smartGroupQuery = '';
3381 if (!empty($smartGroups)) {
3382 $smartGroups = implode(',', $smartGroups);
3383 $smartGroupQuery = " UNION DISTINCT
3384 SELECT DISTINCT smartgroup_contact.contact_id
3385 FROM civicrm_group_contact_cache smartgroup_contact
3386 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3389 $sqlOp = $this->getSQLOperator($op);
3390 if (!is_array($value)) {
3391 $value = array($value);
3393 //include child groups if any
3394 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3396 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3398 $contactAlias = $this->_aliases
['civicrm_contact'];
3399 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3400 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3402 return " {$contactAlias}.id {$sqlOp} (
3403 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3404 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3405 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3406 {$smartGroupQuery} ) ";
3410 * Build where clause for groups.
3412 * @param string $field
3413 * @param mixed $value
3418 public function whereGroupClause($field, $value, $op) {
3419 if ($this->groupFilterNotOptimised
) {
3420 return $this->legacySlowGroupFilterClause($field, $value, $op);
3422 if ($op === 'notin') {
3423 return " group_temp_table.id IS NULL ";
3425 // We will have used an inner join instead.
3431 * Create a table of the contact ids included by the group filter.
3433 * This function is called by both the api (tests) and the UI.
3435 public function buildGroupTempTable() {
3436 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3439 $filteredGroups = (array) $this->_params
['gid_value'];
3441 $groups = civicrm_api3('Group', 'get', array(
3443 'id' => array('IN' => $filteredGroups),
3444 'saved_search_id' => array('>' => 0),
3447 $smartGroups = array_keys($groups['values']);
3450 SELECT DISTINCT group_contact.contact_id as id
3451 FROM civicrm_group_contact group_contact
3452 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3453 AND group_contact.status = 'Added' ";
3455 if (!empty($smartGroups)) {
3456 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3457 $smartGroups = implode(',', $smartGroups);
3460 SELECT smartgroup_contact.contact_id as id
3461 FROM civicrm_group_contact_cache smartgroup_contact
3462 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3465 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3466 $this->executeReportQuery("
3467 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3470 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3474 * Execute query and add it to the developer tab.
3476 * @param string $query
3477 * @param array $params
3479 * @return \CRM_Core_DAO|object
3481 protected function executeReportQuery($query, $params = array()) {
3482 $this->addToDeveloperTab($query);
3483 return CRM_Core_DAO
::executeQuery($query, $params);
3487 * Build where clause for tags.
3489 * @param string $field
3490 * @param mixed $value
3495 public function whereTagClause($field, $value, $op) {
3496 // not using left join in query because if any contact
3497 // belongs to more than one tag, results duplicate
3499 $sqlOp = $this->getSQLOperator($op);
3500 if (!is_array($value)) {
3501 $value = array($value);
3503 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3504 $entity_table = $this->_tagFilterTable
;
3505 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3506 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3507 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3508 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3512 * Generate membership organization clause.
3514 * @param mixed $value
3515 * @param string $op SQL Operator
3519 public function whereMembershipOrgClause($value, $op) {
3520 $sqlOp = $this->getSQLOperator($op);
3521 if (!is_array($value)) {
3522 $value = array($value);
3525 $tmp_membership_org_sql_list = implode(', ', $value);
3526 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3527 SELECT DISTINCT mem.contact_id
3528 FROM civicrm_membership mem
3529 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3530 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3531 WHERE mt.member_of_contact_id IN (" .
3532 $tmp_membership_org_sql_list . ")
3533 AND mt.is_active = '1'
3534 AND mem_status.is_current_member = '1'
3535 AND mem_status.is_active = '1' ) ";
3539 * Generate Membership Type SQL Clause.
3541 * @param mixed $value
3547 public function whereMembershipTypeClause($value, $op) {
3548 $sqlOp = $this->getSQLOperator($op);
3549 if (!is_array($value)) {
3550 $value = array($value);
3553 $tmp_membership_sql_list = implode(', ', $value);
3554 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3555 SELECT DISTINCT mem.contact_id
3556 FROM civicrm_membership mem
3557 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3558 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3559 WHERE mem.membership_type_id IN (" .
3560 $tmp_membership_sql_list . ")
3561 AND mt.is_active = '1'
3562 AND mem_status.is_current_member = '1'
3563 AND mem_status.is_active = '1' ) ";
3567 * Buld contact acl clause
3568 * @deprecated in favor of buildPermissionClause
3570 * @param string $tableAlias
3572 public function buildACLClause($tableAlias = 'contact_a') {
3573 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3577 * Build the permision clause for all entities in this report
3579 public function buildPermissionClause() {
3581 foreach ($this->selectedTables() as $tableName) {
3582 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3583 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3584 $tableAlias = $this->_columns
[$tableName]['alias'];
3585 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3586 foreach ($clauses as $field => $clause) {
3587 // Skip contact_id field if redundant
3588 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3589 $ret["$tableName.$field"] = $clause;
3594 // Override output from buildACLClause
3595 $this->_aclFrom
= NULL;
3596 $this->_aclWhere
= implode(' AND ', $ret);
3600 * Add custom data to the columns.
3602 * @param bool $addFields
3603 * @param array $permCustomGroupIds
3605 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3606 if (empty($this->_customGroupExtends
)) {
3609 if (!is_array($this->_customGroupExtends
)) {
3610 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3612 $customGroupWhere = '';
3613 if (!empty($permCustomGroupIds)) {
3614 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3618 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3619 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3620 FROM civicrm_custom_group cg
3621 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3622 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3624 cg.is_active = 1 AND
3625 cf.is_active = 1 AND
3626 cf.is_searchable = 1
3627 ORDER BY cg.weight, cf.weight";
3628 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3631 while ($customDAO->fetch()) {
3632 if ($customDAO->table_name
!= $curTable) {
3633 $curTable = $customDAO->table_name
;
3634 $curFields = $curFilters = array();
3637 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3638 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3639 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3640 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3642 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3643 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3644 $this->_columns
[$curTable][$colKey] = array();
3648 $fieldName = 'custom_' . $customDAO->cf_id
;
3651 // this makes aliasing work in favor
3652 $curFields[$fieldName] = array(
3653 'name' => $customDAO->column_name
,
3654 'title' => $customDAO->label
,
3655 'dataType' => $customDAO->data_type
,
3656 'htmlType' => $customDAO->html_type
,
3659 if ($this->_customGroupFilters
) {
3660 // this makes aliasing work in favor
3661 $curFilters[$fieldName] = array(
3662 'name' => $customDAO->column_name
,
3663 'title' => $customDAO->label
,
3664 'dataType' => $customDAO->data_type
,
3665 'htmlType' => $customDAO->html_type
,
3669 switch ($customDAO->data_type
) {
3672 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3673 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3674 // CRM-6946, show time part for datetime date fields
3675 if ($customDAO->time_format
) {
3676 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3681 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3682 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3683 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3687 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3688 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3692 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3693 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3694 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3698 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3699 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3703 case 'StateProvince':
3705 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3707 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3708 if ($options !== FALSE) {
3709 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3710 $curFilters[$fieldName]['options'] = $options;
3714 case 'ContactReference':
3715 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3716 $curFilters[$fieldName]['name'] = 'display_name';
3717 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3719 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3720 $curFields[$fieldName]['name'] = 'display_name';
3721 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3725 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3726 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3730 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3731 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3732 if ($options !== FALSE) {
3733 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3734 $curFilters[$fieldName]['options'] = $options;
3738 if (!array_key_exists('type', $curFields[$fieldName])) {
3739 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3743 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3745 if ($this->_customGroupFilters
) {
3746 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3748 if ($this->_customGroupGroupBy
) {
3749 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3755 * Build custom data from clause.
3757 * @param bool $joinsForFiltersOnly
3758 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3760 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3761 if (empty($this->_customGroupExtends
)) {
3764 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3765 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3766 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3767 $customTables = array();
3768 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3769 while ($customTablesDAO->fetch()) {
3770 $customTables[] = $customTablesDAO->table_name
;
3773 foreach ($this->_columns
as $table => $prop) {
3774 if (in_array($table, $customTables)) {
3775 $extendsTable = $mapper[$prop['extends']];
3776 // Check field is required for rendering the report.
3777 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3780 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3782 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3784 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3785 // handle for ContactReference
3786 if (array_key_exists('fields', $prop)) {
3787 foreach ($prop['fields'] as $fieldName => $field) {
3788 if (CRM_Utils_Array
::value('dataType', $field) ==
3791 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3793 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3802 * Check if the field is selected.
3804 * @param string $prop
3808 public function isFieldSelected($prop) {
3813 if (!empty($this->_params
['fields'])) {
3814 foreach (array_keys($prop['fields']) as $fieldAlias) {
3815 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3816 if ($customFieldId) {
3817 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3821 //might be survey response field.
3822 if (!empty($this->_params
['fields']['survey_response']) &&
3823 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3831 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3832 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3833 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3834 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3841 if (!empty($this->_params
['order_bys'])) {
3842 foreach (array_keys($prop['fields']) as $fieldAlias) {
3843 foreach ($this->_params
['order_bys'] as $orderBy) {
3844 if ($fieldAlias == $orderBy['column'] &&
3845 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3852 return $this->isFieldFiltered($prop);
3857 * Check if the field is used as a filter.
3859 * @param string $prop
3863 protected function isFieldFiltered($prop) {
3864 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3865 foreach ($prop['filters'] as $fieldAlias => $val) {
3874 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3875 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3876 ||
($attach != 'relative' &&
3877 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3883 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3884 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3895 * Check for empty order_by configurations and remove them.
3897 * Also set template to hide them.
3899 * @param array $formValues
3901 public function preProcessOrderBy(&$formValues) {
3902 // Object to show/hide form elements
3903 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3905 $_showHide->addShow('optionField_1');
3907 // Cycle through order_by options; skip any empty ones, and hide them as well
3910 if (!empty($formValues['order_bys'])) {
3911 foreach ($formValues['order_bys'] as $order_by) {
3912 if ($order_by['column'] && $order_by['column'] != '-') {
3913 $_showHide->addShow('optionField_' . $n);
3914 $orderBys[$n] = $order_by;
3919 for ($i = $n; $i <= 5; $i++
) {
3921 $_showHide->addHide('optionField_' . $i);
3925 // overwrite order_by options with modified values
3926 if (!empty($orderBys)) {
3927 $formValues['order_bys'] = $orderBys;
3930 $formValues['order_bys'] = array(1 => array('column' => '-'));
3933 // assign show/hide data to template
3934 $_showHide->addToTemplate();
3938 * Check if table name has columns in SELECT clause.
3940 * @param string $tableName
3941 * Name of table (index of $this->_columns array).
3945 public function isTableSelected($tableName) {
3946 return in_array($tableName, $this->selectedTables());
3950 * Check if table name has columns in WHERE or HAVING clause.
3952 * @param string $tableName
3953 * Name of table (index of $this->_columns array).
3957 public function isTableFiltered($tableName) {
3958 // Cause the array to be generated if not previously done.
3959 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3960 $this->selectedTables();
3962 return in_array($tableName, $this->filteredTables
);
3966 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3968 * If the array is unset it will be built.
3973 public function selectedTables() {
3974 if (!$this->_selectedTables
) {
3975 $orderByColumns = array();
3976 if (array_key_exists('order_bys', $this->_params
) &&
3977 is_array($this->_params
['order_bys'])
3979 foreach ($this->_params
['order_bys'] as $orderBy) {
3980 $orderByColumns[] = $orderBy['column'];
3984 foreach ($this->_columns
as $tableName => $table) {
3985 if (array_key_exists('fields', $table)) {
3986 foreach ($table['fields'] as $fieldName => $field) {
3987 if (!empty($field['required']) ||
3988 !empty($this->_params
['fields'][$fieldName])
3990 $this->_selectedTables
[] = $tableName;
3995 if (array_key_exists('order_bys', $table)) {
3996 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3997 if (in_array($orderByName, $orderByColumns)) {
3998 $this->_selectedTables
[] = $tableName;
4003 if (array_key_exists('filters', $table)) {
4004 foreach ($table['filters'] as $filterName => $filter) {
4005 if (!empty($this->_params
["{$filterName}_value"]) ||
4006 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4008 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4011 $this->_selectedTables
[] = $tableName;
4012 $this->filteredTables
[] = $tableName;
4019 return $this->_selectedTables
;
4023 * Add address fields.
4025 * @deprecated - use getAddressColumns which is a more accurate description
4026 * and also accepts an array of options rather than a long list
4028 * adding address fields to construct function in reports
4030 * @param bool $groupBy
4031 * Add GroupBy? Not appropriate for detail report.
4032 * @param bool $orderBy
4033 * Add GroupBy? Not appropriate for detail report.
4034 * @param bool $filters
4035 * @param array $defaults
4038 * address fields for construct clause
4040 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4041 $defaultAddressFields = array(
4042 'street_address' => ts('Street Address'),
4043 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4044 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4045 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4046 'street_number' => ts('Street Number'),
4047 'street_name' => ts('Street Name'),
4048 'street_unit' => ts('Street Unit'),
4049 'city' => ts('City'),
4050 'postal_code' => ts('Postal Code'),
4051 'postal_code_suffix' => ts('Postal Code Suffix'),
4052 'country_id' => ts('Country'),
4053 'state_province_id' => ts('State/Province'),
4054 'county_id' => ts('County'),
4056 $addressFields = array(
4057 'civicrm_address' => array(
4058 'dao' => 'CRM_Core_DAO_Address',
4060 'address_name' => array(
4061 'title' => ts('Address Name'),
4062 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4066 'grouping' => 'location-fields',
4069 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4070 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4071 'title' => $fieldLabel,
4072 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4076 $street_address_filters = $general_address_filters = array();
4078 // Address filter depends on whether street address parsing is enabled.
4080 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4083 if ($addressOptions['street_address_parsing']) {
4084 $street_address_filters = array(
4085 'street_number' => array(
4086 'title' => ts('Street Number'),
4087 'type' => CRM_Utils_Type
::T_INT
,
4088 'name' => 'street_number',
4090 'street_name' => array(
4091 'title' => ts('Street Name'),
4092 'name' => 'street_name',
4093 'type' => CRM_Utils_Type
::T_STRING
,
4098 $street_address_filters = array(
4099 'street_address' => array(
4100 'title' => ts('Street Address'),
4101 'type' => CRM_Utils_Type
::T_STRING
,
4102 'name' => 'street_address',
4106 $general_address_filters = array(
4107 'postal_code' => array(
4108 'title' => ts('Postal Code'),
4109 'type' => CRM_Utils_Type
::T_STRING
,
4110 'name' => 'postal_code',
4113 'title' => ts('City'),
4114 'type' => CRM_Utils_Type
::T_STRING
,
4117 'country_id' => array(
4118 'name' => 'country_id',
4119 'title' => ts('Country'),
4120 'type' => CRM_Utils_Type
::T_INT
,
4121 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4122 'options' => CRM_Core_PseudoConstant
::country(),
4124 'state_province_id' => array(
4125 'name' => 'state_province_id',
4126 'title' => ts('State/Province'),
4127 'type' => CRM_Utils_Type
::T_INT
,
4128 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4129 'options' => array(),
4131 'county_id' => array(
4132 'name' => 'county_id',
4133 'title' => ts('County'),
4134 'type' => CRM_Utils_Type
::T_INT
,
4135 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4136 'options' => array(),
4140 $addressFields['civicrm_address']['filters'] = array_merge(
4141 $street_address_filters,
4142 $general_address_filters);
4145 $addressFields['civicrm_address']['order_bys'] = array(
4146 'street_name' => array('title' => ts('Street Name')),
4147 'street_number' => array('title' => ts('Odd / Even Street Number')),
4148 'street_address' => NULL,
4150 'postal_code' => NULL,
4155 $addressFields['civicrm_address']['group_bys'] = array(
4156 'street_address' => NULL,
4158 'postal_code' => NULL,
4159 'state_province_id' => array(
4160 'title' => ts('State/Province'),
4162 'country_id' => array(
4163 'title' => ts('Country'),
4165 'county_id' => array(
4166 'title' => ts('County'),
4170 return $addressFields;
4174 * Do AlterDisplay processing on Address Fields.
4177 * @param array $rows
4178 * @param int $rowNum
4179 * @param string $baseUrl
4180 * @param string $linkText
4184 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4185 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4186 $entryFound = FALSE;
4188 if (array_key_exists('civicrm_address_country_id', $row)) {
4189 if ($value = $row['civicrm_address_country_id']) {
4190 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4192 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4193 "reset=1&force=1&{$criteriaQueryParams}&" .
4194 "country_id_op=in&country_id_value={$value}",
4195 $this->_absoluteUrl
, $this->_id
4197 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4198 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4199 array(1 => $linkText)
4206 if (array_key_exists('civicrm_address_county_id', $row)) {
4207 if ($value = $row['civicrm_address_county_id']) {
4208 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4210 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4211 "reset=1&force=1&{$criteriaQueryParams}&" .
4212 "county_id_op=in&county_id_value={$value}",
4213 $this->_absoluteUrl
, $this->_id
4215 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4216 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4217 array(1 => $linkText)
4223 // handle state province
4224 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4225 if ($value = $row['civicrm_address_state_province_id']) {
4226 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4228 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4229 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4230 $this->_absoluteUrl
, $this->_id
4232 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4233 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4234 array(1 => $linkText)
4245 * Do AlterDisplay processing on Address Fields.
4248 * @param array $rows
4249 * @param int $rowNum
4250 * @param string $baseUrl
4251 * @param string $linkText
4255 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4256 $entryFound = FALSE;
4257 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4258 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4259 $addLinks = array('gender_id' => 'Gender');
4260 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4261 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4262 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4263 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4264 $rowLabels = array();
4265 foreach ($rowValues as $rowValue) {
4267 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4270 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4271 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4272 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4278 $yesNoFields = array(
4279 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4281 foreach ($yesNoFields as $fieldName) {
4282 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4283 // Since these are essentially 'negative fields' it feels like it
4284 // makes sense to only highlight the exceptions hence no 'No'.
4285 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4293 * Adjusts dates passed in to YEAR() for fiscal year.
4295 * @param string $fieldName
4299 public function fiscalYearOffset($fieldName) {
4300 $config = CRM_Core_Config
::singleton();
4301 $fy = $config->fiscalYearStart
;
4302 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4303 ($fy['d'] == 1 && $fy['M'] == 1)
4305 return "YEAR( $fieldName )";
4307 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4308 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4312 * Add Address into From Table if required.
4314 public function addAddressFromClause() {
4315 // include address field if address column is to be included
4316 if ((isset($this->_addressField
) &&
4317 $this->_addressField
4319 $this->isTableSelected('civicrm_address')
4322 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4323 ON ({$this->_aliases['civicrm_contact']}.id =
4324 {$this->_aliases['civicrm_address']}.contact_id) AND
4325 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4330 * Add Phone into From Table if required.
4332 public function addPhoneFromClause() {
4333 // include address field if address column is to be included
4334 if ($this->isTableSelected('civicrm_phone')) {
4336 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4337 ON ({$this->_aliases['civicrm_contact']}.id =
4338 {$this->_aliases['civicrm_phone']}.contact_id) AND
4339 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4344 * Add Financial Transaction into From Table if required.
4346 public function addFinancialTrxnFromClause() {
4347 if ($this->isTableSelected('civicrm_financial_trxn')) {
4349 LEFT JOIN civicrm_entity_financial_trxn eftcc
4350 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4351 eftcc.entity_table = 'civicrm_contribution')
4352 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4353 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4358 * Get phone columns to add to array.
4360 * @param array $options
4361 * - prefix Prefix to add to table (in case of more than one instance of the table)
4362 * - prefix_label Label to give columns from this phone table instance
4365 * phone columns definition
4367 public function getPhoneColumns($options = array()) {
4368 $defaultOptions = array(
4370 'prefix_label' => '',
4373 $options = array_merge($defaultOptions, $options);
4376 $options['prefix'] . 'civicrm_phone' => array(
4377 'dao' => 'CRM_Core_DAO_Phone',
4379 $options['prefix'] . 'phone' => array(
4380 'title' => ts($options['prefix_label'] . 'Phone'),
4390 * Get address columns to add to array.
4392 * @param array $options
4393 * - prefix Prefix to add to table (in case of more than one instance of the table)
4394 * - prefix_label Label to give columns from this address table instance
4397 * address columns definition
4399 public function getAddressColumns($options = array()) {
4402 'prefix_label' => '',
4406 'defaults' => array(),
4408 return $this->addAddressFields(
4409 $options['group_by'],
4410 $options['order_by'],
4411 $options['filters'],
4412 $options['defaults']
4417 * Get a standard set of contact fields.
4421 public function getBasicContactFields() {
4423 'sort_name' => array(
4424 'title' => ts('Contact Name'),
4429 'no_display' => TRUE,
4432 'prefix_id' => array(
4433 'title' => ts('Contact Prefix'),
4435 'first_name' => array(
4436 'title' => ts('First Name'),
4438 'nick_name' => array(
4439 'title' => ts('Nick Name'),
4441 'middle_name' => array(
4442 'title' => ts('Middle Name'),
4444 'last_name' => array(
4445 'title' => ts('Last Name'),
4447 'suffix_id' => array(
4448 'title' => ts('Contact Suffix'),
4450 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4451 'email_greeting_display' => array('title' => ts('Email Greeting')),
4452 'addressee_display' => array('title' => ts('Addressee')),
4453 'contact_type' => array(
4454 'title' => ts('Contact Type'),
4456 'contact_sub_type' => array(
4457 'title' => ts('Contact Subtype'),
4459 'gender_id' => array(
4460 'title' => ts('Gender'),
4462 'birth_date' => array(
4463 'title' => ts('Birth Date'),
4466 'title' => ts('Age'),
4467 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4469 'job_title' => array(
4470 'title' => ts('Contact Job title'),
4472 'organization_name' => array(
4473 'title' => ts('Organization Name'),
4475 'external_identifier' => array(
4476 'title' => ts('Contact identifier from external system'),
4478 'do_not_email' => array(),
4479 'do_not_phone' => array(),
4480 'do_not_mail' => array(),
4481 'do_not_sms' => array(),
4482 'is_opt_out' => array(),
4483 'is_deceased' => array(),
4484 'preferred_language' => array(),
4489 * Get a standard set of contact filters.
4493 public function getBasicContactFilters() {
4495 'sort_name' => array(
4496 'title' => ts('Contact Name'),
4499 'title' => ts('Contact Source'),
4500 'type' => CRM_Utils_Type
::T_STRING
,
4503 'title' => ts('Contact ID'),
4504 'no_display' => TRUE,
4506 'gender_id' => array(
4507 'title' => ts('Gender'),
4508 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4509 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4511 'birth_date' => array(
4512 'title' => ts('Birth Date'),
4513 'operatorType' => CRM_Report_Form
::OP_DATE
,
4515 'contact_type' => array(
4516 'title' => ts('Contact Type'),
4518 'contact_sub_type' => array(
4519 'title' => ts('Contact Subtype'),
4521 'modified_date' => array(
4522 'title' => ts('Contact Modified'),
4523 'operatorType' => CRM_Report_Form
::OP_DATE
,
4524 'type' => CRM_Utils_Type
::T_DATE
,
4526 'is_deceased' => array(
4527 'title' => ts('Deceased'),
4528 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4531 'do_not_email' => array(
4532 'title' => ts('Do not email'),
4533 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4535 'do_not_phone' => array(
4536 'title' => ts('Do not phone'),
4537 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4539 'do_not_mail' => array(
4540 'title' => ts('Do not mail'),
4541 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4543 'do_not_sms' => array(
4544 'title' => ts('Do not SMS'),
4545 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4547 'is_opt_out' => array(
4548 'title' => ts('Do not bulk email'),
4549 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4551 'preferred_language' => array(
4552 'title' => ts('Preferred Language'),
4558 * Add contact to group.
4560 * @param int $groupID
4562 public function add2group($groupID) {
4563 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4564 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4565 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4566 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4567 $sql = str_replace('WITH ROLLUP', '', $sql);
4568 $dao = CRM_Core_DAO
::executeQuery($sql);
4570 $contact_ids = array();
4571 // Add resulting contacts to group
4572 while ($dao->fetch()) {
4573 if ($dao->addtogroup_contact_id
) {
4574 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4578 if (!empty($contact_ids)) {
4579 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4580 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4583 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4589 * Show charts on print screen.
4591 public static function uploadChartImage() {
4592 // upload strictly for '.png' images
4593 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4594 if (preg_match('/\.png$/', $name)) {
4596 // Get the RAW .png from the input.
4597 $httpRawPostData = file_get_contents("php://input");
4599 // prepare the directory
4600 $config = CRM_Core_Config
::singleton();
4602 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4604 if (!file_exists($defaultPath)) {
4605 mkdir($defaultPath, 0777, TRUE);
4608 // full path to the saved image including filename
4609 $destination = $defaultPath . $name;
4612 $jfh = fopen($destination, 'w') or die("can't open file");
4613 fwrite($jfh, $httpRawPostData);
4615 CRM_Utils_System
::civiExit();
4620 * Apply common settings to entityRef fields.
4622 * @param array $field
4623 * @param string $table
4625 private function setEntityRefDefaults(&$field, $table) {
4626 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4627 $field['attributes'] +
= array(
4628 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4630 'placeholder' => ts('- select -'),
4635 * Add link fields to the row.
4637 * Function adds the _link & _hover fields to the row.
4640 * @param string $baseUrl
4641 * @param string $linkText
4642 * @param string $value
4643 * @param string $fieldName
4644 * @param string $tablePrefix
4645 * @param string $fieldLabel
4649 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4650 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4651 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4652 "reset=1&force=1&{$criteriaQueryParams}&" .
4653 $fieldName . "_op=in&{$fieldName}_value={$value}",
4654 $this->_absoluteUrl
, $this->_id
4656 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4657 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4658 array(1 => $linkText, 2 => $fieldLabel)
4663 * Generate temporary table to hold all contributions with permissioned FTs.
4665 * @param object $query
4666 * @param string $alias
4667 * @param bool $return
4671 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4672 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4675 $financialTypes = NULL;
4676 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4677 if (empty($financialTypes)) {
4679 $liFTs = implode(',', array_keys(CRM_Contribute_PseudoConstant
::financialType()));
4682 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4684 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4686 $query->_aliases
['civicrm_line_item'] = $alias;
4689 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4691 if (empty($query->_where
)) {
4692 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4694 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4695 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp {$this->_databaseAttributes} AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4696 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4697 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4698 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4699 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4701 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4702 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4703 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4704 CRM_Core_DAO
::executeQuery($sql);
4706 $query->_aliases
['civicrm_line_item'] = $temp;
4708 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4712 $query->_from
.= $from;
4716 * Get label for show results buttons.
4720 public function getResultsLabel() {
4721 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4722 return $showResultsLabel;
4726 * Determine the output mode from the url or input.
4729 * - pdf : Render as pdf
4730 * - csv : Render as csv
4731 * - print : Render in print format
4732 * - save : save the report and display the new report
4733 * - copy : save the report as a new instance and display that.
4734 * - group : go to the add to group screen.
4736 * Potentially chart variations could also be included but the complexity
4737 * is that we might print a bar chart as a pdf.
4739 protected function setOutputMode() {
4740 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4743 CRM_Core_DAO
::$_nullObject,
4745 CRM_Utils_Array
::value('task', $this->_params
)
4747 // if contacts are added to group
4748 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4749 $this->_outputMode
= 'group';
4751 if (isset($this->_params
['task'])) {
4752 unset($this->_params
['task']);
4757 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4760 * @param $columnName
4762 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4763 // add new column with date value for the datetime field
4764 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4765 CRM_Core_DAO
::executeQuery($tempQuery);
4766 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4767 CRM_Core_DAO
::executeQuery($updateQuery);
4768 $this->_selectClauses
[] = "{$columnName}_date";
4769 $this->_select
.= ", {$columnName}_date";
4770 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4771 unset($this->_sections
["{$columnName}"]);
4772 $this->assign('sections', $this->_sections
);
4776 * Get an array of the columns that have been selected for display.
4780 public function getSelectColumns() {
4781 $selectColumns = array();
4782 foreach ($this->_columns
as $tableName => $table) {
4783 if (array_key_exists('fields', $table)) {
4784 foreach ($table['fields'] as $fieldName => $field) {
4785 if (!empty($field['required']) ||
4786 !empty($this->_params
['fields'][$fieldName])
4789 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4794 return $selectColumns;
4798 * Add location tables to the query if they are used for filtering.
4800 * This is for when we are running the query separately for filtering and retrieving display fields.
4802 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4803 if ($this->isTableFiltered('civicrm_email')) {
4805 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4806 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4807 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4809 if ($this->isTableFiltered('civicrm_phone')) {
4811 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4812 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4813 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4815 if ($this->isTableFiltered('civicrm_address')) {
4817 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4818 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4819 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4824 * Set the base table for the FROM clause.
4826 * Sets up the from clause, allowing for the possibility it might be a
4827 * temp table pre-filtered by groups if a group filter is in use.
4829 * @param string $baseTable
4830 * @param string $field
4831 * @param null $tableAlias
4833 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4835 $tableAlias = $this->_aliases
[$baseTable];
4837 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4838 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4839 $this->_from
.= " {$this->_aclFrom} ";
4843 * Join the temp table contacting contacts who are members of the filtered groups.
4845 * If we are using an IN filter we use an inner join, otherwise a left join.
4847 * @param string $baseTable
4848 * @param string $field
4849 * @param string $tableAlias
4851 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4852 if ($this->groupTempTable
) {
4853 if ($this->_params
['gid_op'] == 'in') {
4854 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4855 ON group_temp_table.id = $tableAlias.{$field} ";
4859 LEFT JOIN $this->groupTempTable group_temp_table
4860 ON $tableAlias.{$field} = group_temp_table.id ";
4866 * Get all labels for fields that are used in a group concat.
4868 * @param string $options
4869 * comma separated option values.
4870 * @param string $baoName
4871 * The BAO name for the field.
4872 * @param string $fieldName
4873 * The name of the field for which labels should be retrieved.
4877 public function getLabels($options, $baoName, $fieldName) {
4878 $types = explode(',', $options);
4880 foreach ($types as $value) {
4881 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
4883 return implode(', ', array_filter($labels));
4887 * Add statistics columns.
4889 * If a group by is in play then add columns for the statistics fields.
4891 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
4892 * column header field.
4894 * @param array $field
4895 * @param string $tableName
4896 * @param string $fieldName
4897 * @param array $select
4901 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
4902 foreach ($field['statistics'] as $stat => $label) {
4903 $alias = "{$tableName}_{$fieldName}_{$stat}";
4904 switch (strtolower($stat)) {
4907 $select[] = "$stat({$field['dbAlias']}) as $alias";
4908 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4909 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4910 $this->_statFields
[$label] = $alias;
4911 $this->_selectAliases
[] = $alias;
4915 $select[] = "COUNT({$field['dbAlias']}) as $alias";
4916 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4917 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4918 $this->_statFields
[$label] = $alias;
4919 $this->_selectAliases
[] = $alias;
4922 case 'count_distinct':
4923 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
4924 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4925 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4926 $this->_statFields
[$label] = $alias;
4927 $this->_selectAliases
[] = $alias;
4931 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
4932 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4933 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4934 $this->_statFields
[$label] = $alias;
4935 $this->_selectAliases
[] = $alias;
4943 * Add a basic field to the select clause.
4945 * @param string $tableName
4946 * @param string $fieldName
4947 * @param array $field
4948 * @param string $select
4951 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
4952 $alias = "{$tableName}_{$fieldName}";
4953 $select[] = "{$field['dbAlias']} as $alias";
4954 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
4955 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
4956 $this->_selectAliases
[] = $alias;
4963 * @param array $table
4964 * @param string $tableName
4969 protected function setTableAlias($table, $tableName) {
4970 if (!isset($table['alias'])) {
4971 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
4975 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
4978 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
4979 return $this->_aliases
[$tableName];