3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 public $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
156 * Has the report been optimised for group filtering.
158 * The functionality for group filtering has been improved but not
159 * all reports have been adjusted to take care of it.
161 * This property exists to highlight the reports which are still using the
162 * slow method & allow group filtering to still work for them until they
165 * In order to protect extensions we have to default to TRUE - but I have
166 * separately marked every class with a groupFilter in the hope that will trigger
167 * people to fix them as they touch them.
173 protected $groupFilterNotOptimised = TRUE;
180 public $_navigation = array();
182 public $_drilldownReport = array();
185 * Array of tabs to display on report.
187 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
189 * $this->tabs['OrderBy'] = array(
190 * 'title' => ts('Sorting'),
191 * 'tpl' => 'OrderBy',
192 * 'div_label' => 'order-by',
197 protected $tabs = array();
200 * Should we add paging.
204 protected $addPaging = TRUE;
207 * An attribute for checkbox/radio form field layout
211 protected $_fourColumnAttribute = array(
212 '</td><td width="25%">',
213 '</td><td width="25%">',
214 '</td><td width="25%">',
218 protected $_force = 1;
220 protected $_params = NULL;
221 protected $_formValues = NULL;
222 protected $_instanceValues = NULL;
224 protected $_instanceForm = FALSE;
225 protected $_criteriaForm = FALSE;
227 protected $_instanceButtonName = NULL;
228 protected $_createNewButtonName = NULL;
229 protected $_printButtonName = NULL;
230 protected $_pdfButtonName = NULL;
231 protected $_csvButtonName = NULL;
232 protected $_groupButtonName = NULL;
233 protected $_chartButtonName = NULL;
234 protected $_csvSupported = TRUE;
235 protected $_add2groupSupported = TRUE;
236 protected $_groups = NULL;
237 protected $_grandFlag = FALSE;
238 protected $_rowsFound = NULL;
239 protected $_selectAliases = array();
240 protected $_rollup = NULL;
243 * Table containing list of contact IDs within the group filter.
247 protected $groupTempTable = '';
252 protected $_aliases = array();
268 protected $_limit = NULL;
271 * This can be set to specify a limit to the number of rows
272 * Since it is currently envisaged as part of the api usage it is only being applied
273 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
274 * of the code (see limit() fn.
278 protected $_limitValue = NULL;
281 * This can be set to specify row offset
282 * See notes on _limitValue
285 protected $_offsetValue = NULL;
289 protected $_sections = NULL;
290 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
291 protected $_absoluteUrl = FALSE;
294 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
298 protected $_storeResultSet = FALSE;
301 * When _storeResultSet Flag is set use this var to store result set in form of array
305 protected $_resultSet = array();
308 * To what frequency group-by a date column
312 protected $_groupByDateFreq = array(
314 'YEARWEEK' => 'Week',
315 'QUARTER' => 'Quarter',
320 * Variables to hold the acl inner join and where clause
322 protected $_aclFrom = NULL;
323 protected $_aclWhere = NULL;
326 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
328 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
332 protected $_selectedTables = array();
335 * Array of DAO tables having columns included in WHERE or HAVING clause
339 protected $filteredTables;
342 * Output mode e.g 'print', 'csv', 'pdf'.
346 protected $_outputMode;
349 * Format of any chart in use.
351 * (it's unclear if this could be merged with outputMode at this stage)
357 public $_having = NULL;
358 public $_select = NULL;
359 public $_selectClauses = array();
360 public $_columnHeaders = array();
361 public $_orderBy = NULL;
362 public $_orderByFields = array();
363 public $_orderByArray = array();
364 public $_groupBy = NULL;
365 public $_whereClauses = array();
366 public $_havingClauses = array();
369 * DashBoardRowCount Dashboard row count
372 public $_dashBoardRowCount;
375 * Is this being called without a form controller (ie. the report is being render outside the normal form
376 * - e.g the api is retrieving the rows
379 public $noController = FALSE;
382 * Variable to hold the currency alias
384 protected $_currencyColumn = NULL;
389 protected $_interval;
394 protected $_sendmail;
407 * @var string Report description.
409 public $_description;
412 * @var bool Is an address field selected.
413 * This was intended to determine if the address table should be joined in
414 * The isTableSelected function is now preferred for this purpose
416 protected $_addressField;
419 * @var bool Is an email field selected.
420 * This was intended to determine if the email table should be joined in
421 * The isTableSelected function is now preferred for this purpose
423 protected $_emailField;
426 * @var bool Is a phone field selected.
427 * This was intended to determine if the phone table should be joined in
428 * The isTableSelected function is now preferred for this purpose
430 protected $_phoneField;
433 * @var bool Create new report instance? (or update existing) on save.
435 protected $_createNew;
438 * When a grand total row has calculated the status we pop it off to here.
440 * This allows us to access it from the stats function and avoid recalculating.
442 protected $rollupRow = array();
445 * @var string Database attributes - character set and collation
447 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
450 * SQL being run in this report.
452 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
460 * SQL being run in this report as an array.
462 * The sql in the report is stored in this variable in order to be returned to api & test calls.
471 public function __construct() {
472 parent
::__construct();
474 $this->addClass('crm-report-form');
476 if ($this->_tagFilter
) {
477 $this->buildTagFilter();
479 if ($this->_exposeContactID
) {
480 if (array_key_exists('civicrm_contact', $this->_columns
)) {
481 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
483 'title' => ts('Contact ID'),
489 if ($this->_groupFilter
) {
490 $this->buildGroupFilter();
493 // Get all custom groups
494 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
496 // Get the custom groupIds for which the user has VIEW permission
497 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
498 // and addCustomDataToColumns() will allow access to all custom groups.
499 $permCustomGroupIds = array();
500 if (!CRM_Core_Permission
::check('access all custom data')) {
501 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
502 // do not allow custom data for reports if user doesn't have
503 // permission to access custom data.
504 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
505 $this->_customGroupExtends
= array();
509 // merge custom data columns to _columns list, if any
510 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
512 // add / modify display columns, filters ..etc
513 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
515 //assign currencyColumn variable to tpl
516 $this->assign('currencyColumn', $this->_currencyColumn
);
520 * Shared pre-process function.
522 * If overriding preProcess function this should still be called.
526 public function preProcessCommon() {
527 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
529 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
531 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
533 $this->assign('section', $this->_section
);
534 CRM_Core_Region
::instance('page-header')->add(array(
535 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
537 if (!$this->noController
) {
538 $this->setID($this->get('instanceId'));
541 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
543 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
547 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
548 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
549 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
553 $this->assign('instanceId', $this->_id
);
554 $params = array('id' => $this->_id
);
555 $this->_instanceValues
= array();
556 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
558 $this->_instanceValues
560 if (empty($this->_instanceValues
)) {
561 CRM_Core_Error
::fatal("Report could not be loaded.");
563 $this->_title
= $this->_instanceValues
['title'];
564 if (!empty($this->_instanceValues
['permission']) &&
565 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
566 CRM_Core_Permission
::check('administer Reports')
569 CRM_Utils_System
::permissionDenied();
570 CRM_Utils_System
::civiExit();
573 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
575 $this->_formValues
= unserialize($formValues);
578 $this->_formValues
= NULL;
581 $this->setOutputMode();
583 if ($this->_outputMode
== 'copy') {
584 $this->_createNew
= TRUE;
585 $this->_params
= $this->_formValues
;
586 $this->_params
['view_mode'] = 'criteria';
587 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
588 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
589 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
591 // Do not pass go. Do not collect another chance to re-run the same query.
592 CRM_Report_Form_Instance
::postProcess($this);
595 // lets always do a force if reset is found in the url.
596 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
597 // in the comment line above these 2.
598 if (!empty($_REQUEST['reset'])
599 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
604 $this->assign('mode', 'instance');
606 elseif (!$this->noController
) {
607 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
608 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
609 if (($instanceCount > 0) && $optionValueID) {
610 $this->assign('instanceUrl',
611 CRM_Utils_System
::url('civicrm/report/list',
612 "reset=1&ovid=$optionValueID"
616 if ($optionValueID) {
617 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
621 $this->assign('mode', 'template');
624 // lets display the Report Settings section
625 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
627 // Do not display Report Settings section if administer Reports permission is absent OR
628 // if report instance is reserved and administer reserved reports absent
629 if (!CRM_Core_Permission
::check('administer Reports') ||
630 ($this->_instanceValues
['is_reserved'] &&
631 !CRM_Core_Permission
::check('administer reserved reports'))
633 $this->_instanceForm
= FALSE;
636 $this->assign('criteriaForm', FALSE);
637 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
638 if (CRM_Core_Permission
::check('administer Reports') ||
639 CRM_Core_Permission
::check('access Report Criteria')
641 if (!$this->_instanceValues
['is_reserved'] ||
642 CRM_Core_Permission
::check('administer reserved reports')
644 $this->assign('criteriaForm', TRUE);
645 $this->_criteriaForm
= TRUE;
649 // Special permissions check for private instance if it's not the current contact instance
651 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
652 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
653 if (!CRM_Core_Permission
::check('access all private reports')) {
654 $this->_instanceForm
= FALSE;
655 $this->assign('criteriaForm', FALSE);
659 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
660 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
661 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
662 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
668 public function addBreadCrumb() {
672 'title' => ts('Report Templates'),
673 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
677 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
681 * Pre process function.
683 * Called prior to build form.
685 public function preProcess() {
686 $this->preProcessCommon();
689 $this->addBreadCrumb();
692 foreach ($this->_columns
as $tableName => $table) {
694 if (!isset($table['alias'])) {
695 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
699 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
702 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
704 $daoOrBaoName = NULL;
705 // higher preference to bao object
706 if (array_key_exists('bao', $table)) {
707 $daoOrBaoName = $table['bao'];
708 $expFields = $daoOrBaoName::exportableFields();
710 elseif (array_key_exists('dao', $table)) {
711 $daoOrBaoName = $table['dao'];
712 $expFields = $daoOrBaoName::export();
715 $expFields = array();
718 $doNotCopy = array('required');
720 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
721 foreach ($fieldGroups as $fieldGrp) {
722 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
723 foreach ($table[$fieldGrp] as $fieldName => $field) {
724 // $name is the field name used to reference the BAO/DAO export fields array
725 $name = isset($field['name']) ?
$field['name'] : $fieldName;
727 // Sometimes the field name key in the BAO/DAO export fields array is
728 // different from the actual database field name.
729 // Unset $field['name'] so that actual database field name can be obtained
730 // from the BAO/DAO export fields array.
731 unset($field['name']);
733 if (array_key_exists($name, $expFields)) {
734 foreach ($doNotCopy as $dnc) {
735 // unset the values we don't want to be copied.
736 unset($expFields[$name][$dnc]);
739 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
742 foreach ($expFields[$name] as $property => $val) {
743 if (!array_key_exists($property, $field)) {
744 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
751 if (!empty($field['no_repeat'])) {
752 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
754 if (!empty($field['no_display'])) {
755 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
758 // set alias = table-name, unless already set
759 $alias = isset($field['alias']) ?
$field['alias'] : (
760 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
762 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
764 // set name = fieldName, unless already set
765 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
766 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
769 // set dbAlias = alias.name, unless already set
770 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
771 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
773 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
776 // a few auto fills for filters
777 if ($fieldGrp == 'filters') {
778 // fill operator types
779 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
780 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
781 case CRM_Utils_Type
::T_MONEY
:
782 case CRM_Utils_Type
::T_FLOAT
:
783 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
786 case CRM_Utils_Type
::T_INT
:
787 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
790 case CRM_Utils_Type
::T_DATE
:
791 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
794 case CRM_Utils_Type
::T_BOOLEAN
:
795 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
796 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
797 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
808 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
810 // with multiple options operator-type is generally multi-select
811 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
812 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
814 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
825 // copy filters to a separate handy variable
826 if (array_key_exists('filters', $table)) {
827 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
830 if (array_key_exists('group_bys', $table)) {
831 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
834 if (array_key_exists('fields', $table)) {
835 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
840 $this->setDefaultValues(FALSE);
843 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
844 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
845 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
846 CRM_Report_Utils_Get
::processChart($this->_defaults
);
849 $this->_formValues
= $this->_defaults
;
850 $this->postProcess();
855 * Set default values.
857 * @param bool $freeze
861 public function setDefaultValues($freeze = TRUE) {
862 $freezeGroup = array();
864 // FIXME: generalizing form field naming conventions would reduce
865 // Lots of lines below.
866 foreach ($this->_columns
as $tableName => $table) {
867 if (array_key_exists('fields', $table)) {
868 foreach ($table['fields'] as $fieldName => $field) {
869 if (empty($field['no_display'])) {
870 if (isset($field['required'])) {
872 $this->_defaults
['fields'][$fieldName] = 1;
875 // find element object, so that we could use quickform's freeze method
876 // for required elements
877 $obj = $this->getElementFromGroup("fields", $fieldName);
879 $freezeGroup[] = $obj;
883 elseif (isset($field['default'])) {
884 $this->_defaults
['fields'][$fieldName] = $field['default'];
890 if (array_key_exists('group_bys', $table)) {
891 foreach ($table['group_bys'] as $fieldName => $field) {
892 if (isset($field['default'])) {
893 if (!empty($field['frequency'])) {
894 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
896 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
900 if (array_key_exists('filters', $table)) {
901 foreach ($table['filters'] as $fieldName => $field) {
902 if (isset($field['default'])) {
903 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
905 if (is_array($field['default'])) {
906 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
907 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
908 $this->_defaults
["{$fieldName}_relative"] = 0;
911 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
915 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
916 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
917 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
919 $this->_defaults
["{$fieldName}_value"] = $field['default'];
922 //assign default value as "in" for multiselect
923 //operator, To freeze the select element
924 if (CRM_Utils_Array
::value('operatorType', $field) ==
925 CRM_Report_Form
::OP_MULTISELECT
927 $this->_defaults
["{$fieldName}_op"] = 'in';
929 if (CRM_Utils_Array
::value('operatorType', $field) ==
930 CRM_Report_Form
::OP_ENTITYREF
932 $this->_defaults
["{$fieldName}_op"] = 'in';
934 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
935 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
937 $this->_defaults
["{$fieldName}_op"] = 'mhas';
939 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
940 $this->_defaults
["{$fieldName}_op"] = $op;
946 empty($this->_formValues
['order_bys']) &&
947 (array_key_exists('order_bys', $table) &&
948 is_array($table['order_bys']))
950 if (!array_key_exists('order_bys', $this->_defaults
)) {
951 $this->_defaults
['order_bys'] = array();
953 foreach ($table['order_bys'] as $fieldName => $field) {
954 if (!empty($field['default']) ||
!empty($field['default_order']) ||
955 CRM_Utils_Array
::value('default_is_section', $field) ||
956 !empty($field['default_weight'])
959 'column' => $fieldName,
960 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
961 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
964 if (!empty($field['default_weight'])) {
965 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
968 array_unshift($this->_defaults
['order_bys'], $order_by);
974 foreach ($this->_options
as $fieldName => $field) {
975 if (isset($field['default'])) {
976 $this->_defaults
['options'][$fieldName] = $field['default'];
981 if (!empty($this->_submitValues
)) {
982 $this->preProcessOrderBy($this->_submitValues
);
985 $this->preProcessOrderBy($this->_defaults
);
988 // lets finish freezing task here itself
989 if (!empty($freezeGroup)) {
990 foreach ($freezeGroup as $elem) {
995 if ($this->_formValues
) {
996 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
999 if ($this->_instanceValues
) {
1000 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1003 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1005 return $this->_defaults
;
1009 * Get element from group.
1011 * @param string $group
1012 * @param string $grpFieldName
1016 public function getElementFromGroup($group, $grpFieldName) {
1017 $eleObj = $this->getElement($group);
1018 foreach ($eleObj->_elements
as $index => $obj) {
1019 if ($grpFieldName == $obj->_attributes
['name']) {
1027 * Setter for $_params.
1029 * @param array $params
1031 public function setParams($params) {
1032 $this->_params
= $params;
1038 * @param int $instanceID
1040 public function setID($instanceID) {
1041 $this->_id
= $instanceID;
1045 * Setter for $_force.
1047 * @param bool $isForce
1049 public function setForce($isForce) {
1050 $this->_force
= $isForce;
1054 * Setter for $_limitValue.
1056 * @param int $_limitValue
1058 public function setLimitValue($_limitValue) {
1059 $this->_limitValue
= $_limitValue;
1063 * Setter for $_offsetValue.
1065 * @param int $_offsetValue
1067 public function setOffsetValue($_offsetValue) {
1068 $this->_offsetValue
= $_offsetValue;
1072 * Setter for $addPaging.
1074 * @param bool $value
1076 public function setAddPaging($value) {
1077 $this->addPaging
= $value;
1081 * Getter for $_defaultValues.
1085 public function getDefaultValues() {
1086 return $this->_defaults
;
1090 * Add columns to report.
1092 public function addColumns() {
1095 foreach ($this->_columns
as $tableName => $table) {
1096 if (array_key_exists('fields', $table)) {
1097 foreach ($table['fields'] as $fieldName => $field) {
1099 if (empty($field['no_display'])) {
1100 foreach (array('table', 'field') as $var) {
1101 if (!empty($
{$var}['grouping'])) {
1102 if (!is_array($
{$var}['grouping'])) {
1103 $tableName = $
{$var}['grouping'];
1106 $tableName = array_keys($
{$var}['grouping']);
1107 $tableName = $tableName[0];
1108 $groupTitle = array_values($
{$var}['grouping']);
1109 $groupTitle = $groupTitle[0];
1114 if (!$groupTitle && isset($table['group_title'])) {
1115 $groupTitle = $table['group_title'];
1116 // Having a group_title is secret code for being a custom group
1117 // which cryptically translates to needing an accordion.
1118 // here we make that explicit.
1119 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1122 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1123 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1124 $colGroups[$tableName]['group_title'] = $groupTitle;
1126 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1132 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1133 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1135 if (!empty($colGroups)) {
1136 $this->tabs
['FieldSelection'] = array(
1137 'title' => ts('Columns'),
1138 'tpl' => 'FieldSelection',
1139 'div_label' => 'col-groups',
1142 // Note this assignment is only really required in buildForm. It is being 'over-called'
1143 // to reduce risk of being missed due to overridden functions.
1144 $this->assign('tabs', $this->tabs
);
1147 $this->assign('colGroups', $colGroups);
1151 * Add filters to report.
1153 public function addFilters() {
1154 $filters = $filterGroups = array();
1157 foreach ($this->_filters
as $table => $attributes) {
1158 if (isset($this->_columns
[$table]['group_title'])) {
1159 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1160 // which magically means to 'display in an accordian'
1161 // here we make this explicit.
1162 $filterGroups[$table] = array(
1163 'group_title' => $this->_columns
[$table]['group_title'],
1164 'use_accordian_for_field_selection' => TRUE,
1168 foreach ($attributes as $fieldName => $field) {
1169 // get ready with option value pair
1170 // @ 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
1172 $operations = $this->getOperationPair(
1173 CRM_Utils_Array
::value('operatorType', $field),
1176 $filters[$table][$fieldName] = $field;
1178 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1179 case CRM_Report_Form
::OP_MONTH
:
1180 if (!array_key_exists('options', $field) ||
1181 !is_array($field['options']) ||
empty($field['options'])
1183 // If there's no option list for this filter, define one.
1184 $field['options'] = array(
1186 2 => ts('February'),
1193 9 => ts('September'),
1194 10 => ts('October'),
1195 11 => ts('November'),
1196 12 => ts('December'),
1198 // Add this option list to this column _columns. This is
1199 // required so that filter statistics show properly.
1200 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1202 case CRM_Report_Form
::OP_MULTISELECT
:
1203 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1204 // assume a multi-select field
1205 if (!empty($field['options']) ||
1206 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1208 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1209 if (count($operations) <= 1) {
1212 if ($fieldName == 'state_province_id' ||
1213 $fieldName == 'county_id'
1215 $this->addChainSelect($fieldName . '_value', array(
1222 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1223 'style' => 'min-width:250px',
1224 'class' => 'crm-select2 huge',
1226 'placeholder' => ts('- select -'),
1232 case CRM_Report_Form
::OP_SELECT
:
1233 // assume a select field
1234 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1235 if (!empty($field['options'])) {
1236 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1240 case CRM_Report_Form
::OP_ENTITYREF
:
1241 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1242 $this->setEntityRefDefaults($field, $table);
1243 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1246 case CRM_Report_Form
::OP_DATE
:
1247 // build datetime fields
1248 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1252 case CRM_Report_Form
::OP_DATETIME
:
1253 // build datetime fields
1254 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1258 case CRM_Report_Form
::OP_INT
:
1259 case CRM_Report_Form
::OP_FLOAT
:
1260 // and a min value input box
1261 $this->add('text', "{$fieldName}_min", ts('Min'));
1262 // and a max value input box
1263 $this->add('text', "{$fieldName}_max", ts('Max'));
1265 // default type is string
1266 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1267 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1269 // we need text box for value input
1270 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1275 if (!empty($filters)) {
1276 $this->tabs
['Filters'] = array(
1277 'title' => ts('Filters'),
1279 'div_label' => 'set-filters',
1282 $this->assign('filters', $filters);
1283 $this->assign('filterGroups', $filterGroups);
1287 * Function to assign the tabs to the template in the correct order.
1289 * We want the tabs to wind up in this order (if not overridden).
1297 protected function assignTabs() {
1305 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1306 $order = array_merge($order, $this->tabs
);
1307 $this->assign('tabs', $order);
1311 * The intent is to add a tab for developers to view the sql.
1313 * Currently using dpm.
1315 * @param string $sql
1317 protected function addToDeveloperTab($sql) {
1318 if (!CRM_Core_Permission
::check('view report sql')) {
1321 $this->tabs
['Developer'] = array(
1322 'title' => ts('Developer'),
1323 'tpl' => 'Developer',
1324 'div_label' => 'set-developer',
1327 $this->assignTabs();
1328 $this->sqlArray
[] = $sql;
1329 foreach ($this->sqlArray
as $sql) {
1330 foreach (array('LEFT JOIN') as $term) {
1331 $sql = str_replace($term, '<br>  ' . $term, $sql);
1333 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1334 $sql = str_replace($term, '<br><br>' . $term, $sql);
1336 $this->sqlFormattedArray
[] = $sql;
1337 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1342 * Add options defined in $this->_options to the report.
1344 public function addOptions() {
1345 if (!empty($this->_options
)) {
1346 // FIXME: For now lets build all elements as checkboxes.
1347 // Once we clear with the format we can build elements based on type
1349 foreach ($this->_options
as $fieldName => $field) {
1352 if ($field['type'] == 'select') {
1353 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1355 elseif ($field['type'] == 'checkbox') {
1356 $options[$field['title']] = $fieldName;
1357 $this->addCheckBox($fieldName, NULL,
1359 NULL, NULL, NULL, $this->_fourColumnAttribute
1364 if (!empty($this->_options
) &&
1366 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1368 $this->tabs
['ReportOptions'] = array(
1369 'title' => ts('Display Options'),
1370 'tpl' => 'ReportOptions',
1371 'div_label' => 'other-options',
1374 $this->assign('otherOptions', $this->_options
);
1378 * Add chart options to the report.
1380 public function addChartOptions() {
1381 if (!empty($this->_charts
)) {
1382 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1383 $this->assign('charts', $this->_charts
);
1384 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1389 * Add group by options to the report.
1391 public function addGroupBys() {
1392 $options = $freqElements = array();
1394 foreach ($this->_columns
as $tableName => $table) {
1395 if (array_key_exists('group_bys', $table)) {
1396 foreach ($table['group_bys'] as $fieldName => $field) {
1397 if (!empty($field)) {
1398 $options[$field['title']] = $fieldName;
1399 if (!empty($field['frequency'])) {
1400 $freqElements[$field['title']] = $fieldName;
1406 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1407 NULL, NULL, NULL, $this->_fourColumnAttribute
1409 $this->assign('groupByElements', $options);
1410 if (!empty($options)) {
1411 $this->tabs
['GroupBy'] = array(
1412 'title' => ts('Grouping'),
1414 'div_label' => 'group-by-elements',
1418 foreach ($freqElements as $name) {
1419 $this->addElement('select', "group_bys_freq[$name]",
1420 ts('Frequency'), $this->_groupByDateFreq
1426 * Add data for order by tab.
1428 public function addOrderBys() {
1430 foreach ($this->_columns
as $tableName => $table) {
1432 // Report developer may define any column to order by; include these as order-by options.
1433 if (array_key_exists('order_bys', $table)) {
1434 foreach ($table['order_bys'] as $fieldName => $field) {
1435 if (!empty($field)) {
1436 $options[$fieldName] = $field['title'];
1441 // Add searchable custom fields as order-by options, if so requested
1442 // (These are already indexed, so allowing to order on them is cheap.)
1444 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1445 array_key_exists('extends', $table) && !empty($table['extends'])
1447 foreach ($table['fields'] as $fieldName => $field) {
1448 if (empty($field['no_display'])) {
1449 $options[$fieldName] = $field['title'];
1457 $this->assign('orderByOptions', $options);
1458 if (!empty($options)) {
1459 $this->tabs
['OrderBy'] = array(
1460 'title' => ts('Sorting'),
1462 'div_label' => 'order-by-elements',
1466 if (!empty($options)) {
1468 '-' => ' - none - ',
1470 for ($i = 1; $i <= 5; $i++
) {
1471 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1472 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1473 'ASC' => ts('Ascending'),
1474 'DESC' => ts('Descending'),
1476 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1477 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1483 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1485 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1486 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1489 public function buildInstanceAndButtons() {
1490 CRM_Report_Form_Instance
::buildForm($this);
1491 $this->_actionButtonName
= $this->getButtonName('submit');
1492 $this->addTaskMenu($this->getActions($this->_id
));
1494 $this->assign('instanceForm', $this->_instanceForm
);
1496 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1497 $permission = CRM_Core_Permission
::getPermission();
1498 if ($permission == CRM_Core_Permission
::EDIT
&&
1499 $this->_add2groupSupported
1501 $this->addElement('select', 'groups', ts('Group'),
1502 array('' => ts('Add Contacts to Group')) +
1503 CRM_Core_PseudoConstant
::nestedGroup(),
1504 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1506 $this->assign('group', TRUE);
1509 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1511 $this->addChartOptions();
1512 $showResultsLabel = $this->getResultsLabel();
1513 $this->addButtons(array(
1516 'name' => $showResultsLabel,
1517 'isDefault' => TRUE,
1524 * Has this form been submitted already?
1528 public function resultsDisplayed() {
1529 $buttonName = $this->controller
->getButtonName();
1530 return ($buttonName ||
$this->_outputMode
);
1534 * Get the actions for this report instance.
1536 * @param int $instanceId
1540 protected function getActions($instanceId) {
1541 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1542 if (empty($instanceId)) {
1543 $actions['report_instance.save'] = array(
1544 'title' => ts('Create Report'),
1546 'is_confirm' => TRUE,
1547 'confirm_title' => ts('Create Report'),
1548 'confirm_refresh_fields' => json_encode(array(
1549 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1550 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1556 if (!$this->_csvSupported
) {
1557 unset($actions['report_instance.csv']);
1564 * Main build form function.
1566 public function buildQuickForm() {
1567 $this->addColumns();
1569 $this->addFilters();
1571 $this->addOptions();
1573 $this->addGroupBys();
1575 $this->addOrderBys();
1577 $this->buildInstanceAndButtons();
1579 // Add form rule for report.
1580 if (is_callable(array(
1584 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1586 $this->assignTabs();
1590 * A form rule function for custom data.
1592 * The rule ensures that fields selected in group_by if any) should only be the ones
1593 * present in display/select fields criteria;
1594 * note: works if and only if any custom field selected in group_by.
1596 * @param array $fields
1597 * @param array $ignoreFields
1601 public function customDataFormRule($fields, $ignoreFields = array()) {
1603 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1604 !empty($fields['group_bys'])
1606 foreach ($this->_columns
as $tableName => $table) {
1607 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1608 substr($tableName, 0, 12) == 'custom_value') &&
1609 !empty($this->_columns
[$tableName]['fields'])
1611 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1612 if (array_key_exists($fieldName, $fields['group_bys']) &&
1613 !array_key_exists($fieldName, $fields['fields'])
1615 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1617 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1618 foreach ($fields['fields'] as $fld => $val) {
1619 if (!array_key_exists($fld, $fields['group_bys']) &&
1620 !in_array($fld, $ignoreFields)
1622 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1634 * Get operators to display on form.
1636 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1638 * @param string $type
1639 * @param string $fieldName
1643 public function getOperationPair($type = "string", $fieldName = NULL) {
1644 // FIXME: At some point we should move these key-val pairs
1645 // to option_group and option_value table.
1647 case CRM_Report_Form
::OP_INT
:
1648 case CRM_Report_Form
::OP_FLOAT
:
1651 'lte' => ts('Is less than or equal to'),
1652 'gte' => ts('Is greater than or equal to'),
1653 'bw' => ts('Is between'),
1654 'eq' => ts('Is equal to'),
1655 'lt' => ts('Is less than'),
1656 'gt' => ts('Is greater than'),
1657 'neq' => ts('Is not equal to'),
1658 'nbw' => ts('Is not between'),
1659 'nll' => ts('Is empty (Null)'),
1660 'nnll' => ts('Is not empty (Null)'),
1664 case CRM_Report_Form
::OP_SELECT
:
1666 'eq' => ts('Is equal to'),
1670 case CRM_Report_Form
::OP_MONTH
:
1671 case CRM_Report_Form
::OP_MULTISELECT
:
1672 case CRM_Report_Form
::OP_ENTITYREF
:
1675 'in' => ts('Is one of'),
1676 'notin' => ts('Is not one of'),
1680 case CRM_Report_Form
::OP_DATE
:
1683 'nll' => ts('Is empty (Null)'),
1684 'nnll' => ts('Is not empty (Null)'),
1688 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1689 // use this operator for the values, concatenated with separator. For e.g if
1690 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1692 'mhas' => ts('Is one of'),
1693 'mnot' => ts('Is not one of'),
1700 'has' => ts('Contains'),
1701 'sw' => ts('Starts with'),
1702 'ew' => ts('Ends with'),
1703 'nhas' => ts('Does not contain'),
1704 'eq' => ts('Is equal to'),
1705 'neq' => ts('Is not equal to'),
1706 'nll' => ts('Is empty (Null)'),
1707 'nnll' => ts('Is not empty (Null)'),
1714 * Build the tag filter field to display on the filters tab.
1716 public function buildTagFilter() {
1717 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1718 if (!empty($contactTags)) {
1719 $this->_columns
['civicrm_tag'] = array(
1720 'dao' => 'CRM_Core_DAO_Tag',
1724 'title' => ts('Tag'),
1725 'type' => CRM_Utils_Type
::T_INT
,
1727 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1728 'options' => $contactTags,
1736 * Adds group filters to _columns (called from _Construct).
1738 public function buildGroupFilter() {
1739 $this->_columns
['civicrm_group']['filters'] = array(
1741 'name' => 'group_id',
1742 'title' => ts('Group'),
1743 'type' => CRM_Utils_Type
::T_INT
,
1744 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1746 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1749 if (empty($this->_columns
['civicrm_group']['dao'])) {
1750 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1752 if (empty($this->_columns
['civicrm_group']['alias'])) {
1753 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1758 * Get SQL operator from form text version.
1760 * @param string $operator
1764 public function getSQLOperator($operator = "like") {
1765 switch ($operator) {
1798 return 'IS NOT NULL';
1807 * Generate where clause.
1809 * This can be overridden in reports for special treatment of a field
1811 * @param array $field Field specifications
1812 * @param string $op Query operator (not an exact match to sql)
1813 * @param mixed $value
1817 * @return null|string
1819 public function whereClause(&$field, $op, $value, $min, $max) {
1821 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1823 // CRM-18010: Ensure type of each report filters
1825 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1832 if (($min !== NULL && strlen($min) > 0) ||
1833 ($max !== NULL && strlen($max) > 0)
1837 $min = CRM_Utils_Type
::escape($min, $type);
1839 $clauses[] = "( {$field['dbAlias']} >= $min )";
1842 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1846 $max = CRM_Utils_Type
::escape($max, $type);
1848 $clauses[] = "( {$field['dbAlias']} <= $max )";
1851 $clauses[] = "( {$field['dbAlias']} > $max )";
1855 if (!empty($clauses)) {
1857 $clause = implode(' AND ', $clauses);
1860 $clause = '(' . implode('OR', $clauses) . ')';
1868 if ($value !== NULL && strlen($value) > 0) {
1869 $value = CRM_Utils_Type
::escape($value, $type);
1870 if (strpos($value, '%') === FALSE) {
1871 $value = "'%{$value}%'";
1874 $value = "'{$value}'";
1876 $sqlOP = $this->getSQLOperator($op);
1877 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1883 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1884 $value = explode(',', $value);
1886 if ($value !== NULL && is_array($value) && count($value) > 0) {
1887 $sqlOP = $this->getSQLOperator($op);
1888 if (CRM_Utils_Array
::value('type', $field) ==
1889 CRM_Utils_Type
::T_STRING
1891 //cycle through selections and escape values
1892 foreach ($value as $key => $selection) {
1893 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1896 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1900 // for numerical values
1901 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1904 if ($op == 'notin') {
1905 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1908 $clause = "( " . $clause . " )";
1915 // multiple has or multiple not
1916 if ($value !== NULL && count($value) > 0) {
1917 $value = CRM_Utils_Type
::escapeAll($value, $type);
1918 $operator = $op == 'mnot' ?
'NOT' : '';
1919 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1920 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1926 if ($value !== NULL && strlen($value) > 0) {
1927 $value = CRM_Utils_Type
::escape($value, $type);
1928 if (strpos($value, '%') === FALSE) {
1930 $value = "'{$value}%'";
1933 $value = "'%{$value}'";
1937 $value = "'{$value}'";
1939 $sqlOP = $this->getSQLOperator($op);
1940 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1946 $sqlOP = $this->getSQLOperator($op);
1947 $clause = "( {$field['dbAlias']} $sqlOP )";
1953 //CRM-18457: some custom field passes value in array format against binary operator
1954 if (is_array($value) && count($value)) {
1959 if ($value !== NULL && $value !== '') {
1960 if (isset($field['clause'])) {
1961 // FIXME: we not doing escape here. Better solution is to use two
1962 // different types - data-type and filter-type
1963 $clause = $field['clause'];
1965 elseif (!is_array($value)) {
1966 $value = CRM_Utils_Type
::escape($value, $type);
1967 $sqlOP = $this->getSQLOperator($op);
1968 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1969 $value = "'{$value}'";
1971 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1977 if (!empty($field['group']) && $clause) {
1978 $clause = $this->whereGroupClause($field, $value, $op);
1980 elseif (!empty($field['tag']) && $clause) {
1981 // not using left join in query because if any contact
1982 // belongs to more than one tag, results duplicate
1984 $clause = $this->whereTagClause($field, $value, $op);
1986 elseif (!empty($field['membership_org']) && $clause) {
1987 $clause = $this->whereMembershipOrgClause($value, $op);
1989 elseif (!empty($field['membership_type']) && $clause) {
1990 $clause = $this->whereMembershipTypeClause($value, $op);
1996 * Get SQL where clause for a date field.
1998 * @param string $fieldName
1999 * @param string $relative
2000 * @param string $from
2002 * @param string $type
2003 * @param string $fromTime
2004 * @param string $toTime
2006 * @return null|string
2008 public function dateClause(
2010 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2013 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2014 $sqlOP = $this->getSQLOperator($relative);
2015 return "( {$fieldName} {$sqlOP} )";
2018 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2021 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2022 $clauses[] = "( {$fieldName} >= $from )";
2026 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2027 $clauses[] = "( {$fieldName} <= {$to} )";
2030 if (!empty($clauses)) {
2031 return implode(' AND ', $clauses);
2038 * Get values for from and to for date ranges.
2040 * @param bool $relative
2041 * @param string $from
2043 * @param string $fromTime
2044 * @param string $toTime
2048 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2049 if (empty($toTime)) {
2052 //FIX ME not working for relative
2054 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2055 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2056 $from = substr($dateRange['from'], 0, 8);
2057 //Take only Date Part, Sometime Time part is also present in 'to'
2058 $to = substr($dateRange['to'], 0, 8);
2060 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2061 $to = CRM_Utils_Date
::processDate($to, $toTime);
2062 return array($from, $to);
2066 * Alter display of rows.
2068 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2069 * such as rendering contacts as links.
2071 * @param array $rows
2072 * Rows generated by SQL, with an array for each row.
2074 public function alterDisplay(&$rows) {
2078 * Alter the way in which custom data fields are displayed.
2080 * @param array $rows
2082 public function alterCustomDataDisplay(&$rows) {
2083 // custom code to alter rows having custom values
2084 if (empty($this->_customGroupExtends
)) {
2088 $customFields = array();
2089 $customFieldIds = array();
2090 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2091 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2092 $customFieldIds[$fieldAlias] = $fieldId;
2095 if (empty($customFieldIds)) {
2099 // skip for type date and ContactReference since date format is already handled
2101 SELECT cg.table_name, cf.id
2102 FROM civicrm_custom_field cf
2103 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2104 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2105 cg.is_active = 1 AND
2106 cf.is_active = 1 AND
2107 cf.is_searchable = 1 AND
2108 cf.data_type NOT IN ('ContactReference', 'Date') AND
2109 cf.id IN (" . implode(",", $customFieldIds) . ")";
2111 $dao = CRM_Core_DAO
::executeQuery($query);
2112 while ($dao->fetch()) {
2113 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2117 $entryFound = FALSE;
2118 foreach ($rows as $rowNum => $row) {
2119 foreach ($row as $tableCol => $val) {
2120 if (array_key_exists($tableCol, $customFields)) {
2121 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2126 // skip looking further in rows, if first row itself doesn't
2127 // have the column we need
2135 * Remove duplicate rows.
2137 * @param array $rows
2139 public function removeDuplicates(&$rows) {
2140 if (empty($this->_noRepeats
)) {
2143 $checkList = array();
2145 foreach ($rows as $key => $list) {
2146 foreach ($list as $colName => $colVal) {
2147 if (array_key_exists($colName, $checkList) &&
2148 $checkList[$colName] == $colVal
2150 $rows[$key][$colName] = "";
2152 if (in_array($colName, $this->_noRepeats
)) {
2153 $checkList[$colName] = $colVal;
2160 * Fix subtotal display.
2163 * @param array $fields
2164 * @param bool $subtotal
2166 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2167 foreach ($row as $colName => $colVal) {
2168 if (in_array($colName, $fields)) {
2170 elseif (isset($this->_columnHeaders
[$colName])) {
2172 $row[$colName] = 'Subtotal';
2176 unset($row[$colName]);
2183 * Calculate grant total.
2185 * @param array $rows
2189 public function grandTotal(&$rows) {
2190 if (!$this->_rollup ||
count($rows) == 1) {
2194 $this->moveSummaryColumnsToTheRightHandSide();
2196 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2200 $this->rollupRow
= array_pop($rows);
2202 foreach ($this->_columnHeaders
as $fld => $val) {
2203 if (!in_array($fld, $this->_statFields
)) {
2204 if (!$this->_grandFlag
) {
2205 $this->rollupRow
[$fld] = ts('Grand Total');
2206 $this->_grandFlag
= TRUE;
2209 $this->rollupRow
[$fld] = "";
2214 $this->assign('grandStat', $this->rollupRow
);
2219 * Format display output.
2221 * @param array $rows
2222 * @param bool $pager
2224 public function formatDisplay(&$rows, $pager = TRUE) {
2225 // set pager based on if any limit was applied in the query.
2230 // allow building charts if any
2231 if (!empty($this->_params
['charts']) && !empty($rows)) {
2232 $this->buildChart($rows);
2233 $this->assign('chartEnabled', TRUE);
2234 $this->_chartId
= "{$this->_params['charts']}_" .
2235 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2237 $this->assign('chartId', $this->_chartId
);
2240 // unset columns not to be displayed.
2241 foreach ($this->_columnHeaders
as $key => $value) {
2242 if (!empty($value['no_display'])) {
2243 unset($this->_columnHeaders
[$key]);
2247 // unset columns not to be displayed.
2248 if (!empty($rows)) {
2249 foreach ($this->_noDisplay
as $noDisplayField) {
2250 foreach ($rows as $rowNum => $row) {
2251 unset($this->_columnHeaders
[$noDisplayField]);
2256 // build array of section totals
2257 $this->sectionTotals();
2259 // process grand-total row
2260 $this->grandTotal($rows);
2262 // use this method for formatting rows for display purpose.
2263 $this->alterDisplay($rows);
2264 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2266 // use this method for formatting custom rows for display purpose.
2267 $this->alterCustomDataDisplay($rows);
2273 * @param array $rows
2275 public function buildChart(&$rows) {
2276 // override this method for building charts.
2279 // select() method below has been added recently (v3.3), and many of the report templates might
2280 // still be having their own select() method. We should fix them as and when encountered and move
2281 // towards generalizing the select() method below.
2284 * Generate the SELECT clause and set class variable $_select.
2286 public function select() {
2287 $select = $this->_selectAliases
= array();
2289 foreach ($this->_columns
as $tableName => $table) {
2290 if (array_key_exists('fields', $table)) {
2291 foreach ($table['fields'] as $fieldName => $field) {
2292 if ($tableName == 'civicrm_address') {
2293 // deprecated, use $this->isTableSelected.
2294 $this->_addressField
= TRUE;
2296 if ($tableName == 'civicrm_email') {
2297 $this->_emailField
= TRUE;
2299 if ($tableName == 'civicrm_phone') {
2300 $this->_phoneField
= TRUE;
2303 if (!empty($field['required']) ||
2304 !empty($this->_params
['fields'][$fieldName])
2307 // 1. In many cases we want select clause to be built in slightly different way
2308 // for a particular field of a particular type.
2309 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2311 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2312 if ($selectClause) {
2313 $select[] = $selectClause;
2317 // include statistics columns only if set
2318 if (!empty($field['statistics'])) {
2319 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2322 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2328 // select for group bys
2329 if (array_key_exists('group_bys', $table)) {
2330 foreach ($table['group_bys'] as $fieldName => $field) {
2332 if ($tableName == 'civicrm_address') {
2333 $this->_addressField
= TRUE;
2335 if ($tableName == 'civicrm_email') {
2336 $this->_emailField
= TRUE;
2338 if ($tableName == 'civicrm_phone') {
2339 $this->_phoneField
= TRUE;
2341 // 1. In many cases we want select clause to be built in slightly different way
2342 // for a particular field of a particular type.
2343 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2345 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2346 if ($selectClause) {
2347 $select[] = $selectClause;
2351 if (!empty($this->_params
['group_bys']) &&
2352 !empty($this->_params
['group_bys'][$fieldName]) &&
2353 !empty($this->_params
['group_bys_freq'])
2355 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2357 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2358 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2359 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2360 $field['title'] = 'Week';
2364 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2365 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2366 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2367 $field['title'] = 'Year';
2371 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2372 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2373 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2374 $field['title'] = 'Month';
2378 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2379 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2380 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2381 $field['title'] = 'Quarter';
2384 // for graphs and charts -
2385 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2386 $this->_interval
= $field['title'];
2387 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2388 = $field['title'] . ' Beginning';
2389 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2390 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2392 // just to make sure these values are transferred to rows.
2393 // since we 'll need them for calculation purpose,
2394 // e.g making subtotals look nicer or graphs
2395 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2396 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2403 $this->_selectClauses
= $select;
2404 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2408 * Build select clause for a single field.
2410 * @param string $tableName
2411 * @param string $tableKey
2412 * @param string $fieldName
2413 * @param string $field
2417 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2422 * Build where clause.
2424 public function where() {
2425 $this->storeWhereHavingClauseArray();
2427 if (empty($this->_whereClauses
)) {
2428 $this->_where
= "WHERE ( 1 ) ";
2429 $this->_having
= "";
2432 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2435 if ($this->_aclWhere
) {
2436 $this->_where
.= " AND {$this->_aclWhere} ";
2439 if (!empty($this->_havingClauses
)) {
2440 // use this clause to construct group by clause.
2441 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2446 * Store Where clauses into an array.
2448 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2449 * temp table that may not be part of the final where clause or added
2450 * in other functions
2452 public function storeWhereHavingClauseArray() {
2453 foreach ($this->_columns
as $tableName => $table) {
2454 if (array_key_exists('filters', $table)) {
2455 foreach ($table['filters'] as $fieldName => $field) {
2456 // respect pseudofield to filter spec so fields can be marked as
2457 // not to be handled here
2458 if (!empty($field['pseudofield'])) {
2462 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2463 if (CRM_Utils_Array
::value('operatorType', $field) ==
2464 CRM_Report_Form
::OP_MONTH
2466 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2467 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2468 if (is_array($value) && !empty($value)) {
2470 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2475 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2476 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2477 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2478 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2479 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2480 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2484 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2486 $clause = $this->whereClause($field,
2488 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2489 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2490 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2495 if (!empty($clause)) {
2496 if (!empty($field['having'])) {
2497 $this->_havingClauses
[] = $clause;
2500 $this->_whereClauses
[] = $clause;
2512 public function processReportMode() {
2513 $this->setOutputMode();
2516 = CRM_Utils_Request
::retrieve(
2519 CRM_Core_DAO
::$_nullObject
2522 $this->_absoluteUrl
= FALSE;
2524 $this->assign('printOnly', FALSE);
2526 if ($this->_outputMode
== 'print' ||
2527 ($this->_sendmail
&& !$this->_outputMode
)
2529 $this->assign('printOnly', TRUE);
2531 $this->addPaging
= FALSE;
2532 $this->assign('outputMode', 'print');
2533 $this->_outputMode
= 'print';
2534 if ($this->_sendmail
) {
2535 $this->_absoluteUrl
= TRUE;
2538 elseif ($this->_outputMode
== 'pdf') {
2540 $this->addPaging
= FALSE;
2541 $this->_absoluteUrl
= TRUE;
2543 elseif ($this->_outputMode
== 'csv') {
2545 $this->_absoluteUrl
= TRUE;
2546 $this->addPaging
= FALSE;
2548 elseif ($this->_outputMode
== 'group') {
2549 $this->assign('outputMode', 'group');
2551 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2552 $this->assign('outputMode', 'create_report');
2554 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2555 $this->_createNew
= TRUE;
2558 $this->assign('outputMode', $this->_outputMode
);
2559 $this->assign('printOnly', $printOnly);
2560 // Get today's date to include in printed reports
2562 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2563 $this->assign('reportDate', $reportDate);
2568 * Post Processing function for Form.
2570 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2571 * This function is not accessed when the api calls the report.
2573 public function beginPostProcess() {
2574 $this->setParams($this->controller
->exportValues($this->_name
));
2575 if (empty($this->_params
) &&
2578 $this->setParams($this->_formValues
);
2581 // hack to fix params when submitted from dashboard, CRM-8532
2582 // fields array is missing because form building etc is skipped
2583 // in dashboard mode for report
2584 //@todo - this could be done in the dashboard no we have a setter
2585 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2586 $this->setParams($this->_formValues
);
2589 $this->processReportMode();
2591 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2592 $this->_createNew
= ($this->_outputMode
== 'copy');
2593 CRM_Report_Form_Instance
::postProcess($this);
2595 if ($this->_outputMode
== 'delete') {
2596 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2599 $this->_formValues
= $this->_params
;
2601 $this->beginPostProcessCommon();
2605 * BeginPostProcess function run in both report mode and non-report mode (api).
2607 public function beginPostProcessCommon() {
2611 * Build the report query.
2613 * @param bool $applyLimit
2617 public function buildQuery($applyLimit = TRUE) {
2618 $this->buildGroupTempTable();
2621 $this->customDataFrom();
2622 $this->buildPermissionClause();
2624 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2625 $this->getPermissionedFTQuery($this);
2630 // order_by columns not selected for display need to be included in SELECT
2631 $unselectedSectionColumns = $this->unselectedSectionColumns();
2632 foreach ($unselectedSectionColumns as $alias => $section) {
2633 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2636 if ($applyLimit && empty($this->_params
['charts'])) {
2639 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2641 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2642 $this->addToDeveloperTab($sql);
2647 * Build group by clause.
2649 public function groupBy() {
2650 $groupBys = array();
2651 if (!empty($this->_params
['group_bys']) &&
2652 is_array($this->_params
['group_bys'])
2654 foreach ($this->_columns
as $tableName => $table) {
2655 if (array_key_exists('group_bys', $table)) {
2656 foreach ($table['group_bys'] as $fieldName => $field) {
2657 if (!empty($this->_params
['group_bys'][$fieldName])) {
2658 $groupBys[] = $field['dbAlias'];
2665 if (!empty($groupBys)) {
2666 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBys);
2671 * Build order by clause.
2673 public function orderBy() {
2674 $this->_orderBy
= "";
2675 $this->_sections
= array();
2676 $this->storeOrderByArray();
2677 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2678 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2680 $this->assign('sections', $this->_sections
);
2684 * Extract order by fields and store as an array.
2686 * In some cases other functions want to know which fields are selected for ordering by
2687 * Separating this into a separate function allows it to be called separately from constructing
2688 * the order by clause
2690 public function storeOrderByArray() {
2691 $orderBys = array();
2693 if (!empty($this->_params
['order_bys']) &&
2694 is_array($this->_params
['order_bys']) &&
2695 !empty($this->_params
['order_bys'])
2698 // Process order_bys in user-specified order
2699 foreach ($this->_params
['order_bys'] as $orderBy) {
2700 $orderByField = array();
2701 foreach ($this->_columns
as $tableName => $table) {
2702 if (array_key_exists('order_bys', $table)) {
2703 // For DAO columns defined in $this->_columns
2704 $fields = $table['order_bys'];
2706 elseif (array_key_exists('extends', $table)) {
2707 // For custom fields referenced in $this->_customGroupExtends
2708 $fields = CRM_Utils_Array
::value('fields', $table, array());
2713 if (!empty($fields) && is_array($fields)) {
2714 foreach ($fields as $fieldName => $field) {
2715 if ($fieldName == $orderBy['column']) {
2716 $orderByField = array_merge($field, $orderBy);
2717 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2724 if (!empty($orderByField)) {
2725 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2726 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2728 // Record any section headers for assignment to the template
2729 if (!empty($orderBy['section'])) {
2730 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2731 $this->_sections
[$orderByField['tplField']] = $orderByField;
2737 $this->_orderByArray
= $orderBys;
2739 $this->assign('sections', $this->_sections
);
2743 * Determine unselected columns.
2747 public function unselectedSectionColumns() {
2748 if (is_array($this->_sections
)) {
2749 return array_diff_key($this->_sections
, $this->getSelectColumns());
2757 * Build output rows.
2759 * @param string $sql
2760 * @param array $rows
2762 public function buildRows($sql, &$rows) {
2763 $dao = CRM_Core_DAO
::executeQuery($sql);
2764 if (!is_array($rows)) {
2768 // use this method to modify $this->_columnHeaders
2769 $this->modifyColumnHeaders();
2771 $unselectedSectionColumns = $this->unselectedSectionColumns();
2773 while ($dao->fetch()) {
2775 foreach ($this->_columnHeaders
as $key => $value) {
2776 if (property_exists($dao, $key)) {
2777 $row[$key] = $dao->$key;
2781 // section headers not selected for display need to be added to row
2782 foreach ($unselectedSectionColumns as $key => $values) {
2783 if (property_exists($dao, $key)) {
2784 $row[$key] = $dao->$key;
2793 * Calculate section totals.
2795 * When "order by" fields are marked as sections, this assigns to the template
2796 * an array of total counts for each section. This data is used by the Smarty
2797 * plugin {sectionTotal}.
2799 public function sectionTotals() {
2801 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2802 if (empty($this->_selectAliases
)) {
2806 if (!empty($this->_sections
)) {
2807 // build the query with no LIMIT clause
2808 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2809 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2811 // pull section aliases out of $this->_sections
2812 $sectionAliases = array_keys($this->_sections
);
2815 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2816 $ifnulls[] = "ifnull($alias, '') as $alias";
2818 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2819 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2821 // Group (un-limited) report by all aliases and get counts. This might
2822 // be done more efficiently when the contents of $sql are known, ie. by
2823 // overriding this method in the report class.
2825 $query = $this->_select
.
2826 ", count(*) as ct from ($sql) as subquery group by " .
2827 implode(", ", $sectionAliases);
2829 // initialize array of total counts
2831 $dao = CRM_Core_DAO
::executeQuery($query);
2832 while ($dao->fetch()) {
2834 // let $this->_alterDisplay translate any integer ids to human-readable values.
2835 $rows[0] = $dao->toArray();
2836 $this->alterDisplay($rows);
2839 // add totals for all permutations of section values
2842 $aliasCount = count($sectionAliases);
2843 foreach ($sectionAliases as $alias) {
2844 $values[] = $row[$alias];
2845 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2846 if ($i == $aliasCount) {
2847 // the last alias is the lowest-level section header; use count as-is
2848 $totals[$key] = $dao->ct
;
2851 // other aliases are higher level; roll count into their total
2852 $totals[$key] +
= $dao->ct
;
2856 $this->assign('sectionTotals', $totals);
2861 * Modify column headers.
2863 public function modifyColumnHeaders() {
2864 // use this method to modify $this->_columnHeaders
2868 * Move totals columns to the right edge of the table.
2870 * It seems like a more logical layout to have any totals columns on the far right regardless of
2871 * the location of the rest of their table.
2873 public function moveSummaryColumnsToTheRightHandSide() {
2874 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2875 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2879 * Assign rows to the template.
2881 * @param array $rows
2883 public function doTemplateAssignment(&$rows) {
2884 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2885 $this->assign_by_ref('rows', $rows);
2886 $this->assign('statistics', $this->statistics($rows));
2890 * Build report statistics.
2892 * Override this method to build your own statistics.
2894 * @param array $rows
2898 public function statistics(&$rows) {
2899 $statistics = array();
2901 $count = count($rows);
2902 // Why do we increment the count for rollup seems to artificially inflate the count.
2903 // It seems perhaps intentional to include the summary row in the count of results - although
2904 // this just seems odd.
2905 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2909 $this->countStat($statistics, $count);
2911 $this->groupByStat($statistics);
2913 $this->filterStat($statistics);
2919 * Add count statistics.
2921 * @param array $statistics
2924 public function countStat(&$statistics, $count) {
2925 $statistics['counts']['rowCount'] = array(
2926 'title' => ts('Row(s) Listed'),
2930 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2931 $statistics['counts']['rowsFound'] = array(
2932 'title' => ts('Total Row(s)'),
2933 'value' => $this->_rowsFound
,
2939 * Add group by statistics.
2941 * @param array $statistics
2943 public function groupByStat(&$statistics) {
2944 if (!empty($this->_params
['group_bys']) &&
2945 is_array($this->_params
['group_bys']) &&
2946 !empty($this->_params
['group_bys'])
2948 foreach ($this->_columns
as $tableName => $table) {
2949 if (array_key_exists('group_bys', $table)) {
2950 foreach ($table['group_bys'] as $fieldName => $field) {
2951 if (!empty($this->_params
['group_bys'][$fieldName])) {
2952 $combinations[] = $field['title'];
2957 $statistics['groups'][] = array(
2958 'title' => ts('Grouping(s)'),
2959 'value' => implode(' & ', $combinations),
2965 * Filter statistics.
2967 * @param array $statistics
2969 public function filterStat(&$statistics) {
2970 foreach ($this->_columns
as $tableName => $table) {
2971 if (array_key_exists('filters', $table)) {
2972 foreach ($table['filters'] as $fieldName => $field) {
2973 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2974 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2975 CRM_Utils_Array
::value('operatorType', $field) !=
2976 CRM_Report_Form
::OP_MONTH
2980 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2981 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2982 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2983 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2984 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2986 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2987 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2989 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2990 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2993 $statistics['filters'][] = array(
2994 'title' => $field['title'],
2995 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2998 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2999 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3001 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3002 $statistics['filters'][] = array(
3003 'title' => $field['title'],
3004 'value' => $pair[$rel],
3009 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3012 $pair = $this->getOperationPair(
3013 CRM_Utils_Array
::value('operatorType', $field),
3016 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3017 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3018 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3019 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3020 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3022 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3023 $this->setEntityRefDefaults($field, $tableName);
3024 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3025 array('id' => $val) +
3026 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3028 foreach ($result['values'] as $v) {
3029 $values[] = $v['label'];
3031 $value = "{$pair[$op]} " . implode(', ', $values);
3033 elseif ($op == 'nll' ||
$op == 'nnll') {
3034 $value = $pair[$op];
3036 elseif (is_array($val) && (!empty($val))) {
3037 $options = CRM_Utils_Array
::value('options', $field, array());
3038 foreach ($val as $key => $valIds) {
3039 if (isset($options[$valIds])) {
3040 $val[$key] = $options[$valIds];
3043 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3044 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3045 $val = implode(', ', $val);
3046 $value = "{$pair[$op]} " . $val;
3048 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3049 isset($field['options']) &&
3050 is_array($field['options']) && !empty($field['options'])
3052 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3053 CRM_Utils_Array
::value($val, $field['options'], $val);
3056 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3060 $statistics['filters'][] = array(
3061 'title' => CRM_Utils_Array
::value('title', $field),
3072 * End post processing.
3074 * @param array|null $rows
3076 public function endPostProcess(&$rows = NULL) {
3077 $this->assign('report_class', get_class($this));
3078 if ($this->_storeResultSet
) {
3079 $this->_resultSet
= $rows;
3082 if ($this->_outputMode
== 'print' ||
3083 $this->_outputMode
== 'pdf' ||
3087 $content = $this->compileContent();
3088 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3092 if ($this->_sendmail
) {
3093 $config = CRM_Core_Config
::singleton();
3094 $attachments = array();
3096 if ($this->_outputMode
== 'csv') {
3098 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3099 ": {$url}</p>" . '<p>' .
3100 ts('The report is attached as a CSV file.') . '</p>' .
3101 $this->_formValues
['report_footer'];
3103 $csvFullFilename = $config->templateCompileDir
.
3104 CRM_Utils_File
::makeFileName('CiviReport.csv');
3105 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3106 file_put_contents($csvFullFilename, $csvContent);
3107 $attachments[] = array(
3108 'fullPath' => $csvFullFilename,
3109 'mime_type' => 'text/csv',
3110 'cleanName' => 'CiviReport.csv',
3113 if ($this->_outputMode
== 'pdf') {
3114 // generate PDF content
3115 $pdfFullFilename = $config->templateCompileDir
.
3116 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3117 file_put_contents($pdfFullFilename,
3118 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3119 TRUE, array('orientation' => 'landscape')
3122 // generate Email Content
3124 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3125 ": {$url}</p>" . '<p>' .
3126 ts('The report is attached as a PDF file.') . '</p>' .
3127 $this->_formValues
['report_footer'];
3129 $attachments[] = array(
3130 'fullPath' => $pdfFullFilename,
3131 'mime_type' => 'application/pdf',
3132 'cleanName' => 'CiviReport.pdf',
3136 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3137 $this->_outputMode
, $attachments
3140 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3143 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3147 elseif ($this->_outputMode
== 'print') {
3151 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3152 $config = CRM_Core_Config
::singleton();
3153 //get chart image name
3154 $chartImg = $this->_chartId
. '.png';
3155 //get image url path
3157 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3159 $uploadUrl .= $chartImg;
3160 //get image doc path to overwrite
3162 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3163 'openFlashChart/' . $chartImg;
3165 $chart = imagecreatefrompng($uploadUrl);
3166 //convert it into formatted png
3167 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3168 //overwrite with same image
3169 imagepng($chart, $uploadImg);
3171 imagedestroy($chart);
3173 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3175 CRM_Utils_System
::civiExit();
3177 elseif ($this->_outputMode
== 'csv') {
3178 CRM_Report_Utils_Report
::export2csv($this, $rows);
3180 elseif ($this->_outputMode
== 'group') {
3181 $group = $this->_params
['groups'];
3182 $this->add2group($group);
3187 * Set store result set indicator to TRUE.
3189 * @todo explain what this does
3191 public function storeResultSet() {
3192 $this->_storeResultSet
= TRUE;
3200 public function getResultSet() {
3201 return $this->_resultSet
;
3205 * Get the sql used to generate the report.
3209 public function getReportSql() {
3210 return $this->sqlArray
;
3214 * Use the form name to create the tpl file name.
3218 public function getTemplateFileName() {
3219 $defaultTpl = parent
::getTemplateFileName();
3220 $template = CRM_Core_Smarty
::singleton();
3221 if (!$template->template_exists($defaultTpl)) {
3222 $defaultTpl = 'CRM/Report/Form.tpl';
3228 * Compile the report content.
3230 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3234 public function compileContent() {
3235 $templateFile = $this->getHookedTemplateFileName();
3236 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3237 CRM_Core_Form
::$_template->fetch($templateFile) .
3238 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3243 * Post process function.
3245 public function postProcess() {
3246 // get ready with post process params
3247 $this->beginPostProcess();
3250 $sql = $this->buildQuery();
3252 // build array of result based on column headers. This method also allows
3253 // modifying column headers before using it to build result set i.e $rows.
3255 $this->buildRows($sql, $rows);
3257 // format result set.
3258 $this->formatDisplay($rows);
3260 // assign variables to templates
3261 $this->doTemplateAssignment($rows);
3263 // do print / pdf / instance stuff if needed
3264 $this->endPostProcess($rows);
3270 * @param int $rowCount
3274 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3275 // lets do the pager if in html mode
3276 $this->_limit
= NULL;
3278 // CRM-14115, over-ride row count if rowCount is specified in URL
3279 if ($this->_dashBoardRowCount
) {
3280 $rowCount = $this->_dashBoardRowCount
;
3282 if ($this->addPaging
) {
3283 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3285 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3287 // @todo all http vars should be extracted in the preProcess
3288 // - not randomly in the class
3289 if (!$pageId && !empty($_POST)) {
3290 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3291 $pageId = max((int) $_POST['crmPID_B'], 1);
3293 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3294 $pageId = max((int) $_POST['crmPID'], 1);
3296 unset($_POST['crmPID_B'], $_POST['crmPID']);
3299 $pageId = $pageId ?
$pageId : 1;
3300 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3301 $offset = ($pageId - 1) * $rowCount;
3303 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3304 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3306 $this->_limit
= " LIMIT $offset, $rowCount";
3307 return array($offset, $rowCount);
3309 if ($this->_limitValue
) {
3310 if ($this->_offsetValue
) {
3311 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3314 $this->_limit
= " LIMIT " . $this->_limitValue
;
3322 * @param int $rowCount
3324 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3325 // CRM-14115, over-ride row count if rowCount is specified in URL
3326 if ($this->_dashBoardRowCount
) {
3327 $rowCount = $this->_dashBoardRowCount
;
3330 if ($this->_limit
&& ($this->_limit
!= '')) {
3331 if (!$this->_rowsFound
) {
3332 $sql = "SELECT FOUND_ROWS();";
3333 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3336 'total' => $this->_rowsFound
,
3337 'rowCount' => $rowCount,
3338 'status' => ts('Records') . ' %%StatusMessage%%',
3339 'buttonBottom' => 'PagerBottomButton',
3340 'buttonTop' => 'PagerTopButton',
3342 if (!empty($this->controller
)) {
3343 // This happens when being called from the api Really we want the api to be able to
3344 // pass paging parameters, but at this stage just preventing test crashes.
3345 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3348 $pager = new CRM_Utils_Pager($params);
3349 $this->assign_by_ref('pager', $pager);
3350 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3355 * Build a group filter with contempt for large data sets.
3357 * This function has been retained as it takes time to migrate the reports over
3358 * to the new method which will not crash on large datasets.
3362 * @param string $field
3363 * @param mixed $value
3368 public function legacySlowGroupFilterClause($field, $value, $op) {
3369 $smartGroupQuery = "";
3371 $group = new CRM_Contact_DAO_Group();
3372 $group->is_active
= 1;
3374 $smartGroups = array();
3375 while ($group->fetch()) {
3376 if (in_array($group->id
, $this->_params
['gid_value']) &&
3377 $group->saved_search_id
3379 $smartGroups[] = $group->id
;
3383 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3385 $smartGroupQuery = '';
3386 if (!empty($smartGroups)) {
3387 $smartGroups = implode(',', $smartGroups);
3388 $smartGroupQuery = " UNION DISTINCT
3389 SELECT DISTINCT smartgroup_contact.contact_id
3390 FROM civicrm_group_contact_cache smartgroup_contact
3391 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3394 $sqlOp = $this->getSQLOperator($op);
3395 if (!is_array($value)) {
3396 $value = array($value);
3398 //include child groups if any
3399 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3401 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3403 $contactAlias = $this->_aliases
['civicrm_contact'];
3404 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3405 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3407 return " {$contactAlias}.id {$sqlOp} (
3408 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3409 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3410 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3411 {$smartGroupQuery} ) ";
3415 * Build where clause for groups.
3417 * @param string $field
3418 * @param mixed $value
3423 public function whereGroupClause($field, $value, $op) {
3424 if ($this->groupFilterNotOptimised
) {
3425 return $this->legacySlowGroupFilterClause($field, $value, $op);
3427 if ($op === 'notin') {
3428 return " group_temp_table.id IS NULL ";
3430 // We will have used an inner join instead.
3436 * Create a table of the contact ids included by the group filter.
3438 * This function is called by both the api (tests) and the UI.
3440 public function buildGroupTempTable() {
3441 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3444 $filteredGroups = (array) $this->_params
['gid_value'];
3446 $groups = civicrm_api3('Group', 'get', array(
3448 'id' => array('IN' => $filteredGroups),
3449 'saved_search_id' => array('>' => 0),
3452 $smartGroups = array_keys($groups['values']);
3455 SELECT group_contact.contact_id as id
3456 FROM civicrm_group_contact group_contact
3457 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3458 AND group_contact.status = 'Added' ";
3460 if (!empty($smartGroups)) {
3461 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3462 $smartGroups = implode(',', $smartGroups);
3465 SELECT smartgroup_contact.contact_id as id
3466 FROM civicrm_group_contact_cache smartgroup_contact
3467 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3470 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3471 $this->executeReportQuery("
3472 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3475 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3479 * Execute query and add it to the developer tab.
3481 * @param string $query
3482 * @param array $params
3484 * @return \CRM_Core_DAO|object
3486 protected function executeReportQuery($query, $params = array()) {
3487 $this->addToDeveloperTab($query);
3488 return CRM_Core_DAO
::executeQuery($query, $params);
3492 * Build where clause for tags.
3494 * @param string $field
3495 * @param mixed $value
3500 public function whereTagClause($field, $value, $op) {
3501 // not using left join in query because if any contact
3502 // belongs to more than one tag, results duplicate
3504 $sqlOp = $this->getSQLOperator($op);
3505 if (!is_array($value)) {
3506 $value = array($value);
3508 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3509 $entity_table = $this->_tagFilterTable
;
3510 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3511 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3512 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3513 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3517 * Generate membership organization clause.
3519 * @param mixed $value
3520 * @param string $op SQL Operator
3524 public function whereMembershipOrgClause($value, $op) {
3525 $sqlOp = $this->getSQLOperator($op);
3526 if (!is_array($value)) {
3527 $value = array($value);
3530 $tmp_membership_org_sql_list = implode(', ', $value);
3531 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3532 SELECT DISTINCT mem.contact_id
3533 FROM civicrm_membership mem
3534 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3535 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3536 WHERE mt.member_of_contact_id IN (" .
3537 $tmp_membership_org_sql_list . ")
3538 AND mt.is_active = '1'
3539 AND mem_status.is_current_member = '1'
3540 AND mem_status.is_active = '1' ) ";
3544 * Generate Membership Type SQL Clause.
3546 * @param mixed $value
3552 public function whereMembershipTypeClause($value, $op) {
3553 $sqlOp = $this->getSQLOperator($op);
3554 if (!is_array($value)) {
3555 $value = array($value);
3558 $tmp_membership_sql_list = implode(', ', $value);
3559 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3560 SELECT DISTINCT mem.contact_id
3561 FROM civicrm_membership mem
3562 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3563 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3564 WHERE mem.membership_type_id IN (" .
3565 $tmp_membership_sql_list . ")
3566 AND mt.is_active = '1'
3567 AND mem_status.is_current_member = '1'
3568 AND mem_status.is_active = '1' ) ";
3572 * Buld contact acl clause
3573 * @deprecated in favor of buildPermissionClause
3575 * @param string $tableAlias
3577 public function buildACLClause($tableAlias = 'contact_a') {
3578 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3582 * Build the permision clause for all entities in this report
3584 public function buildPermissionClause() {
3586 foreach ($this->selectedTables() as $tableName) {
3587 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3588 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3589 $tableAlias = $this->_columns
[$tableName]['alias'];
3590 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3591 foreach ($clauses as $field => $clause) {
3592 // Skip contact_id field if redundant
3593 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3594 $ret["$tableName.$field"] = $clause;
3599 // Override output from buildACLClause
3600 $this->_aclFrom
= NULL;
3601 $this->_aclWhere
= implode(' AND ', $ret);
3605 * Add custom data to the columns.
3607 * @param bool $addFields
3608 * @param array $permCustomGroupIds
3610 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3611 if (empty($this->_customGroupExtends
)) {
3614 if (!is_array($this->_customGroupExtends
)) {
3615 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3617 $customGroupWhere = '';
3618 if (!empty($permCustomGroupIds)) {
3619 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3623 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3624 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3625 FROM civicrm_custom_group cg
3626 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3627 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3629 cg.is_active = 1 AND
3630 cf.is_active = 1 AND
3631 cf.is_searchable = 1
3632 ORDER BY cg.weight, cf.weight";
3633 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3636 while ($customDAO->fetch()) {
3637 if ($customDAO->table_name
!= $curTable) {
3638 $curTable = $customDAO->table_name
;
3639 $curFields = $curFilters = array();
3642 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3643 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3644 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3645 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3647 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3648 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3649 $this->_columns
[$curTable][$colKey] = array();
3653 $fieldName = 'custom_' . $customDAO->cf_id
;
3656 // this makes aliasing work in favor
3657 $curFields[$fieldName] = array(
3658 'name' => $customDAO->column_name
,
3659 'title' => $customDAO->label
,
3660 'dataType' => $customDAO->data_type
,
3661 'htmlType' => $customDAO->html_type
,
3664 if ($this->_customGroupFilters
) {
3665 // this makes aliasing work in favor
3666 $curFilters[$fieldName] = array(
3667 'name' => $customDAO->column_name
,
3668 'title' => $customDAO->label
,
3669 'dataType' => $customDAO->data_type
,
3670 'htmlType' => $customDAO->html_type
,
3674 switch ($customDAO->data_type
) {
3677 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3678 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3679 // CRM-6946, show time part for datetime date fields
3680 if ($customDAO->time_format
) {
3681 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3686 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3687 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3688 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3692 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3693 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3697 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3698 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3699 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3703 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3704 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3708 case 'StateProvince':
3710 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3712 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3713 if ($options !== FALSE) {
3714 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3715 $curFilters[$fieldName]['options'] = $options;
3719 case 'ContactReference':
3720 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3721 $curFilters[$fieldName]['name'] = 'display_name';
3722 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3724 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3725 $curFields[$fieldName]['name'] = 'display_name';
3726 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3730 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3731 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3735 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3736 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3737 if ($options !== FALSE) {
3738 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3739 $curFilters[$fieldName]['options'] = $options;
3743 if (!array_key_exists('type', $curFields[$fieldName])) {
3744 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3748 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3750 if ($this->_customGroupFilters
) {
3751 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3753 if ($this->_customGroupGroupBy
) {
3754 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3760 * Build custom data from clause.
3762 * @param bool $joinsForFiltersOnly
3763 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3765 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3766 if (empty($this->_customGroupExtends
)) {
3769 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3770 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3771 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3772 $customTables = array();
3773 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3774 while ($customTablesDAO->fetch()) {
3775 $customTables[] = $customTablesDAO->table_name
;
3778 foreach ($this->_columns
as $table => $prop) {
3779 if (in_array($table, $customTables)) {
3780 $extendsTable = $mapper[$prop['extends']];
3781 // Check field is required for rendering the report.
3782 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3785 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3787 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3789 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3790 // handle for ContactReference
3791 if (array_key_exists('fields', $prop)) {
3792 foreach ($prop['fields'] as $fieldName => $field) {
3793 if (CRM_Utils_Array
::value('dataType', $field) ==
3796 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3798 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3807 * Check if the field is selected.
3809 * @param string $prop
3813 public function isFieldSelected($prop) {
3818 if (!empty($this->_params
['fields'])) {
3819 foreach (array_keys($prop['fields']) as $fieldAlias) {
3820 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3821 if ($customFieldId) {
3822 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3826 //might be survey response field.
3827 if (!empty($this->_params
['fields']['survey_response']) &&
3828 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3836 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3837 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3838 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3839 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3846 if (!empty($this->_params
['order_bys'])) {
3847 foreach (array_keys($prop['fields']) as $fieldAlias) {
3848 foreach ($this->_params
['order_bys'] as $orderBy) {
3849 if ($fieldAlias == $orderBy['column'] &&
3850 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3857 return $this->isFieldFiltered($prop);
3862 * Check if the field is used as a filter.
3864 * @param string $prop
3868 protected function isFieldFiltered($prop) {
3869 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3870 foreach ($prop['filters'] as $fieldAlias => $val) {
3879 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3880 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3881 ||
($attach != 'relative' &&
3882 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3888 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3889 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3900 * Check for empty order_by configurations and remove them.
3902 * Also set template to hide them.
3904 * @param array $formValues
3906 public function preProcessOrderBy(&$formValues) {
3907 // Object to show/hide form elements
3908 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3910 $_showHide->addShow('optionField_1');
3912 // Cycle through order_by options; skip any empty ones, and hide them as well
3915 if (!empty($formValues['order_bys'])) {
3916 foreach ($formValues['order_bys'] as $order_by) {
3917 if ($order_by['column'] && $order_by['column'] != '-') {
3918 $_showHide->addShow('optionField_' . $n);
3919 $orderBys[$n] = $order_by;
3924 for ($i = $n; $i <= 5; $i++
) {
3926 $_showHide->addHide('optionField_' . $i);
3930 // overwrite order_by options with modified values
3931 if (!empty($orderBys)) {
3932 $formValues['order_bys'] = $orderBys;
3935 $formValues['order_bys'] = array(1 => array('column' => '-'));
3938 // assign show/hide data to template
3939 $_showHide->addToTemplate();
3943 * Check if table name has columns in SELECT clause.
3945 * @param string $tableName
3946 * Name of table (index of $this->_columns array).
3950 public function isTableSelected($tableName) {
3951 return in_array($tableName, $this->selectedTables());
3955 * Check if table name has columns in WHERE or HAVING clause.
3957 * @param string $tableName
3958 * Name of table (index of $this->_columns array).
3962 public function isTableFiltered($tableName) {
3963 // Cause the array to be generated if not previously done.
3964 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3965 $this->selectedTables();
3967 return in_array($tableName, $this->filteredTables
);
3971 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3973 * If the array is unset it will be built.
3978 public function selectedTables() {
3979 if (!$this->_selectedTables
) {
3980 $orderByColumns = array();
3981 if (array_key_exists('order_bys', $this->_params
) &&
3982 is_array($this->_params
['order_bys'])
3984 foreach ($this->_params
['order_bys'] as $orderBy) {
3985 $orderByColumns[] = $orderBy['column'];
3989 foreach ($this->_columns
as $tableName => $table) {
3990 if (array_key_exists('fields', $table)) {
3991 foreach ($table['fields'] as $fieldName => $field) {
3992 if (!empty($field['required']) ||
3993 !empty($this->_params
['fields'][$fieldName])
3995 $this->_selectedTables
[] = $tableName;
4000 if (array_key_exists('order_bys', $table)) {
4001 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4002 if (in_array($orderByName, $orderByColumns)) {
4003 $this->_selectedTables
[] = $tableName;
4008 if (array_key_exists('filters', $table)) {
4009 foreach ($table['filters'] as $filterName => $filter) {
4010 if (!empty($this->_params
["{$filterName}_value"]) ||
4011 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4013 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4016 $this->_selectedTables
[] = $tableName;
4017 $this->filteredTables
[] = $tableName;
4024 return $this->_selectedTables
;
4028 * Add address fields.
4030 * @deprecated - use getAddressColumns which is a more accurate description
4031 * and also accepts an array of options rather than a long list
4033 * adding address fields to construct function in reports
4035 * @param bool $groupBy
4036 * Add GroupBy? Not appropriate for detail report.
4037 * @param bool $orderBy
4038 * Add GroupBy? Not appropriate for detail report.
4039 * @param bool $filters
4040 * @param array $defaults
4043 * address fields for construct clause
4045 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4046 $defaultAddressFields = array(
4047 'street_address' => ts('Street Address'),
4048 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4049 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4050 'street_number' => ts('Street Number'),
4051 'street_name' => ts('Street Name'),
4052 'street_unit' => ts('Street Unit'),
4053 'city' => ts('City'),
4054 'postal_code' => ts('Postal Code'),
4055 'postal_code_suffix' => ts('Postal Code Suffix'),
4056 'country_id' => ts('Country'),
4057 'state_province_id' => ts('State/Province'),
4058 'county_id' => ts('County'),
4060 $addressFields = array(
4061 'civicrm_address' => array(
4062 'dao' => 'CRM_Core_DAO_Address',
4064 'address_name' => array(
4065 'title' => ts('Address Name'),
4066 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4070 'grouping' => 'location-fields',
4073 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4074 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4075 'title' => $fieldLabel,
4076 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4080 $street_address_filters = $general_address_filters = array();
4082 // Address filter depends on whether street address parsing is enabled.
4084 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4087 if ($addressOptions['street_address_parsing']) {
4088 $street_address_filters = array(
4089 'street_number' => array(
4090 'title' => ts('Street Number'),
4091 'type' => CRM_Utils_Type
::T_INT
,
4092 'name' => 'street_number',
4094 'street_name' => array(
4095 'title' => ts('Street Name'),
4096 'name' => 'street_name',
4097 'type' => CRM_Utils_Type
::T_STRING
,
4102 $street_address_filters = array(
4103 'street_address' => array(
4104 'title' => ts('Street Address'),
4105 'type' => CRM_Utils_Type
::T_STRING
,
4106 'name' => 'street_address',
4110 $general_address_filters = array(
4111 'postal_code' => array(
4112 'title' => ts('Postal Code'),
4113 'type' => CRM_Utils_Type
::T_STRING
,
4114 'name' => 'postal_code',
4117 'title' => ts('City'),
4118 'type' => CRM_Utils_Type
::T_STRING
,
4121 'country_id' => array(
4122 'name' => 'country_id',
4123 'title' => ts('Country'),
4124 'type' => CRM_Utils_Type
::T_INT
,
4125 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4126 'options' => CRM_Core_PseudoConstant
::country(),
4128 'state_province_id' => array(
4129 'name' => 'state_province_id',
4130 'title' => ts('State/Province'),
4131 'type' => CRM_Utils_Type
::T_INT
,
4132 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4133 'options' => array(),
4135 'county_id' => array(
4136 'name' => 'county_id',
4137 'title' => ts('County'),
4138 'type' => CRM_Utils_Type
::T_INT
,
4139 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4140 'options' => array(),
4144 $addressFields['civicrm_address']['filters'] = array_merge(
4145 $street_address_filters,
4146 $general_address_filters);
4149 $addressFields['civicrm_address']['order_bys'] = array(
4150 'street_name' => array('title' => ts('Street Name')),
4151 'street_number' => array('title' => ts('Odd / Even Street Number')),
4152 'street_address' => NULL,
4154 'postal_code' => NULL,
4159 $addressFields['civicrm_address']['group_bys'] = array(
4160 'street_address' => NULL,
4162 'postal_code' => NULL,
4163 'state_province_id' => array(
4164 'title' => ts('State/Province'),
4166 'country_id' => array(
4167 'title' => ts('Country'),
4169 'county_id' => array(
4170 'title' => ts('County'),
4174 return $addressFields;
4178 * Do AlterDisplay processing on Address Fields.
4181 * @param array $rows
4182 * @param int $rowNum
4183 * @param string $baseUrl
4184 * @param string $linkText
4188 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4189 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4190 $entryFound = FALSE;
4192 if (array_key_exists('civicrm_address_country_id', $row)) {
4193 if ($value = $row['civicrm_address_country_id']) {
4194 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4196 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4197 "reset=1&force=1&{$criteriaQueryParams}&" .
4198 "country_id_op=in&country_id_value={$value}",
4199 $this->_absoluteUrl
, $this->_id
4201 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4202 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4203 array(1 => $linkText)
4210 if (array_key_exists('civicrm_address_county_id', $row)) {
4211 if ($value = $row['civicrm_address_county_id']) {
4212 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4214 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4215 "reset=1&force=1&{$criteriaQueryParams}&" .
4216 "county_id_op=in&county_id_value={$value}",
4217 $this->_absoluteUrl
, $this->_id
4219 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4220 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4221 array(1 => $linkText)
4227 // handle state province
4228 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4229 if ($value = $row['civicrm_address_state_province_id']) {
4230 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4232 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4233 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4234 $this->_absoluteUrl
, $this->_id
4236 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4237 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4238 array(1 => $linkText)
4249 * Do AlterDisplay processing on Address Fields.
4252 * @param array $rows
4253 * @param int $rowNum
4254 * @param string $baseUrl
4255 * @param string $linkText
4259 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4260 $entryFound = FALSE;
4261 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4262 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4263 $addLinks = array('gender_id' => 'Gender');
4264 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4265 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4266 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4267 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4268 $rowLabels = array();
4269 foreach ($rowValues as $rowValue) {
4271 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4274 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4275 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4276 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4282 $yesNoFields = array(
4283 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4285 foreach ($yesNoFields as $fieldName) {
4286 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4287 // Since these are essentially 'negative fields' it feels like it
4288 // makes sense to only highlight the exceptions hence no 'No'.
4289 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4297 * Adjusts dates passed in to YEAR() for fiscal year.
4299 * @param string $fieldName
4303 public function fiscalYearOffset($fieldName) {
4304 $config = CRM_Core_Config
::singleton();
4305 $fy = $config->fiscalYearStart
;
4306 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4307 ($fy['d'] == 1 && $fy['M'] == 1)
4309 return "YEAR( $fieldName )";
4311 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4312 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4316 * Add Address into From Table if required.
4318 public function addAddressFromClause() {
4319 // include address field if address column is to be included
4320 if ((isset($this->_addressField
) &&
4321 $this->_addressField
4323 $this->isTableSelected('civicrm_address')
4326 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4327 ON ({$this->_aliases['civicrm_contact']}.id =
4328 {$this->_aliases['civicrm_address']}.contact_id) AND
4329 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4334 * Add Phone into From Table if required.
4336 public function addPhoneFromClause() {
4337 // include address field if address column is to be included
4338 if ($this->isTableSelected('civicrm_phone')) {
4340 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4341 ON ({$this->_aliases['civicrm_contact']}.id =
4342 {$this->_aliases['civicrm_phone']}.contact_id) AND
4343 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4348 * Add Financial Transaction into From Table if required.
4350 public function addFinancialTrxnFromClause() {
4351 if ($this->isTableSelected('civicrm_financial_trxn')) {
4353 LEFT JOIN civicrm_entity_financial_trxn eftcc
4354 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4355 eftcc.entity_table = 'civicrm_contribution')
4356 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4357 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4362 * Get phone columns to add to array.
4364 * @param array $options
4365 * - prefix Prefix to add to table (in case of more than one instance of the table)
4366 * - prefix_label Label to give columns from this phone table instance
4369 * phone columns definition
4371 public function getPhoneColumns($options = array()) {
4372 $defaultOptions = array(
4374 'prefix_label' => '',
4377 $options = array_merge($defaultOptions, $options);
4380 $options['prefix'] . 'civicrm_phone' => array(
4381 'dao' => 'CRM_Core_DAO_Phone',
4383 $options['prefix'] . 'phone' => array(
4384 'title' => ts($options['prefix_label'] . 'Phone'),
4394 * Get address columns to add to array.
4396 * @param array $options
4397 * - prefix Prefix to add to table (in case of more than one instance of the table)
4398 * - prefix_label Label to give columns from this address table instance
4401 * address columns definition
4403 public function getAddressColumns($options = array()) {
4406 'prefix_label' => '',
4410 'defaults' => array(),
4412 return $this->addAddressFields(
4413 $options['group_by'],
4414 $options['order_by'],
4415 $options['filters'],
4416 $options['defaults']
4421 * Get a standard set of contact fields.
4425 public function getBasicContactFields() {
4427 'sort_name' => array(
4428 'title' => ts('Contact Name'),
4433 'no_display' => TRUE,
4436 'prefix_id' => array(
4437 'title' => ts('Contact Prefix'),
4439 'first_name' => array(
4440 'title' => ts('First Name'),
4442 'nick_name' => array(
4443 'title' => ts('Nick Name'),
4445 'middle_name' => array(
4446 'title' => ts('Middle Name'),
4448 'last_name' => array(
4449 'title' => ts('Last Name'),
4451 'suffix_id' => array(
4452 'title' => ts('Contact Suffix'),
4454 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4455 'email_greeting_display' => array('title' => ts('Email Greeting')),
4456 'addressee_display' => array('title' => ts('Addressee')),
4457 'contact_type' => array(
4458 'title' => ts('Contact Type'),
4460 'contact_sub_type' => array(
4461 'title' => ts('Contact Subtype'),
4463 'gender_id' => array(
4464 'title' => ts('Gender'),
4466 'birth_date' => array(
4467 'title' => ts('Birth Date'),
4470 'title' => ts('Age'),
4471 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4473 'job_title' => array(
4474 'title' => ts('Contact Job title'),
4476 'organization_name' => array(
4477 'title' => ts('Organization Name'),
4479 'external_identifier' => array(
4480 'title' => ts('Contact identifier from external system'),
4482 'do_not_email' => array(),
4483 'do_not_phone' => array(),
4484 'do_not_mail' => array(),
4485 'do_not_sms' => array(),
4486 'is_opt_out' => array(),
4487 'is_deceased' => array(),
4488 'preferred_language' => array(),
4493 * Get a standard set of contact filters.
4497 public function getBasicContactFilters() {
4499 'sort_name' => array(
4500 'title' => ts('Contact Name'),
4503 'title' => ts('Contact Source'),
4504 'type' => CRM_Utils_Type
::T_STRING
,
4507 'title' => ts('Contact ID'),
4508 'no_display' => TRUE,
4510 'gender_id' => array(
4511 'title' => ts('Gender'),
4512 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4513 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4515 'birth_date' => array(
4516 'title' => ts('Birth Date'),
4517 'operatorType' => CRM_Report_Form
::OP_DATE
,
4519 'contact_type' => array(
4520 'title' => ts('Contact Type'),
4522 'contact_sub_type' => array(
4523 'title' => ts('Contact Subtype'),
4525 'modified_date' => array(
4526 'title' => ts('Contact Modified'),
4527 'operatorType' => CRM_Report_Form
::OP_DATE
,
4528 'type' => CRM_Utils_Type
::T_DATE
,
4530 'is_deceased' => array(
4531 'title' => ts('Deceased'),
4532 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4535 'do_not_email' => array(
4536 'title' => ts('Do not email'),
4537 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4539 'do_not_phone' => array(
4540 'title' => ts('Do not phone'),
4541 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4543 'do_not_mail' => array(
4544 'title' => ts('Do not mail'),
4545 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4547 'do_not_sms' => array(
4548 'title' => ts('Do not SMS'),
4549 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4551 'is_opt_out' => array(
4552 'title' => ts('Do not bulk email'),
4553 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4555 'preferred_language' => array(
4556 'title' => ts('Preferred Language'),
4562 * Add contact to group.
4564 * @param int $groupID
4566 public function add2group($groupID) {
4567 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4568 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4569 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4570 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4571 $sql = str_replace('WITH ROLLUP', '', $sql);
4572 $dao = CRM_Core_DAO
::executeQuery($sql);
4574 $contact_ids = array();
4575 // Add resulting contacts to group
4576 while ($dao->fetch()) {
4577 if ($dao->addtogroup_contact_id
) {
4578 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4582 if (!empty($contact_ids)) {
4583 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4584 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4587 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4593 * Show charts on print screen.
4595 public static function uploadChartImage() {
4596 // upload strictly for '.png' images
4597 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4598 if (preg_match('/\.png$/', $name)) {
4600 // Get the RAW .png from the input.
4601 $httpRawPostData = file_get_contents("php://input");
4603 // prepare the directory
4604 $config = CRM_Core_Config
::singleton();
4606 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4608 if (!file_exists($defaultPath)) {
4609 mkdir($defaultPath, 0777, TRUE);
4612 // full path to the saved image including filename
4613 $destination = $defaultPath . $name;
4616 $jfh = fopen($destination, 'w') or die("can't open file");
4617 fwrite($jfh, $httpRawPostData);
4619 CRM_Utils_System
::civiExit();
4624 * Apply common settings to entityRef fields.
4626 * @param array $field
4627 * @param string $table
4629 private function setEntityRefDefaults(&$field, $table) {
4630 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4631 $field['attributes'] +
= array(
4632 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4634 'placeholder' => ts('- select -'),
4639 * Add link fields to the row.
4641 * Function adds the _link & _hover fields to the row.
4644 * @param string $baseUrl
4645 * @param string $linkText
4646 * @param string $value
4647 * @param string $fieldName
4648 * @param string $tablePrefix
4649 * @param string $fieldLabel
4653 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4654 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4655 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4656 "reset=1&force=1&{$criteriaQueryParams}&" .
4657 $fieldName . "_op=in&{$fieldName}_value={$value}",
4658 $this->_absoluteUrl
, $this->_id
4660 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4661 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4662 array(1 => $linkText, 2 => $fieldLabel)
4667 * Generate temporary table to hold all contributions with permissioned FTs.
4669 * @param object $query
4670 * @param string $alias
4671 * @param bool $return
4675 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4676 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4679 $financialTypes = NULL;
4680 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4681 if (empty($financialTypes)) {
4683 $liFTs = implode(',', array_keys(CRM_Contribute_PseudoConstant
::financialType()));
4686 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4688 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4690 $query->_aliases
['civicrm_line_item'] = $alias;
4693 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4695 if (empty($query->_where
)) {
4696 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4698 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4699 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp {$this->_databaseAttributes} AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4700 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4701 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4702 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4703 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4705 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4706 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4707 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4708 CRM_Core_DAO
::executeQuery($sql);
4710 $query->_aliases
['civicrm_line_item'] = $temp;
4712 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4716 $query->_from
.= $from;
4720 * Get label for show results buttons.
4724 public function getResultsLabel() {
4725 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4726 return $showResultsLabel;
4730 * Determine the output mode from the url or input.
4733 * - pdf : Render as pdf
4734 * - csv : Render as csv
4735 * - print : Render in print format
4736 * - save : save the report and display the new report
4737 * - copy : save the report as a new instance and display that.
4738 * - group : go to the add to group screen.
4740 * Potentially chart variations could also be included but the complexity
4741 * is that we might print a bar chart as a pdf.
4743 protected function setOutputMode() {
4744 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4747 CRM_Core_DAO
::$_nullObject,
4749 CRM_Utils_Array
::value('task', $this->_params
)
4751 // if contacts are added to group
4752 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4753 $this->_outputMode
= 'group';
4755 if (isset($this->_params
['task'])) {
4756 unset($this->_params
['task']);
4761 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4764 * @param $columnName
4766 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4767 // add new column with date value for the datetime field
4768 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4769 CRM_Core_DAO
::executeQuery($tempQuery);
4770 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4771 CRM_Core_DAO
::executeQuery($updateQuery);
4772 $this->_selectClauses
[] = "{$columnName}_date";
4773 $this->_select
.= ", {$columnName}_date";
4774 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4775 unset($this->_sections
["{$columnName}"]);
4776 $this->assign('sections', $this->_sections
);
4780 * Get an array of the columns that have been selected for display.
4784 public function getSelectColumns() {
4785 $selectColumns = array();
4786 foreach ($this->_columns
as $tableName => $table) {
4787 if (array_key_exists('fields', $table)) {
4788 foreach ($table['fields'] as $fieldName => $field) {
4789 if (!empty($field['required']) ||
4790 !empty($this->_params
['fields'][$fieldName])
4793 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4798 return $selectColumns;
4802 * Add location tables to the query if they are used for filtering.
4804 * This is for when we are running the query separately for filtering and retrieving display fields.
4806 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4807 if ($this->isTableFiltered('civicrm_email')) {
4809 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4810 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4811 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4813 if ($this->isTableFiltered('civicrm_phone')) {
4815 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4816 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4817 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4819 if ($this->isTableFiltered('civicrm_address')) {
4821 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4822 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4823 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4828 * Set the base table for the FROM clause.
4830 * Sets up the from clause, allowing for the possibility it might be a
4831 * temp table pre-filtered by groups if a group filter is in use.
4833 * @param string $baseTable
4834 * @param string $field
4835 * @param null $tableAlias
4837 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4839 $tableAlias = $this->_aliases
[$baseTable];
4841 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4842 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4843 $this->_from
.= " {$this->_aclFrom} ";
4847 * Join the temp table contacting contacts who are members of the filtered groups.
4849 * If we are using an IN filter we use an inner join, otherwise a left join.
4851 * @param string $baseTable
4852 * @param string $field
4853 * @param string $tableAlias
4855 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4856 if ($this->groupTempTable
) {
4857 if ($this->_params
['gid_op'] == 'in') {
4858 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4859 ON group_temp_table.id = $tableAlias.{$field} ";
4863 LEFT JOIN $this->groupTempTable group_temp_table
4864 ON $tableAlias.{$field} = group_temp_table.id ";
4870 * Get all labels for fields that are used in a group concat.
4872 * @param string $options
4873 * comma separated option values.
4874 * @param string $baoName
4875 * The BAO name for the field.
4876 * @param string $fieldName
4877 * The name of the field for which labels should be retrieved.
4881 public function getLabels($options, $baoName, $fieldName) {
4882 $types = explode(',', $options);
4884 foreach ($types as $value) {
4885 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
4887 return implode(', ', array_filter($labels));
4891 * Add statistics columns.
4893 * If a group by is in play then add columns for the statistics fields.
4895 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
4896 * column header field.
4898 * @param array $field
4899 * @param string $tableName
4900 * @param string $fieldName
4901 * @param array $select
4905 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
4906 foreach ($field['statistics'] as $stat => $label) {
4907 $alias = "{$tableName}_{$fieldName}_{$stat}";
4908 switch (strtolower($stat)) {
4911 $select[] = "$stat({$field['dbAlias']}) as $alias";
4912 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4913 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4914 $this->_statFields
[$label] = $alias;
4915 $this->_selectAliases
[] = $alias;
4919 $select[] = "COUNT({$field['dbAlias']}) as $alias";
4920 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4921 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4922 $this->_statFields
[$label] = $alias;
4923 $this->_selectAliases
[] = $alias;
4926 case 'count_distinct':
4927 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
4928 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4929 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4930 $this->_statFields
[$label] = $alias;
4931 $this->_selectAliases
[] = $alias;
4935 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
4936 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4937 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4938 $this->_statFields
[$label] = $alias;
4939 $this->_selectAliases
[] = $alias;
4947 * Add a basic field to the select clause.
4949 * @param string $tableName
4950 * @param string $fieldName
4951 * @param array $field
4952 * @param string $select
4955 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
4956 $alias = "{$tableName}_{$fieldName}";
4957 $select[] = "{$field['dbAlias']} as $alias";
4958 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
4959 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
4960 $this->_selectAliases
[] = $alias;