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) {
693 $this->setTableAlias($table, $tableName);
695 $expFields = array();
696 // higher preference to bao object
697 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
700 if (method_exists($daoOrBaoName, 'exportableFields')) {
701 $expFields = $daoOrBaoName::exportableFields();
704 $expFields = $daoOrBaoName::export();
708 $doNotCopy = array('required', 'default');
710 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
711 foreach ($fieldGroups as $fieldGrp) {
712 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
713 foreach ($table[$fieldGrp] as $fieldName => $field) {
714 // $name is the field name used to reference the BAO/DAO export fields array
715 $name = isset($field['name']) ?
$field['name'] : $fieldName;
717 // Sometimes the field name key in the BAO/DAO export fields array is
718 // different from the actual database field name.
719 // Unset $field['name'] so that actual database field name can be obtained
720 // from the BAO/DAO export fields array.
721 unset($field['name']);
723 if (array_key_exists($name, $expFields)) {
724 foreach ($doNotCopy as $dnc) {
725 // unset the values we don't want to be copied.
726 unset($expFields[$name][$dnc]);
729 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
732 foreach ($expFields[$name] as $property => $val) {
733 if (!array_key_exists($property, $field)) {
734 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
741 if (!empty($field['no_repeat'])) {
742 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
744 if (!empty($field['no_display'])) {
745 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
748 // set alias = table-name, unless already set
749 $alias = isset($field['alias']) ?
$field['alias'] : (
750 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
752 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
754 // set name = fieldName, unless already set
755 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
756 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
759 // set dbAlias = alias.name, unless already set
760 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
761 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
763 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
766 // a few auto fills for filters
767 if ($fieldGrp == 'filters') {
768 // fill operator types
769 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
770 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
771 case CRM_Utils_Type
::T_MONEY
:
772 case CRM_Utils_Type
::T_FLOAT
:
773 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
776 case CRM_Utils_Type
::T_INT
:
777 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
780 case CRM_Utils_Type
::T_DATE
:
781 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
784 case CRM_Utils_Type
::T_BOOLEAN
:
785 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
786 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
787 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
798 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
800 // with multiple options operator-type is generally multi-select
801 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
802 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
804 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
815 // copy filters to a separate handy variable
816 if (array_key_exists('filters', $table)) {
817 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
820 if (array_key_exists('group_bys', $table)) {
821 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
824 if (array_key_exists('fields', $table)) {
825 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
830 $this->setDefaultValues(FALSE);
833 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
834 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
835 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
836 CRM_Report_Utils_Get
::processChart($this->_defaults
);
839 $this->_formValues
= $this->_defaults
;
840 $this->postProcess();
845 * Set default values.
847 * @param bool $freeze
851 public function setDefaultValues($freeze = TRUE) {
852 $freezeGroup = array();
854 // FIXME: generalizing form field naming conventions would reduce
855 // Lots of lines below.
856 foreach ($this->_columns
as $tableName => $table) {
857 if (array_key_exists('fields', $table)) {
858 foreach ($table['fields'] as $fieldName => $field) {
859 if (empty($field['no_display'])) {
860 if (isset($field['required'])) {
862 $this->_defaults
['fields'][$fieldName] = 1;
865 // find element object, so that we could use quickform's freeze method
866 // for required elements
867 $obj = $this->getElementFromGroup("fields", $fieldName);
869 $freezeGroup[] = $obj;
873 elseif (isset($field['default'])) {
874 $this->_defaults
['fields'][$fieldName] = $field['default'];
880 if (array_key_exists('group_bys', $table)) {
881 foreach ($table['group_bys'] as $fieldName => $field) {
882 if (isset($field['default'])) {
883 if (!empty($field['frequency'])) {
884 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
886 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
890 if (array_key_exists('filters', $table)) {
891 foreach ($table['filters'] as $fieldName => $field) {
892 if (isset($field['default'])) {
893 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
895 if (is_array($field['default'])) {
896 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
897 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
898 $this->_defaults
["{$fieldName}_relative"] = 0;
901 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
905 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
906 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
907 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
909 $this->_defaults
["{$fieldName}_value"] = $field['default'];
912 //assign default value as "in" for multiselect
913 //operator, To freeze the select element
914 if (CRM_Utils_Array
::value('operatorType', $field) ==
915 CRM_Report_Form
::OP_MULTISELECT
917 $this->_defaults
["{$fieldName}_op"] = 'in';
919 if (CRM_Utils_Array
::value('operatorType', $field) ==
920 CRM_Report_Form
::OP_ENTITYREF
922 $this->_defaults
["{$fieldName}_op"] = 'in';
924 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
925 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
927 $this->_defaults
["{$fieldName}_op"] = 'mhas';
929 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
930 $this->_defaults
["{$fieldName}_op"] = $op;
936 empty($this->_formValues
['order_bys']) &&
937 (array_key_exists('order_bys', $table) &&
938 is_array($table['order_bys']))
940 if (!array_key_exists('order_bys', $this->_defaults
)) {
941 $this->_defaults
['order_bys'] = array();
943 foreach ($table['order_bys'] as $fieldName => $field) {
944 if (!empty($field['default']) ||
!empty($field['default_order']) ||
945 CRM_Utils_Array
::value('default_is_section', $field) ||
946 !empty($field['default_weight'])
949 'column' => $fieldName,
950 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
951 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
954 if (!empty($field['default_weight'])) {
955 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
958 array_unshift($this->_defaults
['order_bys'], $order_by);
964 foreach ($this->_options
as $fieldName => $field) {
965 if (isset($field['default'])) {
966 $this->_defaults
['options'][$fieldName] = $field['default'];
971 if (!empty($this->_submitValues
)) {
972 $this->preProcessOrderBy($this->_submitValues
);
975 $this->preProcessOrderBy($this->_defaults
);
978 // lets finish freezing task here itself
979 if (!empty($freezeGroup)) {
980 foreach ($freezeGroup as $elem) {
985 if ($this->_formValues
) {
986 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
989 if ($this->_instanceValues
) {
990 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
993 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
995 return $this->_defaults
;
999 * Get element from group.
1001 * @param string $group
1002 * @param string $grpFieldName
1006 public function getElementFromGroup($group, $grpFieldName) {
1007 $eleObj = $this->getElement($group);
1008 foreach ($eleObj->_elements
as $index => $obj) {
1009 if ($grpFieldName == $obj->_attributes
['name']) {
1017 * Setter for $_params.
1019 * @param array $params
1021 public function setParams($params) {
1022 $this->_params
= $params;
1028 * @param int $instanceID
1030 public function setID($instanceID) {
1031 $this->_id
= $instanceID;
1035 * Setter for $_force.
1037 * @param bool $isForce
1039 public function setForce($isForce) {
1040 $this->_force
= $isForce;
1044 * Setter for $_limitValue.
1046 * @param int $_limitValue
1048 public function setLimitValue($_limitValue) {
1049 $this->_limitValue
= $_limitValue;
1053 * Setter for $_offsetValue.
1055 * @param int $_offsetValue
1057 public function setOffsetValue($_offsetValue) {
1058 $this->_offsetValue
= $_offsetValue;
1062 * Setter for $addPaging.
1064 * @param bool $value
1066 public function setAddPaging($value) {
1067 $this->addPaging
= $value;
1071 * Getter for $_defaultValues.
1075 public function getDefaultValues() {
1076 return $this->_defaults
;
1080 * Add columns to report.
1082 public function addColumns() {
1085 foreach ($this->_columns
as $tableName => $table) {
1086 if (array_key_exists('fields', $table)) {
1087 foreach ($table['fields'] as $fieldName => $field) {
1089 if (empty($field['no_display'])) {
1090 foreach (array('table', 'field') as $var) {
1091 if (!empty($
{$var}['grouping'])) {
1092 if (!is_array($
{$var}['grouping'])) {
1093 $tableName = $
{$var}['grouping'];
1096 $tableName = array_keys($
{$var}['grouping']);
1097 $tableName = $tableName[0];
1098 $groupTitle = array_values($
{$var}['grouping']);
1099 $groupTitle = $groupTitle[0];
1104 if (!$groupTitle && isset($table['group_title'])) {
1105 $groupTitle = $table['group_title'];
1106 // Having a group_title is secret code for being a custom group
1107 // which cryptically translates to needing an accordion.
1108 // here we make that explicit.
1109 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1112 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1113 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1114 $colGroups[$tableName]['group_title'] = $groupTitle;
1116 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1122 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1123 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1125 if (!empty($colGroups)) {
1126 $this->tabs
['FieldSelection'] = array(
1127 'title' => ts('Columns'),
1128 'tpl' => 'FieldSelection',
1129 'div_label' => 'col-groups',
1132 // Note this assignment is only really required in buildForm. It is being 'over-called'
1133 // to reduce risk of being missed due to overridden functions.
1134 $this->assign('tabs', $this->tabs
);
1137 $this->assign('colGroups', $colGroups);
1141 * Add filters to report.
1143 public function addFilters() {
1144 $filters = $filterGroups = array();
1147 foreach ($this->_filters
as $table => $attributes) {
1148 if (isset($this->_columns
[$table]['group_title'])) {
1149 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1150 // which magically means to 'display in an accordian'
1151 // here we make this explicit.
1152 $filterGroups[$table] = array(
1153 'group_title' => $this->_columns
[$table]['group_title'],
1154 'use_accordian_for_field_selection' => TRUE,
1158 foreach ($attributes as $fieldName => $field) {
1159 // get ready with option value pair
1160 // @ 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
1162 $operations = $this->getOperationPair(
1163 CRM_Utils_Array
::value('operatorType', $field),
1166 $filters[$table][$fieldName] = $field;
1168 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1169 case CRM_Report_Form
::OP_MONTH
:
1170 if (!array_key_exists('options', $field) ||
1171 !is_array($field['options']) ||
empty($field['options'])
1173 // If there's no option list for this filter, define one.
1174 $field['options'] = array(
1176 2 => ts('February'),
1183 9 => ts('September'),
1184 10 => ts('October'),
1185 11 => ts('November'),
1186 12 => ts('December'),
1188 // Add this option list to this column _columns. This is
1189 // required so that filter statistics show properly.
1190 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1192 case CRM_Report_Form
::OP_MULTISELECT
:
1193 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1194 // assume a multi-select field
1195 if (!empty($field['options']) ||
1196 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1198 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1199 if (count($operations) <= 1) {
1202 if ($fieldName == 'state_province_id' ||
1203 $fieldName == 'county_id'
1205 $this->addChainSelect($fieldName . '_value', array(
1212 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1213 'style' => 'min-width:250px',
1214 'class' => 'crm-select2 huge',
1216 'placeholder' => ts('- select -'),
1222 case CRM_Report_Form
::OP_SELECT
:
1223 // assume a select field
1224 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1225 if (!empty($field['options'])) {
1226 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1230 case CRM_Report_Form
::OP_ENTITYREF
:
1231 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1232 $this->setEntityRefDefaults($field, $table);
1233 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1236 case CRM_Report_Form
::OP_DATE
:
1237 // build datetime fields
1238 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1242 case CRM_Report_Form
::OP_DATETIME
:
1243 // build datetime fields
1244 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1248 case CRM_Report_Form
::OP_INT
:
1249 case CRM_Report_Form
::OP_FLOAT
:
1250 // and a min value input box
1251 $this->add('text', "{$fieldName}_min", ts('Min'));
1252 // and a max value input box
1253 $this->add('text', "{$fieldName}_max", ts('Max'));
1255 // default type is string
1256 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1257 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1259 // we need text box for value input
1260 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1265 if (!empty($filters)) {
1266 $this->tabs
['Filters'] = array(
1267 'title' => ts('Filters'),
1269 'div_label' => 'set-filters',
1272 $this->assign('filters', $filters);
1273 $this->assign('filterGroups', $filterGroups);
1277 * Function to assign the tabs to the template in the correct order.
1279 * We want the tabs to wind up in this order (if not overridden).
1287 protected function assignTabs() {
1295 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1296 $order = array_merge($order, $this->tabs
);
1297 $this->assign('tabs', $order);
1301 * The intent is to add a tab for developers to view the sql.
1303 * Currently using dpm.
1305 * @param string $sql
1307 protected function addToDeveloperTab($sql) {
1308 if (!CRM_Core_Permission
::check('view report sql')) {
1311 $this->tabs
['Developer'] = array(
1312 'title' => ts('Developer'),
1313 'tpl' => 'Developer',
1314 'div_label' => 'set-developer',
1317 $this->assignTabs();
1318 $this->sqlArray
[] = $sql;
1319 foreach ($this->sqlArray
as $sql) {
1320 foreach (array('LEFT JOIN') as $term) {
1321 $sql = str_replace($term, '<br>  ' . $term, $sql);
1323 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1324 $sql = str_replace($term, '<br><br>' . $term, $sql);
1326 $this->sqlFormattedArray
[] = $sql;
1327 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1332 * Add options defined in $this->_options to the report.
1334 public function addOptions() {
1335 if (!empty($this->_options
)) {
1336 // FIXME: For now lets build all elements as checkboxes.
1337 // Once we clear with the format we can build elements based on type
1339 foreach ($this->_options
as $fieldName => $field) {
1342 if ($field['type'] == 'select') {
1343 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1345 elseif ($field['type'] == 'checkbox') {
1346 $options[$field['title']] = $fieldName;
1347 $this->addCheckBox($fieldName, NULL,
1349 NULL, NULL, NULL, $this->_fourColumnAttribute
1354 if (!empty($this->_options
) &&
1356 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1358 $this->tabs
['ReportOptions'] = array(
1359 'title' => ts('Display Options'),
1360 'tpl' => 'ReportOptions',
1361 'div_label' => 'other-options',
1364 $this->assign('otherOptions', $this->_options
);
1368 * Add chart options to the report.
1370 public function addChartOptions() {
1371 if (!empty($this->_charts
)) {
1372 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1373 $this->assign('charts', $this->_charts
);
1374 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1379 * Add group by options to the report.
1381 public function addGroupBys() {
1382 $options = $freqElements = array();
1384 foreach ($this->_columns
as $tableName => $table) {
1385 if (array_key_exists('group_bys', $table)) {
1386 foreach ($table['group_bys'] as $fieldName => $field) {
1387 if (!empty($field)) {
1388 $options[$field['title']] = $fieldName;
1389 if (!empty($field['frequency'])) {
1390 $freqElements[$field['title']] = $fieldName;
1396 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1397 NULL, NULL, NULL, $this->_fourColumnAttribute
1399 $this->assign('groupByElements', $options);
1400 if (!empty($options)) {
1401 $this->tabs
['GroupBy'] = array(
1402 'title' => ts('Grouping'),
1404 'div_label' => 'group-by-elements',
1408 foreach ($freqElements as $name) {
1409 $this->addElement('select', "group_bys_freq[$name]",
1410 ts('Frequency'), $this->_groupByDateFreq
1416 * Add data for order by tab.
1418 public function addOrderBys() {
1420 foreach ($this->_columns
as $tableName => $table) {
1422 // Report developer may define any column to order by; include these as order-by options.
1423 if (array_key_exists('order_bys', $table)) {
1424 foreach ($table['order_bys'] as $fieldName => $field) {
1425 if (!empty($field)) {
1426 $options[$fieldName] = $field['title'];
1431 // Add searchable custom fields as order-by options, if so requested
1432 // (These are already indexed, so allowing to order on them is cheap.)
1434 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1435 array_key_exists('extends', $table) && !empty($table['extends'])
1437 foreach ($table['fields'] as $fieldName => $field) {
1438 if (empty($field['no_display'])) {
1439 $options[$fieldName] = $field['title'];
1447 $this->assign('orderByOptions', $options);
1448 if (!empty($options)) {
1449 $this->tabs
['OrderBy'] = array(
1450 'title' => ts('Sorting'),
1452 'div_label' => 'order-by-elements',
1456 if (!empty($options)) {
1458 '-' => ' - none - ',
1460 for ($i = 1; $i <= 5; $i++
) {
1461 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1462 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1463 'ASC' => ts('Ascending'),
1464 'DESC' => ts('Descending'),
1466 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1467 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1473 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1475 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1476 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1479 public function buildInstanceAndButtons() {
1480 CRM_Report_Form_Instance
::buildForm($this);
1481 $this->_actionButtonName
= $this->getButtonName('submit');
1482 $this->addTaskMenu($this->getActions($this->_id
));
1484 $this->assign('instanceForm', $this->_instanceForm
);
1486 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1487 $permission = CRM_Core_Permission
::getPermission();
1488 if ($permission == CRM_Core_Permission
::EDIT
&&
1489 $this->_add2groupSupported
1491 $this->addElement('select', 'groups', ts('Group'),
1492 array('' => ts('Add Contacts to Group')) +
1493 CRM_Core_PseudoConstant
::nestedGroup(),
1494 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1496 $this->assign('group', TRUE);
1499 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1501 $this->addChartOptions();
1502 $showResultsLabel = $this->getResultsLabel();
1503 $this->addButtons(array(
1506 'name' => $showResultsLabel,
1507 'isDefault' => TRUE,
1514 * Has this form been submitted already?
1518 public function resultsDisplayed() {
1519 $buttonName = $this->controller
->getButtonName();
1520 return ($buttonName ||
$this->_outputMode
);
1524 * Get the actions for this report instance.
1526 * @param int $instanceId
1530 protected function getActions($instanceId) {
1531 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1532 if (empty($instanceId)) {
1533 $actions['report_instance.save'] = array(
1534 'title' => ts('Create Report'),
1536 'is_confirm' => TRUE,
1537 'confirm_title' => ts('Create Report'),
1538 'confirm_refresh_fields' => json_encode(array(
1539 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1540 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1546 if (!$this->_csvSupported
) {
1547 unset($actions['report_instance.csv']);
1554 * Main build form function.
1556 public function buildQuickForm() {
1557 $this->addColumns();
1559 $this->addFilters();
1561 $this->addOptions();
1563 $this->addGroupBys();
1565 $this->addOrderBys();
1567 $this->buildInstanceAndButtons();
1569 // Add form rule for report.
1570 if (is_callable(array(
1574 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1576 $this->assignTabs();
1580 * A form rule function for custom data.
1582 * The rule ensures that fields selected in group_by if any) should only be the ones
1583 * present in display/select fields criteria;
1584 * note: works if and only if any custom field selected in group_by.
1586 * @param array $fields
1587 * @param array $ignoreFields
1591 public function customDataFormRule($fields, $ignoreFields = array()) {
1593 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1594 !empty($fields['group_bys'])
1596 foreach ($this->_columns
as $tableName => $table) {
1597 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1598 substr($tableName, 0, 12) == 'custom_value') &&
1599 !empty($this->_columns
[$tableName]['fields'])
1601 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1602 if (array_key_exists($fieldName, $fields['group_bys']) &&
1603 !array_key_exists($fieldName, $fields['fields'])
1605 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1607 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1608 foreach ($fields['fields'] as $fld => $val) {
1609 if (!array_key_exists($fld, $fields['group_bys']) &&
1610 !in_array($fld, $ignoreFields)
1612 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1624 * Get operators to display on form.
1626 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1628 * @param string $type
1629 * @param string $fieldName
1633 public function getOperationPair($type = "string", $fieldName = NULL) {
1634 // FIXME: At some point we should move these key-val pairs
1635 // to option_group and option_value table.
1637 case CRM_Report_Form
::OP_INT
:
1638 case CRM_Report_Form
::OP_FLOAT
:
1641 'lte' => ts('Is less than or equal to'),
1642 'gte' => ts('Is greater than or equal to'),
1643 'bw' => ts('Is between'),
1644 'eq' => ts('Is equal to'),
1645 'lt' => ts('Is less than'),
1646 'gt' => ts('Is greater than'),
1647 'neq' => ts('Is not equal to'),
1648 'nbw' => ts('Is not between'),
1649 'nll' => ts('Is empty (Null)'),
1650 'nnll' => ts('Is not empty (Null)'),
1654 case CRM_Report_Form
::OP_SELECT
:
1656 'eq' => ts('Is equal to'),
1660 case CRM_Report_Form
::OP_MONTH
:
1661 case CRM_Report_Form
::OP_MULTISELECT
:
1662 case CRM_Report_Form
::OP_ENTITYREF
:
1665 'in' => ts('Is one of'),
1666 'notin' => ts('Is not one of'),
1670 case CRM_Report_Form
::OP_DATE
:
1673 'nll' => ts('Is empty (Null)'),
1674 'nnll' => ts('Is not empty (Null)'),
1678 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1679 // use this operator for the values, concatenated with separator. For e.g if
1680 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1682 'mhas' => ts('Is one of'),
1683 'mnot' => ts('Is not one of'),
1690 'has' => ts('Contains'),
1691 'sw' => ts('Starts with'),
1692 'ew' => ts('Ends with'),
1693 'nhas' => ts('Does not contain'),
1694 'eq' => ts('Is equal to'),
1695 'neq' => ts('Is not equal to'),
1696 'nll' => ts('Is empty (Null)'),
1697 'nnll' => ts('Is not empty (Null)'),
1704 * Build the tag filter field to display on the filters tab.
1706 public function buildTagFilter() {
1707 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1708 if (!empty($contactTags)) {
1709 $this->_columns
['civicrm_tag'] = array(
1710 'dao' => 'CRM_Core_DAO_Tag',
1714 'title' => ts('Tag'),
1715 'type' => CRM_Utils_Type
::T_INT
,
1717 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1718 'options' => $contactTags,
1726 * Adds group filters to _columns (called from _Construct).
1728 public function buildGroupFilter() {
1729 $this->_columns
['civicrm_group']['filters'] = array(
1731 'name' => 'group_id',
1732 'title' => ts('Group'),
1733 'type' => CRM_Utils_Type
::T_INT
,
1734 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1736 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1739 if (empty($this->_columns
['civicrm_group']['dao'])) {
1740 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1742 if (empty($this->_columns
['civicrm_group']['alias'])) {
1743 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1748 * Get SQL operator from form text version.
1750 * @param string $operator
1754 public function getSQLOperator($operator = "like") {
1755 switch ($operator) {
1788 return 'IS NOT NULL';
1797 * Generate where clause.
1799 * This can be overridden in reports for special treatment of a field
1801 * @param array $field Field specifications
1802 * @param string $op Query operator (not an exact match to sql)
1803 * @param mixed $value
1807 * @return null|string
1809 public function whereClause(&$field, $op, $value, $min, $max) {
1811 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1813 // CRM-18010: Ensure type of each report filters
1815 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1822 if (($min !== NULL && strlen($min) > 0) ||
1823 ($max !== NULL && strlen($max) > 0)
1827 $min = CRM_Utils_Type
::escape($min, $type);
1829 $clauses[] = "( {$field['dbAlias']} >= $min )";
1832 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1836 $max = CRM_Utils_Type
::escape($max, $type);
1838 $clauses[] = "( {$field['dbAlias']} <= $max )";
1841 $clauses[] = "( {$field['dbAlias']} > $max )";
1845 if (!empty($clauses)) {
1847 $clause = implode(' AND ', $clauses);
1850 $clause = '(' . implode('OR', $clauses) . ')';
1858 if ($value !== NULL && strlen($value) > 0) {
1859 $value = CRM_Utils_Type
::escape($value, $type);
1860 if (strpos($value, '%') === FALSE) {
1861 $value = "'%{$value}%'";
1864 $value = "'{$value}'";
1866 $sqlOP = $this->getSQLOperator($op);
1867 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1873 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1874 $value = explode(',', $value);
1876 if ($value !== NULL && is_array($value) && count($value) > 0) {
1877 $sqlOP = $this->getSQLOperator($op);
1878 if (CRM_Utils_Array
::value('type', $field) ==
1879 CRM_Utils_Type
::T_STRING
1881 //cycle through selections and escape values
1882 foreach ($value as $key => $selection) {
1883 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1886 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1890 // for numerical values
1891 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1894 if ($op == 'notin') {
1895 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1898 $clause = "( " . $clause . " )";
1905 // multiple has or multiple not
1906 if ($value !== NULL && count($value) > 0) {
1907 $value = CRM_Utils_Type
::escapeAll($value, $type);
1908 $operator = $op == 'mnot' ?
'NOT' : '';
1909 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1910 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1916 if ($value !== NULL && strlen($value) > 0) {
1917 $value = CRM_Utils_Type
::escape($value, $type);
1918 if (strpos($value, '%') === FALSE) {
1920 $value = "'{$value}%'";
1923 $value = "'%{$value}'";
1927 $value = "'{$value}'";
1929 $sqlOP = $this->getSQLOperator($op);
1930 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1936 $sqlOP = $this->getSQLOperator($op);
1937 $clause = "( {$field['dbAlias']} $sqlOP )";
1943 //CRM-18457: some custom field passes value in array format against binary operator
1944 if (is_array($value) && count($value)) {
1949 if ($value !== NULL && $value !== '') {
1950 if (isset($field['clause'])) {
1951 // FIXME: we not doing escape here. Better solution is to use two
1952 // different types - data-type and filter-type
1953 $clause = $field['clause'];
1955 elseif (!is_array($value)) {
1956 $value = CRM_Utils_Type
::escape($value, $type);
1957 $sqlOP = $this->getSQLOperator($op);
1958 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1959 $value = "'{$value}'";
1961 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1967 if (!empty($field['group']) && $clause) {
1968 $clause = $this->whereGroupClause($field, $value, $op);
1970 elseif (!empty($field['tag']) && $clause) {
1971 // not using left join in query because if any contact
1972 // belongs to more than one tag, results duplicate
1974 $clause = $this->whereTagClause($field, $value, $op);
1976 elseif (!empty($field['membership_org']) && $clause) {
1977 $clause = $this->whereMembershipOrgClause($value, $op);
1979 elseif (!empty($field['membership_type']) && $clause) {
1980 $clause = $this->whereMembershipTypeClause($value, $op);
1986 * Get SQL where clause for a date field.
1988 * @param string $fieldName
1989 * @param string $relative
1990 * @param string $from
1992 * @param string $type
1993 * @param string $fromTime
1994 * @param string $toTime
1996 * @return null|string
1998 public function dateClause(
2000 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2003 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2004 $sqlOP = $this->getSQLOperator($relative);
2005 return "( {$fieldName} {$sqlOP} )";
2008 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2011 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2012 $clauses[] = "( {$fieldName} >= $from )";
2016 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2017 $clauses[] = "( {$fieldName} <= {$to} )";
2020 if (!empty($clauses)) {
2021 return implode(' AND ', $clauses);
2028 * Get values for from and to for date ranges.
2030 * @param bool $relative
2031 * @param string $from
2033 * @param string $fromTime
2034 * @param string $toTime
2038 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2039 if (empty($toTime)) {
2042 //FIX ME not working for relative
2044 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2045 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2046 $from = substr($dateRange['from'], 0, 8);
2047 //Take only Date Part, Sometime Time part is also present in 'to'
2048 $to = substr($dateRange['to'], 0, 8);
2050 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2051 $to = CRM_Utils_Date
::processDate($to, $toTime);
2052 return array($from, $to);
2056 * Alter display of rows.
2058 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2059 * such as rendering contacts as links.
2061 * @param array $rows
2062 * Rows generated by SQL, with an array for each row.
2064 public function alterDisplay(&$rows) {
2068 * Alter the way in which custom data fields are displayed.
2070 * @param array $rows
2072 public function alterCustomDataDisplay(&$rows) {
2073 // custom code to alter rows having custom values
2074 if (empty($this->_customGroupExtends
)) {
2078 $customFields = array();
2079 $customFieldIds = array();
2080 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2081 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2082 $customFieldIds[$fieldAlias] = $fieldId;
2085 if (empty($customFieldIds)) {
2089 // skip for type date and ContactReference since date format is already handled
2091 SELECT cg.table_name, cf.id
2092 FROM civicrm_custom_field cf
2093 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2094 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2095 cg.is_active = 1 AND
2096 cf.is_active = 1 AND
2097 cf.is_searchable = 1 AND
2098 cf.data_type NOT IN ('ContactReference', 'Date') AND
2099 cf.id IN (" . implode(",", $customFieldIds) . ")";
2101 $dao = CRM_Core_DAO
::executeQuery($query);
2102 while ($dao->fetch()) {
2103 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2107 $entryFound = FALSE;
2108 foreach ($rows as $rowNum => $row) {
2109 foreach ($row as $tableCol => $val) {
2110 if (array_key_exists($tableCol, $customFields)) {
2111 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2116 // skip looking further in rows, if first row itself doesn't
2117 // have the column we need
2125 * Remove duplicate rows.
2127 * @param array $rows
2129 public function removeDuplicates(&$rows) {
2130 if (empty($this->_noRepeats
)) {
2133 $checkList = array();
2135 foreach ($rows as $key => $list) {
2136 foreach ($list as $colName => $colVal) {
2137 if (array_key_exists($colName, $checkList) &&
2138 $checkList[$colName] == $colVal
2140 $rows[$key][$colName] = "";
2142 if (in_array($colName, $this->_noRepeats
)) {
2143 $checkList[$colName] = $colVal;
2150 * Fix subtotal display.
2153 * @param array $fields
2154 * @param bool $subtotal
2156 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2157 foreach ($row as $colName => $colVal) {
2158 if (in_array($colName, $fields)) {
2160 elseif (isset($this->_columnHeaders
[$colName])) {
2162 $row[$colName] = 'Subtotal';
2166 unset($row[$colName]);
2173 * Calculate grant total.
2175 * @param array $rows
2179 public function grandTotal(&$rows) {
2180 if (!$this->_rollup ||
count($rows) == 1) {
2184 $this->moveSummaryColumnsToTheRightHandSide();
2186 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2190 $this->rollupRow
= array_pop($rows);
2192 foreach ($this->_columnHeaders
as $fld => $val) {
2193 if (!in_array($fld, $this->_statFields
)) {
2194 if (!$this->_grandFlag
) {
2195 $this->rollupRow
[$fld] = ts('Grand Total');
2196 $this->_grandFlag
= TRUE;
2199 $this->rollupRow
[$fld] = "";
2204 $this->assign('grandStat', $this->rollupRow
);
2209 * Format display output.
2211 * @param array $rows
2212 * @param bool $pager
2214 public function formatDisplay(&$rows, $pager = TRUE) {
2215 // set pager based on if any limit was applied in the query.
2220 // allow building charts if any
2221 if (!empty($this->_params
['charts']) && !empty($rows)) {
2222 $this->buildChart($rows);
2223 $this->assign('chartEnabled', TRUE);
2224 $this->_chartId
= "{$this->_params['charts']}_" .
2225 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2227 $this->assign('chartId', $this->_chartId
);
2230 // unset columns not to be displayed.
2231 foreach ($this->_columnHeaders
as $key => $value) {
2232 if (!empty($value['no_display'])) {
2233 unset($this->_columnHeaders
[$key]);
2237 // unset columns not to be displayed.
2238 if (!empty($rows)) {
2239 foreach ($this->_noDisplay
as $noDisplayField) {
2240 foreach ($rows as $rowNum => $row) {
2241 unset($this->_columnHeaders
[$noDisplayField]);
2246 // build array of section totals
2247 $this->sectionTotals();
2249 // process grand-total row
2250 $this->grandTotal($rows);
2252 // use this method for formatting rows for display purpose.
2253 $this->alterDisplay($rows);
2254 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2256 // use this method for formatting custom rows for display purpose.
2257 $this->alterCustomDataDisplay($rows);
2263 * @param array $rows
2265 public function buildChart(&$rows) {
2266 // override this method for building charts.
2269 // select() method below has been added recently (v3.3), and many of the report templates might
2270 // still be having their own select() method. We should fix them as and when encountered and move
2271 // towards generalizing the select() method below.
2274 * Generate the SELECT clause and set class variable $_select.
2276 public function select() {
2277 $select = $this->_selectAliases
= array();
2279 foreach ($this->_columns
as $tableName => $table) {
2280 if (array_key_exists('fields', $table)) {
2281 foreach ($table['fields'] as $fieldName => $field) {
2282 if ($tableName == 'civicrm_address') {
2283 // deprecated, use $this->isTableSelected.
2284 $this->_addressField
= TRUE;
2286 if ($tableName == 'civicrm_email') {
2287 $this->_emailField
= TRUE;
2289 if ($tableName == 'civicrm_phone') {
2290 $this->_phoneField
= TRUE;
2293 if (!empty($field['required']) ||
2294 !empty($this->_params
['fields'][$fieldName])
2297 // 1. In many cases we want select clause to be built in slightly different way
2298 // for a particular field of a particular type.
2299 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2301 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2302 if ($selectClause) {
2303 $select[] = $selectClause;
2307 // include statistics columns only if set
2308 if (!empty($field['statistics'])) {
2309 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2312 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2318 // select for group bys
2319 if (array_key_exists('group_bys', $table)) {
2320 foreach ($table['group_bys'] as $fieldName => $field) {
2322 if ($tableName == 'civicrm_address') {
2323 $this->_addressField
= TRUE;
2325 if ($tableName == 'civicrm_email') {
2326 $this->_emailField
= TRUE;
2328 if ($tableName == 'civicrm_phone') {
2329 $this->_phoneField
= TRUE;
2331 // 1. In many cases we want select clause to be built in slightly different way
2332 // for a particular field of a particular type.
2333 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2335 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2336 if ($selectClause) {
2337 $select[] = $selectClause;
2341 if (!empty($this->_params
['group_bys']) &&
2342 !empty($this->_params
['group_bys'][$fieldName]) &&
2343 !empty($this->_params
['group_bys_freq'])
2345 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2347 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2348 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2349 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2350 $field['title'] = 'Week';
2354 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2355 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2356 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2357 $field['title'] = 'Year';
2361 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2362 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2363 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2364 $field['title'] = 'Month';
2368 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2369 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2370 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2371 $field['title'] = 'Quarter';
2374 // for graphs and charts -
2375 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2376 $this->_interval
= $field['title'];
2377 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2378 = $field['title'] . ' Beginning';
2379 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2380 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2382 // just to make sure these values are transferred to rows.
2383 // since we 'll need them for calculation purpose,
2384 // e.g making subtotals look nicer or graphs
2385 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2386 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2393 $this->_selectClauses
= $select;
2394 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2398 * Build select clause for a single field.
2400 * @param string $tableName
2401 * @param string $tableKey
2402 * @param string $fieldName
2403 * @param string $field
2407 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2412 * Build where clause.
2414 public function where() {
2415 $this->storeWhereHavingClauseArray();
2417 if (empty($this->_whereClauses
)) {
2418 $this->_where
= "WHERE ( 1 ) ";
2419 $this->_having
= "";
2422 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2425 if ($this->_aclWhere
) {
2426 $this->_where
.= " AND {$this->_aclWhere} ";
2429 if (!empty($this->_havingClauses
)) {
2430 // use this clause to construct group by clause.
2431 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2436 * Store Where clauses into an array.
2438 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2439 * temp table that may not be part of the final where clause or added
2440 * in other functions
2442 public function storeWhereHavingClauseArray() {
2443 foreach ($this->_columns
as $tableName => $table) {
2444 if (array_key_exists('filters', $table)) {
2445 foreach ($table['filters'] as $fieldName => $field) {
2446 // respect pseudofield to filter spec so fields can be marked as
2447 // not to be handled here
2448 if (!empty($field['pseudofield'])) {
2452 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2453 if (CRM_Utils_Array
::value('operatorType', $field) ==
2454 CRM_Report_Form
::OP_MONTH
2456 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2457 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2458 if (is_array($value) && !empty($value)) {
2460 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2465 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2466 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2467 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2468 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2469 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2470 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2474 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2476 $clause = $this->whereClause($field,
2478 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2479 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2480 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2485 if (!empty($clause)) {
2486 if (!empty($field['having'])) {
2487 $this->_havingClauses
[] = $clause;
2490 $this->_whereClauses
[] = $clause;
2502 public function processReportMode() {
2503 $this->setOutputMode();
2506 = CRM_Utils_Request
::retrieve(
2509 CRM_Core_DAO
::$_nullObject
2512 $this->_absoluteUrl
= FALSE;
2514 $this->assign('printOnly', FALSE);
2516 if ($this->_outputMode
== 'print' ||
2517 ($this->_sendmail
&& !$this->_outputMode
)
2519 $this->assign('printOnly', TRUE);
2521 $this->addPaging
= FALSE;
2522 $this->assign('outputMode', 'print');
2523 $this->_outputMode
= 'print';
2524 if ($this->_sendmail
) {
2525 $this->_absoluteUrl
= TRUE;
2528 elseif ($this->_outputMode
== 'pdf') {
2530 $this->addPaging
= FALSE;
2531 $this->_absoluteUrl
= TRUE;
2533 elseif ($this->_outputMode
== 'csv') {
2535 $this->_absoluteUrl
= TRUE;
2536 $this->addPaging
= FALSE;
2538 elseif ($this->_outputMode
== 'group') {
2539 $this->assign('outputMode', 'group');
2541 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2542 $this->assign('outputMode', 'create_report');
2544 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2545 $this->_createNew
= TRUE;
2548 $this->assign('outputMode', $this->_outputMode
);
2549 $this->assign('printOnly', $printOnly);
2550 // Get today's date to include in printed reports
2552 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2553 $this->assign('reportDate', $reportDate);
2558 * Post Processing function for Form.
2560 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2561 * This function is not accessed when the api calls the report.
2563 public function beginPostProcess() {
2564 $this->setParams($this->controller
->exportValues($this->_name
));
2565 if (empty($this->_params
) &&
2568 $this->setParams($this->_formValues
);
2571 // hack to fix params when submitted from dashboard, CRM-8532
2572 // fields array is missing because form building etc is skipped
2573 // in dashboard mode for report
2574 //@todo - this could be done in the dashboard no we have a setter
2575 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2576 $this->setParams($this->_formValues
);
2579 $this->processReportMode();
2581 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2582 $this->_createNew
= ($this->_outputMode
== 'copy');
2583 CRM_Report_Form_Instance
::postProcess($this);
2585 if ($this->_outputMode
== 'delete') {
2586 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2589 $this->_formValues
= $this->_params
;
2591 $this->beginPostProcessCommon();
2595 * BeginPostProcess function run in both report mode and non-report mode (api).
2597 public function beginPostProcessCommon() {
2601 * Build the report query.
2603 * @param bool $applyLimit
2607 public function buildQuery($applyLimit = TRUE) {
2608 $this->buildGroupTempTable();
2611 $this->customDataFrom();
2612 $this->buildPermissionClause();
2614 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2615 $this->getPermissionedFTQuery($this);
2620 // order_by columns not selected for display need to be included in SELECT
2621 $unselectedSectionColumns = $this->unselectedSectionColumns();
2622 foreach ($unselectedSectionColumns as $alias => $section) {
2623 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2626 if ($applyLimit && empty($this->_params
['charts'])) {
2629 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2631 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2632 $this->addToDeveloperTab($sql);
2637 * Build group by clause.
2639 public function groupBy() {
2640 $groupBys = array();
2641 if (!empty($this->_params
['group_bys']) &&
2642 is_array($this->_params
['group_bys'])
2644 foreach ($this->_columns
as $tableName => $table) {
2645 if (array_key_exists('group_bys', $table)) {
2646 foreach ($table['group_bys'] as $fieldName => $field) {
2647 if (!empty($this->_params
['group_bys'][$fieldName])) {
2648 $groupBys[] = $field['dbAlias'];
2655 if (!empty($groupBys)) {
2656 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBys);
2661 * Build order by clause.
2663 public function orderBy() {
2664 $this->_orderBy
= "";
2665 $this->_sections
= array();
2666 $this->storeOrderByArray();
2667 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2668 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2670 $this->assign('sections', $this->_sections
);
2674 * Extract order by fields and store as an array.
2676 * In some cases other functions want to know which fields are selected for ordering by
2677 * Separating this into a separate function allows it to be called separately from constructing
2678 * the order by clause
2680 public function storeOrderByArray() {
2681 $orderBys = array();
2683 if (!empty($this->_params
['order_bys']) &&
2684 is_array($this->_params
['order_bys']) &&
2685 !empty($this->_params
['order_bys'])
2688 // Process order_bys in user-specified order
2689 foreach ($this->_params
['order_bys'] as $orderBy) {
2690 $orderByField = array();
2691 foreach ($this->_columns
as $tableName => $table) {
2692 if (array_key_exists('order_bys', $table)) {
2693 // For DAO columns defined in $this->_columns
2694 $fields = $table['order_bys'];
2696 elseif (array_key_exists('extends', $table)) {
2697 // For custom fields referenced in $this->_customGroupExtends
2698 $fields = CRM_Utils_Array
::value('fields', $table, array());
2703 if (!empty($fields) && is_array($fields)) {
2704 foreach ($fields as $fieldName => $field) {
2705 if ($fieldName == $orderBy['column']) {
2706 $orderByField = array_merge($field, $orderBy);
2707 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2714 if (!empty($orderByField)) {
2715 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2716 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2718 // Record any section headers for assignment to the template
2719 if (!empty($orderBy['section'])) {
2720 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2721 $this->_sections
[$orderByField['tplField']] = $orderByField;
2727 $this->_orderByArray
= $orderBys;
2729 $this->assign('sections', $this->_sections
);
2733 * Determine unselected columns.
2737 public function unselectedSectionColumns() {
2738 if (is_array($this->_sections
)) {
2739 return array_diff_key($this->_sections
, $this->getSelectColumns());
2747 * Build output rows.
2749 * @param string $sql
2750 * @param array $rows
2752 public function buildRows($sql, &$rows) {
2753 $dao = CRM_Core_DAO
::executeQuery($sql);
2754 if (!is_array($rows)) {
2758 // use this method to modify $this->_columnHeaders
2759 $this->modifyColumnHeaders();
2761 $unselectedSectionColumns = $this->unselectedSectionColumns();
2763 while ($dao->fetch()) {
2765 foreach ($this->_columnHeaders
as $key => $value) {
2766 if (property_exists($dao, $key)) {
2767 $row[$key] = $dao->$key;
2771 // section headers not selected for display need to be added to row
2772 foreach ($unselectedSectionColumns as $key => $values) {
2773 if (property_exists($dao, $key)) {
2774 $row[$key] = $dao->$key;
2783 * Calculate section totals.
2785 * When "order by" fields are marked as sections, this assigns to the template
2786 * an array of total counts for each section. This data is used by the Smarty
2787 * plugin {sectionTotal}.
2789 public function sectionTotals() {
2791 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2792 if (empty($this->_selectAliases
)) {
2796 if (!empty($this->_sections
)) {
2797 // build the query with no LIMIT clause
2798 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2799 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2801 // pull section aliases out of $this->_sections
2802 $sectionAliases = array_keys($this->_sections
);
2805 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2806 $ifnulls[] = "ifnull($alias, '') as $alias";
2808 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2809 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2811 // Group (un-limited) report by all aliases and get counts. This might
2812 // be done more efficiently when the contents of $sql are known, ie. by
2813 // overriding this method in the report class.
2815 $query = $this->_select
.
2816 ", count(*) as ct from ($sql) as subquery group by " .
2817 implode(", ", $sectionAliases);
2819 // initialize array of total counts
2821 $dao = CRM_Core_DAO
::executeQuery($query);
2822 while ($dao->fetch()) {
2824 // let $this->_alterDisplay translate any integer ids to human-readable values.
2825 $rows[0] = $dao->toArray();
2826 $this->alterDisplay($rows);
2829 // add totals for all permutations of section values
2832 $aliasCount = count($sectionAliases);
2833 foreach ($sectionAliases as $alias) {
2834 $values[] = $row[$alias];
2835 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2836 if ($i == $aliasCount) {
2837 // the last alias is the lowest-level section header; use count as-is
2838 $totals[$key] = $dao->ct
;
2841 // other aliases are higher level; roll count into their total
2842 $totals[$key] +
= $dao->ct
;
2846 $this->assign('sectionTotals', $totals);
2851 * Modify column headers.
2853 public function modifyColumnHeaders() {
2854 // use this method to modify $this->_columnHeaders
2858 * Move totals columns to the right edge of the table.
2860 * It seems like a more logical layout to have any totals columns on the far right regardless of
2861 * the location of the rest of their table.
2863 public function moveSummaryColumnsToTheRightHandSide() {
2864 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2865 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2869 * Assign rows to the template.
2871 * @param array $rows
2873 public function doTemplateAssignment(&$rows) {
2874 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2875 $this->assign_by_ref('rows', $rows);
2876 $this->assign('statistics', $this->statistics($rows));
2880 * Build report statistics.
2882 * Override this method to build your own statistics.
2884 * @param array $rows
2888 public function statistics(&$rows) {
2889 $statistics = array();
2891 $count = count($rows);
2892 // Why do we increment the count for rollup seems to artificially inflate the count.
2893 // It seems perhaps intentional to include the summary row in the count of results - although
2894 // this just seems odd.
2895 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2899 $this->countStat($statistics, $count);
2901 $this->groupByStat($statistics);
2903 $this->filterStat($statistics);
2909 * Add count statistics.
2911 * @param array $statistics
2914 public function countStat(&$statistics, $count) {
2915 $statistics['counts']['rowCount'] = array(
2916 'title' => ts('Row(s) Listed'),
2920 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2921 $statistics['counts']['rowsFound'] = array(
2922 'title' => ts('Total Row(s)'),
2923 'value' => $this->_rowsFound
,
2929 * Add group by statistics.
2931 * @param array $statistics
2933 public function groupByStat(&$statistics) {
2934 if (!empty($this->_params
['group_bys']) &&
2935 is_array($this->_params
['group_bys']) &&
2936 !empty($this->_params
['group_bys'])
2938 foreach ($this->_columns
as $tableName => $table) {
2939 if (array_key_exists('group_bys', $table)) {
2940 foreach ($table['group_bys'] as $fieldName => $field) {
2941 if (!empty($this->_params
['group_bys'][$fieldName])) {
2942 $combinations[] = $field['title'];
2947 $statistics['groups'][] = array(
2948 'title' => ts('Grouping(s)'),
2949 'value' => implode(' & ', $combinations),
2955 * Filter statistics.
2957 * @param array $statistics
2959 public function filterStat(&$statistics) {
2960 foreach ($this->_columns
as $tableName => $table) {
2961 if (array_key_exists('filters', $table)) {
2962 foreach ($table['filters'] as $fieldName => $field) {
2963 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2964 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2965 CRM_Utils_Array
::value('operatorType', $field) !=
2966 CRM_Report_Form
::OP_MONTH
2970 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2971 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2972 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2973 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2974 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2976 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2977 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2979 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2980 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2983 $statistics['filters'][] = array(
2984 'title' => $field['title'],
2985 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2988 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2989 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2991 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2992 $statistics['filters'][] = array(
2993 'title' => $field['title'],
2994 'value' => $pair[$rel],
2999 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3002 $pair = $this->getOperationPair(
3003 CRM_Utils_Array
::value('operatorType', $field),
3006 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3007 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3008 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3009 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3010 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3012 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3013 $this->setEntityRefDefaults($field, $tableName);
3014 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3015 array('id' => $val) +
3016 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3018 foreach ($result['values'] as $v) {
3019 $values[] = $v['label'];
3021 $value = "{$pair[$op]} " . implode(', ', $values);
3023 elseif ($op == 'nll' ||
$op == 'nnll') {
3024 $value = $pair[$op];
3026 elseif (is_array($val) && (!empty($val))) {
3027 $options = CRM_Utils_Array
::value('options', $field, array());
3028 foreach ($val as $key => $valIds) {
3029 if (isset($options[$valIds])) {
3030 $val[$key] = $options[$valIds];
3033 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3034 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3035 $val = implode(', ', $val);
3036 $value = "{$pair[$op]} " . $val;
3038 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3039 isset($field['options']) &&
3040 is_array($field['options']) && !empty($field['options'])
3042 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3043 CRM_Utils_Array
::value($val, $field['options'], $val);
3046 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3050 $statistics['filters'][] = array(
3051 'title' => CRM_Utils_Array
::value('title', $field),
3062 * End post processing.
3064 * @param array|null $rows
3066 public function endPostProcess(&$rows = NULL) {
3067 $this->assign('report_class', get_class($this));
3068 if ($this->_storeResultSet
) {
3069 $this->_resultSet
= $rows;
3072 if ($this->_outputMode
== 'print' ||
3073 $this->_outputMode
== 'pdf' ||
3077 $content = $this->compileContent();
3078 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3082 if ($this->_sendmail
) {
3083 $config = CRM_Core_Config
::singleton();
3084 $attachments = array();
3086 if ($this->_outputMode
== 'csv') {
3088 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3089 ": {$url}</p>" . '<p>' .
3090 ts('The report is attached as a CSV file.') . '</p>' .
3091 $this->_formValues
['report_footer'];
3093 $csvFullFilename = $config->templateCompileDir
.
3094 CRM_Utils_File
::makeFileName('CiviReport.csv');
3095 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3096 file_put_contents($csvFullFilename, $csvContent);
3097 $attachments[] = array(
3098 'fullPath' => $csvFullFilename,
3099 'mime_type' => 'text/csv',
3100 'cleanName' => 'CiviReport.csv',
3103 if ($this->_outputMode
== 'pdf') {
3104 // generate PDF content
3105 $pdfFullFilename = $config->templateCompileDir
.
3106 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3107 file_put_contents($pdfFullFilename,
3108 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3109 TRUE, array('orientation' => 'landscape')
3112 // generate Email Content
3114 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3115 ": {$url}</p>" . '<p>' .
3116 ts('The report is attached as a PDF file.') . '</p>' .
3117 $this->_formValues
['report_footer'];
3119 $attachments[] = array(
3120 'fullPath' => $pdfFullFilename,
3121 'mime_type' => 'application/pdf',
3122 'cleanName' => 'CiviReport.pdf',
3126 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3127 $this->_outputMode
, $attachments
3130 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3133 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3137 elseif ($this->_outputMode
== 'print') {
3141 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3142 $config = CRM_Core_Config
::singleton();
3143 //get chart image name
3144 $chartImg = $this->_chartId
. '.png';
3145 //get image url path
3147 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3149 $uploadUrl .= $chartImg;
3150 //get image doc path to overwrite
3152 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3153 'openFlashChart/' . $chartImg;
3155 $chart = imagecreatefrompng($uploadUrl);
3156 //convert it into formatted png
3157 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3158 //overwrite with same image
3159 imagepng($chart, $uploadImg);
3161 imagedestroy($chart);
3163 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3165 CRM_Utils_System
::civiExit();
3167 elseif ($this->_outputMode
== 'csv') {
3168 CRM_Report_Utils_Report
::export2csv($this, $rows);
3170 elseif ($this->_outputMode
== 'group') {
3171 $group = $this->_params
['groups'];
3172 $this->add2group($group);
3177 * Set store result set indicator to TRUE.
3179 * @todo explain what this does
3181 public function storeResultSet() {
3182 $this->_storeResultSet
= TRUE;
3190 public function getResultSet() {
3191 return $this->_resultSet
;
3195 * Get the sql used to generate the report.
3199 public function getReportSql() {
3200 return $this->sqlArray
;
3204 * Use the form name to create the tpl file name.
3208 public function getTemplateFileName() {
3209 $defaultTpl = parent
::getTemplateFileName();
3210 $template = CRM_Core_Smarty
::singleton();
3211 if (!$template->template_exists($defaultTpl)) {
3212 $defaultTpl = 'CRM/Report/Form.tpl';
3218 * Compile the report content.
3220 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3224 public function compileContent() {
3225 $templateFile = $this->getHookedTemplateFileName();
3226 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3227 CRM_Core_Form
::$_template->fetch($templateFile) .
3228 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3233 * Post process function.
3235 public function postProcess() {
3236 // get ready with post process params
3237 $this->beginPostProcess();
3240 $sql = $this->buildQuery();
3242 // build array of result based on column headers. This method also allows
3243 // modifying column headers before using it to build result set i.e $rows.
3245 $this->buildRows($sql, $rows);
3247 // format result set.
3248 $this->formatDisplay($rows);
3250 // assign variables to templates
3251 $this->doTemplateAssignment($rows);
3253 // do print / pdf / instance stuff if needed
3254 $this->endPostProcess($rows);
3260 * @param int $rowCount
3264 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3265 // lets do the pager if in html mode
3266 $this->_limit
= NULL;
3268 // CRM-14115, over-ride row count if rowCount is specified in URL
3269 if ($this->_dashBoardRowCount
) {
3270 $rowCount = $this->_dashBoardRowCount
;
3272 if ($this->addPaging
) {
3273 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3275 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3277 // @todo all http vars should be extracted in the preProcess
3278 // - not randomly in the class
3279 if (!$pageId && !empty($_POST)) {
3280 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3281 $pageId = max((int) $_POST['crmPID_B'], 1);
3283 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3284 $pageId = max((int) $_POST['crmPID'], 1);
3286 unset($_POST['crmPID_B'], $_POST['crmPID']);
3289 $pageId = $pageId ?
$pageId : 1;
3290 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3291 $offset = ($pageId - 1) * $rowCount;
3293 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3294 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3296 $this->_limit
= " LIMIT $offset, $rowCount";
3297 return array($offset, $rowCount);
3299 if ($this->_limitValue
) {
3300 if ($this->_offsetValue
) {
3301 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3304 $this->_limit
= " LIMIT " . $this->_limitValue
;
3312 * @param int $rowCount
3314 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3315 // CRM-14115, over-ride row count if rowCount is specified in URL
3316 if ($this->_dashBoardRowCount
) {
3317 $rowCount = $this->_dashBoardRowCount
;
3320 if ($this->_limit
&& ($this->_limit
!= '')) {
3321 if (!$this->_rowsFound
) {
3322 $sql = "SELECT FOUND_ROWS();";
3323 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3326 'total' => $this->_rowsFound
,
3327 'rowCount' => $rowCount,
3328 'status' => ts('Records') . ' %%StatusMessage%%',
3329 'buttonBottom' => 'PagerBottomButton',
3330 'buttonTop' => 'PagerTopButton',
3332 if (!empty($this->controller
)) {
3333 // This happens when being called from the api Really we want the api to be able to
3334 // pass paging parameters, but at this stage just preventing test crashes.
3335 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3338 $pager = new CRM_Utils_Pager($params);
3339 $this->assign_by_ref('pager', $pager);
3340 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3345 * Build a group filter with contempt for large data sets.
3347 * This function has been retained as it takes time to migrate the reports over
3348 * to the new method which will not crash on large datasets.
3352 * @param string $field
3353 * @param mixed $value
3358 public function legacySlowGroupFilterClause($field, $value, $op) {
3359 $smartGroupQuery = "";
3361 $group = new CRM_Contact_DAO_Group();
3362 $group->is_active
= 1;
3364 $smartGroups = array();
3365 while ($group->fetch()) {
3366 if (in_array($group->id
, $this->_params
['gid_value']) &&
3367 $group->saved_search_id
3369 $smartGroups[] = $group->id
;
3373 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3375 $smartGroupQuery = '';
3376 if (!empty($smartGroups)) {
3377 $smartGroups = implode(',', $smartGroups);
3378 $smartGroupQuery = " UNION DISTINCT
3379 SELECT DISTINCT smartgroup_contact.contact_id
3380 FROM civicrm_group_contact_cache smartgroup_contact
3381 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3384 $sqlOp = $this->getSQLOperator($op);
3385 if (!is_array($value)) {
3386 $value = array($value);
3388 //include child groups if any
3389 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3391 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3393 $contactAlias = $this->_aliases
['civicrm_contact'];
3394 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3395 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3397 return " {$contactAlias}.id {$sqlOp} (
3398 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3399 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3400 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3401 {$smartGroupQuery} ) ";
3405 * Build where clause for groups.
3407 * @param string $field
3408 * @param mixed $value
3413 public function whereGroupClause($field, $value, $op) {
3414 if ($this->groupFilterNotOptimised
) {
3415 return $this->legacySlowGroupFilterClause($field, $value, $op);
3417 if ($op === 'notin') {
3418 return " group_temp_table.id IS NULL ";
3420 // We will have used an inner join instead.
3426 * Create a table of the contact ids included by the group filter.
3428 * This function is called by both the api (tests) and the UI.
3430 public function buildGroupTempTable() {
3431 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3434 $filteredGroups = (array) $this->_params
['gid_value'];
3436 $groups = civicrm_api3('Group', 'get', array(
3438 'id' => array('IN' => $filteredGroups),
3439 'saved_search_id' => array('>' => 0),
3442 $smartGroups = array_keys($groups['values']);
3445 SELECT DISTINCT group_contact.contact_id as id
3446 FROM civicrm_group_contact group_contact
3447 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3448 AND group_contact.status = 'Added' ";
3450 if (!empty($smartGroups)) {
3451 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3452 $smartGroups = implode(',', $smartGroups);
3455 SELECT smartgroup_contact.contact_id as id
3456 FROM civicrm_group_contact_cache smartgroup_contact
3457 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3460 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3461 $this->executeReportQuery("
3462 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3465 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3469 * Execute query and add it to the developer tab.
3471 * @param string $query
3472 * @param array $params
3474 * @return \CRM_Core_DAO|object
3476 protected function executeReportQuery($query, $params = array()) {
3477 $this->addToDeveloperTab($query);
3478 return CRM_Core_DAO
::executeQuery($query, $params);
3482 * Build where clause for tags.
3484 * @param string $field
3485 * @param mixed $value
3490 public function whereTagClause($field, $value, $op) {
3491 // not using left join in query because if any contact
3492 // belongs to more than one tag, results duplicate
3494 $sqlOp = $this->getSQLOperator($op);
3495 if (!is_array($value)) {
3496 $value = array($value);
3498 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3499 $entity_table = $this->_tagFilterTable
;
3500 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3501 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3502 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3503 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3507 * Generate membership organization clause.
3509 * @param mixed $value
3510 * @param string $op SQL Operator
3514 public function whereMembershipOrgClause($value, $op) {
3515 $sqlOp = $this->getSQLOperator($op);
3516 if (!is_array($value)) {
3517 $value = array($value);
3520 $tmp_membership_org_sql_list = implode(', ', $value);
3521 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3522 SELECT DISTINCT mem.contact_id
3523 FROM civicrm_membership mem
3524 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3525 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3526 WHERE mt.member_of_contact_id IN (" .
3527 $tmp_membership_org_sql_list . ")
3528 AND mt.is_active = '1'
3529 AND mem_status.is_current_member = '1'
3530 AND mem_status.is_active = '1' ) ";
3534 * Generate Membership Type SQL Clause.
3536 * @param mixed $value
3542 public function whereMembershipTypeClause($value, $op) {
3543 $sqlOp = $this->getSQLOperator($op);
3544 if (!is_array($value)) {
3545 $value = array($value);
3548 $tmp_membership_sql_list = implode(', ', $value);
3549 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3550 SELECT DISTINCT mem.contact_id
3551 FROM civicrm_membership mem
3552 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3553 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3554 WHERE mem.membership_type_id IN (" .
3555 $tmp_membership_sql_list . ")
3556 AND mt.is_active = '1'
3557 AND mem_status.is_current_member = '1'
3558 AND mem_status.is_active = '1' ) ";
3562 * Buld contact acl clause
3563 * @deprecated in favor of buildPermissionClause
3565 * @param string $tableAlias
3567 public function buildACLClause($tableAlias = 'contact_a') {
3568 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3572 * Build the permision clause for all entities in this report
3574 public function buildPermissionClause() {
3576 foreach ($this->selectedTables() as $tableName) {
3577 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3578 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3579 $tableAlias = $this->_columns
[$tableName]['alias'];
3580 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3581 foreach ($clauses as $field => $clause) {
3582 // Skip contact_id field if redundant
3583 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3584 $ret["$tableName.$field"] = $clause;
3589 // Override output from buildACLClause
3590 $this->_aclFrom
= NULL;
3591 $this->_aclWhere
= implode(' AND ', $ret);
3595 * Add custom data to the columns.
3597 * @param bool $addFields
3598 * @param array $permCustomGroupIds
3600 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3601 if (empty($this->_customGroupExtends
)) {
3604 if (!is_array($this->_customGroupExtends
)) {
3605 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3607 $customGroupWhere = '';
3608 if (!empty($permCustomGroupIds)) {
3609 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3613 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3614 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3615 FROM civicrm_custom_group cg
3616 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3617 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3619 cg.is_active = 1 AND
3620 cf.is_active = 1 AND
3621 cf.is_searchable = 1
3622 ORDER BY cg.weight, cf.weight";
3623 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3626 while ($customDAO->fetch()) {
3627 if ($customDAO->table_name
!= $curTable) {
3628 $curTable = $customDAO->table_name
;
3629 $curFields = $curFilters = array();
3632 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3633 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3634 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3635 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3637 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3638 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3639 $this->_columns
[$curTable][$colKey] = array();
3643 $fieldName = 'custom_' . $customDAO->cf_id
;
3646 // this makes aliasing work in favor
3647 $curFields[$fieldName] = array(
3648 'name' => $customDAO->column_name
,
3649 'title' => $customDAO->label
,
3650 'dataType' => $customDAO->data_type
,
3651 'htmlType' => $customDAO->html_type
,
3654 if ($this->_customGroupFilters
) {
3655 // this makes aliasing work in favor
3656 $curFilters[$fieldName] = array(
3657 'name' => $customDAO->column_name
,
3658 'title' => $customDAO->label
,
3659 'dataType' => $customDAO->data_type
,
3660 'htmlType' => $customDAO->html_type
,
3664 switch ($customDAO->data_type
) {
3667 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3668 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3669 // CRM-6946, show time part for datetime date fields
3670 if ($customDAO->time_format
) {
3671 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3676 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3677 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3678 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3682 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3683 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3687 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3688 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3689 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3693 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3694 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3698 case 'StateProvince':
3700 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3702 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3703 if ($options !== FALSE) {
3704 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3705 $curFilters[$fieldName]['options'] = $options;
3709 case 'ContactReference':
3710 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3711 $curFilters[$fieldName]['name'] = 'display_name';
3712 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3714 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3715 $curFields[$fieldName]['name'] = 'display_name';
3716 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3720 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3721 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3725 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3726 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3727 if ($options !== FALSE) {
3728 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3729 $curFilters[$fieldName]['options'] = $options;
3733 if (!array_key_exists('type', $curFields[$fieldName])) {
3734 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3738 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3740 if ($this->_customGroupFilters
) {
3741 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3743 if ($this->_customGroupGroupBy
) {
3744 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3750 * Build custom data from clause.
3752 * @param bool $joinsForFiltersOnly
3753 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3755 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3756 if (empty($this->_customGroupExtends
)) {
3759 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3760 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3761 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3762 $customTables = array();
3763 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3764 while ($customTablesDAO->fetch()) {
3765 $customTables[] = $customTablesDAO->table_name
;
3768 foreach ($this->_columns
as $table => $prop) {
3769 if (in_array($table, $customTables)) {
3770 $extendsTable = $mapper[$prop['extends']];
3771 // Check field is required for rendering the report.
3772 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3775 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3777 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3779 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3780 // handle for ContactReference
3781 if (array_key_exists('fields', $prop)) {
3782 foreach ($prop['fields'] as $fieldName => $field) {
3783 if (CRM_Utils_Array
::value('dataType', $field) ==
3786 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3788 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3797 * Check if the field is selected.
3799 * @param string $prop
3803 public function isFieldSelected($prop) {
3808 if (!empty($this->_params
['fields'])) {
3809 foreach (array_keys($prop['fields']) as $fieldAlias) {
3810 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3811 if ($customFieldId) {
3812 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3816 //might be survey response field.
3817 if (!empty($this->_params
['fields']['survey_response']) &&
3818 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3826 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3827 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3828 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3829 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3836 if (!empty($this->_params
['order_bys'])) {
3837 foreach (array_keys($prop['fields']) as $fieldAlias) {
3838 foreach ($this->_params
['order_bys'] as $orderBy) {
3839 if ($fieldAlias == $orderBy['column'] &&
3840 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3847 return $this->isFieldFiltered($prop);
3852 * Check if the field is used as a filter.
3854 * @param string $prop
3858 protected function isFieldFiltered($prop) {
3859 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3860 foreach ($prop['filters'] as $fieldAlias => $val) {
3869 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3870 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3871 ||
($attach != 'relative' &&
3872 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3878 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3879 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3890 * Check for empty order_by configurations and remove them.
3892 * Also set template to hide them.
3894 * @param array $formValues
3896 public function preProcessOrderBy(&$formValues) {
3897 // Object to show/hide form elements
3898 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3900 $_showHide->addShow('optionField_1');
3902 // Cycle through order_by options; skip any empty ones, and hide them as well
3905 if (!empty($formValues['order_bys'])) {
3906 foreach ($formValues['order_bys'] as $order_by) {
3907 if ($order_by['column'] && $order_by['column'] != '-') {
3908 $_showHide->addShow('optionField_' . $n);
3909 $orderBys[$n] = $order_by;
3914 for ($i = $n; $i <= 5; $i++
) {
3916 $_showHide->addHide('optionField_' . $i);
3920 // overwrite order_by options with modified values
3921 if (!empty($orderBys)) {
3922 $formValues['order_bys'] = $orderBys;
3925 $formValues['order_bys'] = array(1 => array('column' => '-'));
3928 // assign show/hide data to template
3929 $_showHide->addToTemplate();
3933 * Check if table name has columns in SELECT clause.
3935 * @param string $tableName
3936 * Name of table (index of $this->_columns array).
3940 public function isTableSelected($tableName) {
3941 return in_array($tableName, $this->selectedTables());
3945 * Check if table name has columns in WHERE or HAVING clause.
3947 * @param string $tableName
3948 * Name of table (index of $this->_columns array).
3952 public function isTableFiltered($tableName) {
3953 // Cause the array to be generated if not previously done.
3954 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3955 $this->selectedTables();
3957 return in_array($tableName, $this->filteredTables
);
3961 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3963 * If the array is unset it will be built.
3968 public function selectedTables() {
3969 if (!$this->_selectedTables
) {
3970 $orderByColumns = array();
3971 if (array_key_exists('order_bys', $this->_params
) &&
3972 is_array($this->_params
['order_bys'])
3974 foreach ($this->_params
['order_bys'] as $orderBy) {
3975 $orderByColumns[] = $orderBy['column'];
3979 foreach ($this->_columns
as $tableName => $table) {
3980 if (array_key_exists('fields', $table)) {
3981 foreach ($table['fields'] as $fieldName => $field) {
3982 if (!empty($field['required']) ||
3983 !empty($this->_params
['fields'][$fieldName])
3985 $this->_selectedTables
[] = $tableName;
3990 if (array_key_exists('order_bys', $table)) {
3991 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3992 if (in_array($orderByName, $orderByColumns)) {
3993 $this->_selectedTables
[] = $tableName;
3998 if (array_key_exists('filters', $table)) {
3999 foreach ($table['filters'] as $filterName => $filter) {
4000 if (!empty($this->_params
["{$filterName}_value"]) ||
4001 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4003 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4006 $this->_selectedTables
[] = $tableName;
4007 $this->filteredTables
[] = $tableName;
4014 return $this->_selectedTables
;
4018 * Add address fields.
4020 * @deprecated - use getAddressColumns which is a more accurate description
4021 * and also accepts an array of options rather than a long list
4023 * adding address fields to construct function in reports
4025 * @param bool $groupBy
4026 * Add GroupBy? Not appropriate for detail report.
4027 * @param bool $orderBy
4028 * Add GroupBy? Not appropriate for detail report.
4029 * @param bool $filters
4030 * @param array $defaults
4033 * address fields for construct clause
4035 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4036 $defaultAddressFields = array(
4037 'street_address' => ts('Street Address'),
4038 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4039 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4040 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4041 'street_number' => ts('Street Number'),
4042 'street_name' => ts('Street Name'),
4043 'street_unit' => ts('Street Unit'),
4044 'city' => ts('City'),
4045 'postal_code' => ts('Postal Code'),
4046 'postal_code_suffix' => ts('Postal Code Suffix'),
4047 'country_id' => ts('Country'),
4048 'state_province_id' => ts('State/Province'),
4049 'county_id' => ts('County'),
4051 $addressFields = array(
4052 'civicrm_address' => array(
4053 'dao' => 'CRM_Core_DAO_Address',
4055 'address_name' => array(
4056 'title' => ts('Address Name'),
4057 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4061 'grouping' => 'location-fields',
4064 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4065 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4066 'title' => $fieldLabel,
4067 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4071 $street_address_filters = $general_address_filters = array();
4073 // Address filter depends on whether street address parsing is enabled.
4075 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4078 if ($addressOptions['street_address_parsing']) {
4079 $street_address_filters = array(
4080 'street_number' => array(
4081 'title' => ts('Street Number'),
4082 'type' => CRM_Utils_Type
::T_INT
,
4083 'name' => 'street_number',
4085 'street_name' => array(
4086 'title' => ts('Street Name'),
4087 'name' => 'street_name',
4088 'type' => CRM_Utils_Type
::T_STRING
,
4093 $street_address_filters = array(
4094 'street_address' => array(
4095 'title' => ts('Street Address'),
4096 'type' => CRM_Utils_Type
::T_STRING
,
4097 'name' => 'street_address',
4101 $general_address_filters = array(
4102 'postal_code' => array(
4103 'title' => ts('Postal Code'),
4104 'type' => CRM_Utils_Type
::T_STRING
,
4105 'name' => 'postal_code',
4108 'title' => ts('City'),
4109 'type' => CRM_Utils_Type
::T_STRING
,
4112 'country_id' => array(
4113 'name' => 'country_id',
4114 'title' => ts('Country'),
4115 'type' => CRM_Utils_Type
::T_INT
,
4116 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4117 'options' => CRM_Core_PseudoConstant
::country(),
4119 'state_province_id' => array(
4120 'name' => 'state_province_id',
4121 'title' => ts('State/Province'),
4122 'type' => CRM_Utils_Type
::T_INT
,
4123 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4124 'options' => array(),
4126 'county_id' => array(
4127 'name' => 'county_id',
4128 'title' => ts('County'),
4129 'type' => CRM_Utils_Type
::T_INT
,
4130 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4131 'options' => array(),
4135 $addressFields['civicrm_address']['filters'] = array_merge(
4136 $street_address_filters,
4137 $general_address_filters);
4140 $addressFields['civicrm_address']['order_bys'] = array(
4141 'street_name' => array('title' => ts('Street Name')),
4142 'street_number' => array('title' => ts('Odd / Even Street Number')),
4143 'street_address' => NULL,
4145 'postal_code' => NULL,
4150 $addressFields['civicrm_address']['group_bys'] = array(
4151 'street_address' => NULL,
4153 'postal_code' => NULL,
4154 'state_province_id' => array(
4155 'title' => ts('State/Province'),
4157 'country_id' => array(
4158 'title' => ts('Country'),
4160 'county_id' => array(
4161 'title' => ts('County'),
4165 return $addressFields;
4169 * Do AlterDisplay processing on Address Fields.
4172 * @param array $rows
4173 * @param int $rowNum
4174 * @param string $baseUrl
4175 * @param string $linkText
4179 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4180 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4181 $entryFound = FALSE;
4183 if (array_key_exists('civicrm_address_country_id', $row)) {
4184 if ($value = $row['civicrm_address_country_id']) {
4185 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4187 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4188 "reset=1&force=1&{$criteriaQueryParams}&" .
4189 "country_id_op=in&country_id_value={$value}",
4190 $this->_absoluteUrl
, $this->_id
4192 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4193 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4194 array(1 => $linkText)
4201 if (array_key_exists('civicrm_address_county_id', $row)) {
4202 if ($value = $row['civicrm_address_county_id']) {
4203 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4205 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4206 "reset=1&force=1&{$criteriaQueryParams}&" .
4207 "county_id_op=in&county_id_value={$value}",
4208 $this->_absoluteUrl
, $this->_id
4210 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4211 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4212 array(1 => $linkText)
4218 // handle state province
4219 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4220 if ($value = $row['civicrm_address_state_province_id']) {
4221 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4223 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4224 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4225 $this->_absoluteUrl
, $this->_id
4227 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4228 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4229 array(1 => $linkText)
4240 * Do AlterDisplay processing on Address Fields.
4243 * @param array $rows
4244 * @param int $rowNum
4245 * @param string $baseUrl
4246 * @param string $linkText
4250 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4251 $entryFound = FALSE;
4252 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4253 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4254 $addLinks = array('gender_id' => 'Gender');
4255 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4256 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4257 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4258 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4259 $rowLabels = array();
4260 foreach ($rowValues as $rowValue) {
4262 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4265 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4266 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4267 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4273 $yesNoFields = array(
4274 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4276 foreach ($yesNoFields as $fieldName) {
4277 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4278 // Since these are essentially 'negative fields' it feels like it
4279 // makes sense to only highlight the exceptions hence no 'No'.
4280 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4288 * Adjusts dates passed in to YEAR() for fiscal year.
4290 * @param string $fieldName
4294 public function fiscalYearOffset($fieldName) {
4295 $config = CRM_Core_Config
::singleton();
4296 $fy = $config->fiscalYearStart
;
4297 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4298 ($fy['d'] == 1 && $fy['M'] == 1)
4300 return "YEAR( $fieldName )";
4302 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4303 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4307 * Add Address into From Table if required.
4309 public function addAddressFromClause() {
4310 // include address field if address column is to be included
4311 if ((isset($this->_addressField
) &&
4312 $this->_addressField
4314 $this->isTableSelected('civicrm_address')
4317 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4318 ON ({$this->_aliases['civicrm_contact']}.id =
4319 {$this->_aliases['civicrm_address']}.contact_id) AND
4320 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4325 * Add Phone into From Table if required.
4327 public function addPhoneFromClause() {
4328 // include address field if address column is to be included
4329 if ($this->isTableSelected('civicrm_phone')) {
4331 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4332 ON ({$this->_aliases['civicrm_contact']}.id =
4333 {$this->_aliases['civicrm_phone']}.contact_id) AND
4334 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4339 * Add Financial Transaction into From Table if required.
4341 public function addFinancialTrxnFromClause() {
4342 if ($this->isTableSelected('civicrm_financial_trxn')) {
4344 LEFT JOIN civicrm_entity_financial_trxn eftcc
4345 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4346 eftcc.entity_table = 'civicrm_contribution')
4347 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4348 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4353 * Get phone columns to add to array.
4355 * @param array $options
4356 * - prefix Prefix to add to table (in case of more than one instance of the table)
4357 * - prefix_label Label to give columns from this phone table instance
4360 * phone columns definition
4362 public function getPhoneColumns($options = array()) {
4363 $defaultOptions = array(
4365 'prefix_label' => '',
4368 $options = array_merge($defaultOptions, $options);
4371 $options['prefix'] . 'civicrm_phone' => array(
4372 'dao' => 'CRM_Core_DAO_Phone',
4374 $options['prefix'] . 'phone' => array(
4375 'title' => ts($options['prefix_label'] . 'Phone'),
4385 * Get address columns to add to array.
4387 * @param array $options
4388 * - prefix Prefix to add to table (in case of more than one instance of the table)
4389 * - prefix_label Label to give columns from this address table instance
4392 * address columns definition
4394 public function getAddressColumns($options = array()) {
4397 'prefix_label' => '',
4401 'defaults' => array(),
4403 return $this->addAddressFields(
4404 $options['group_by'],
4405 $options['order_by'],
4406 $options['filters'],
4407 $options['defaults']
4412 * Get a standard set of contact fields.
4416 public function getBasicContactFields() {
4418 'sort_name' => array(
4419 'title' => ts('Contact Name'),
4424 'no_display' => TRUE,
4427 'prefix_id' => array(
4428 'title' => ts('Contact Prefix'),
4430 'first_name' => array(
4431 'title' => ts('First Name'),
4433 'nick_name' => array(
4434 'title' => ts('Nick Name'),
4436 'middle_name' => array(
4437 'title' => ts('Middle Name'),
4439 'last_name' => array(
4440 'title' => ts('Last Name'),
4442 'suffix_id' => array(
4443 'title' => ts('Contact Suffix'),
4445 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4446 'email_greeting_display' => array('title' => ts('Email Greeting')),
4447 'addressee_display' => array('title' => ts('Addressee')),
4448 'contact_type' => array(
4449 'title' => ts('Contact Type'),
4451 'contact_sub_type' => array(
4452 'title' => ts('Contact Subtype'),
4454 'gender_id' => array(
4455 'title' => ts('Gender'),
4457 'birth_date' => array(
4458 'title' => ts('Birth Date'),
4461 'title' => ts('Age'),
4462 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4464 'job_title' => array(
4465 'title' => ts('Contact Job title'),
4467 'organization_name' => array(
4468 'title' => ts('Organization Name'),
4470 'external_identifier' => array(
4471 'title' => ts('Contact identifier from external system'),
4473 'do_not_email' => array(),
4474 'do_not_phone' => array(),
4475 'do_not_mail' => array(),
4476 'do_not_sms' => array(),
4477 'is_opt_out' => array(),
4478 'is_deceased' => array(),
4479 'preferred_language' => array(),
4484 * Get a standard set of contact filters.
4488 public function getBasicContactFilters() {
4490 'sort_name' => array(
4491 'title' => ts('Contact Name'),
4494 'title' => ts('Contact Source'),
4495 'type' => CRM_Utils_Type
::T_STRING
,
4498 'title' => ts('Contact ID'),
4499 'no_display' => TRUE,
4501 'gender_id' => array(
4502 'title' => ts('Gender'),
4503 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4504 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4506 'birth_date' => array(
4507 'title' => ts('Birth Date'),
4508 'operatorType' => CRM_Report_Form
::OP_DATE
,
4510 'contact_type' => array(
4511 'title' => ts('Contact Type'),
4513 'contact_sub_type' => array(
4514 'title' => ts('Contact Subtype'),
4516 'modified_date' => array(
4517 'title' => ts('Contact Modified'),
4518 'operatorType' => CRM_Report_Form
::OP_DATE
,
4519 'type' => CRM_Utils_Type
::T_DATE
,
4521 'is_deceased' => array(
4522 'title' => ts('Deceased'),
4523 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4526 'do_not_email' => array(
4527 'title' => ts('Do not email'),
4528 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4530 'do_not_phone' => array(
4531 'title' => ts('Do not phone'),
4532 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4534 'do_not_mail' => array(
4535 'title' => ts('Do not mail'),
4536 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4538 'do_not_sms' => array(
4539 'title' => ts('Do not SMS'),
4540 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4542 'is_opt_out' => array(
4543 'title' => ts('Do not bulk email'),
4544 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4546 'preferred_language' => array(
4547 'title' => ts('Preferred Language'),
4553 * Add contact to group.
4555 * @param int $groupID
4557 public function add2group($groupID) {
4558 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4559 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4560 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4561 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4562 $sql = str_replace('WITH ROLLUP', '', $sql);
4563 $dao = CRM_Core_DAO
::executeQuery($sql);
4565 $contact_ids = array();
4566 // Add resulting contacts to group
4567 while ($dao->fetch()) {
4568 if ($dao->addtogroup_contact_id
) {
4569 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4573 if (!empty($contact_ids)) {
4574 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4575 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4578 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4584 * Show charts on print screen.
4586 public static function uploadChartImage() {
4587 // upload strictly for '.png' images
4588 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4589 if (preg_match('/\.png$/', $name)) {
4591 // Get the RAW .png from the input.
4592 $httpRawPostData = file_get_contents("php://input");
4594 // prepare the directory
4595 $config = CRM_Core_Config
::singleton();
4597 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4599 if (!file_exists($defaultPath)) {
4600 mkdir($defaultPath, 0777, TRUE);
4603 // full path to the saved image including filename
4604 $destination = $defaultPath . $name;
4607 $jfh = fopen($destination, 'w') or die("can't open file");
4608 fwrite($jfh, $httpRawPostData);
4610 CRM_Utils_System
::civiExit();
4615 * Apply common settings to entityRef fields.
4617 * @param array $field
4618 * @param string $table
4620 private function setEntityRefDefaults(&$field, $table) {
4621 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4622 $field['attributes'] +
= array(
4623 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4625 'placeholder' => ts('- select -'),
4630 * Add link fields to the row.
4632 * Function adds the _link & _hover fields to the row.
4635 * @param string $baseUrl
4636 * @param string $linkText
4637 * @param string $value
4638 * @param string $fieldName
4639 * @param string $tablePrefix
4640 * @param string $fieldLabel
4644 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4645 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4646 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4647 "reset=1&force=1&{$criteriaQueryParams}&" .
4648 $fieldName . "_op=in&{$fieldName}_value={$value}",
4649 $this->_absoluteUrl
, $this->_id
4651 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4652 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4653 array(1 => $linkText, 2 => $fieldLabel)
4658 * Generate temporary table to hold all contributions with permissioned FTs.
4660 * @param object $query
4661 * @param string $alias
4662 * @param bool $return
4666 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4667 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4670 $financialTypes = NULL;
4671 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4672 if (empty($financialTypes)) {
4674 $liFTs = implode(',', array_keys(CRM_Contribute_PseudoConstant
::financialType()));
4677 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4679 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4681 $query->_aliases
['civicrm_line_item'] = $alias;
4684 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4686 if (empty($query->_where
)) {
4687 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4689 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4690 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp {$this->_databaseAttributes} AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4691 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4692 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4693 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4694 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4696 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4697 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4698 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4699 CRM_Core_DAO
::executeQuery($sql);
4701 $query->_aliases
['civicrm_line_item'] = $temp;
4703 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4707 $query->_from
.= $from;
4711 * Get label for show results buttons.
4715 public function getResultsLabel() {
4716 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4717 return $showResultsLabel;
4721 * Determine the output mode from the url or input.
4724 * - pdf : Render as pdf
4725 * - csv : Render as csv
4726 * - print : Render in print format
4727 * - save : save the report and display the new report
4728 * - copy : save the report as a new instance and display that.
4729 * - group : go to the add to group screen.
4731 * Potentially chart variations could also be included but the complexity
4732 * is that we might print a bar chart as a pdf.
4734 protected function setOutputMode() {
4735 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4738 CRM_Core_DAO
::$_nullObject,
4740 CRM_Utils_Array
::value('task', $this->_params
)
4742 // if contacts are added to group
4743 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4744 $this->_outputMode
= 'group';
4746 if (isset($this->_params
['task'])) {
4747 unset($this->_params
['task']);
4752 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4755 * @param $columnName
4757 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4758 // add new column with date value for the datetime field
4759 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4760 CRM_Core_DAO
::executeQuery($tempQuery);
4761 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4762 CRM_Core_DAO
::executeQuery($updateQuery);
4763 $this->_selectClauses
[] = "{$columnName}_date";
4764 $this->_select
.= ", {$columnName}_date";
4765 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4766 unset($this->_sections
["{$columnName}"]);
4767 $this->assign('sections', $this->_sections
);
4771 * Get an array of the columns that have been selected for display.
4775 public function getSelectColumns() {
4776 $selectColumns = array();
4777 foreach ($this->_columns
as $tableName => $table) {
4778 if (array_key_exists('fields', $table)) {
4779 foreach ($table['fields'] as $fieldName => $field) {
4780 if (!empty($field['required']) ||
4781 !empty($this->_params
['fields'][$fieldName])
4784 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4789 return $selectColumns;
4793 * Add location tables to the query if they are used for filtering.
4795 * This is for when we are running the query separately for filtering and retrieving display fields.
4797 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4798 if ($this->isTableFiltered('civicrm_email')) {
4800 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4801 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4802 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4804 if ($this->isTableFiltered('civicrm_phone')) {
4806 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4807 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4808 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4810 if ($this->isTableFiltered('civicrm_address')) {
4812 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4813 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4814 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4819 * Set the base table for the FROM clause.
4821 * Sets up the from clause, allowing for the possibility it might be a
4822 * temp table pre-filtered by groups if a group filter is in use.
4824 * @param string $baseTable
4825 * @param string $field
4826 * @param null $tableAlias
4828 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4830 $tableAlias = $this->_aliases
[$baseTable];
4832 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4833 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4834 $this->_from
.= " {$this->_aclFrom} ";
4838 * Join the temp table contacting contacts who are members of the filtered groups.
4840 * If we are using an IN filter we use an inner join, otherwise a left join.
4842 * @param string $baseTable
4843 * @param string $field
4844 * @param string $tableAlias
4846 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4847 if ($this->groupTempTable
) {
4848 if ($this->_params
['gid_op'] == 'in') {
4849 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4850 ON group_temp_table.id = $tableAlias.{$field} ";
4854 LEFT JOIN $this->groupTempTable group_temp_table
4855 ON $tableAlias.{$field} = group_temp_table.id ";
4861 * Get all labels for fields that are used in a group concat.
4863 * @param string $options
4864 * comma separated option values.
4865 * @param string $baoName
4866 * The BAO name for the field.
4867 * @param string $fieldName
4868 * The name of the field for which labels should be retrieved.
4872 public function getLabels($options, $baoName, $fieldName) {
4873 $types = explode(',', $options);
4875 foreach ($types as $value) {
4876 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
4878 return implode(', ', array_filter($labels));
4882 * Add statistics columns.
4884 * If a group by is in play then add columns for the statistics fields.
4886 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
4887 * column header field.
4889 * @param array $field
4890 * @param string $tableName
4891 * @param string $fieldName
4892 * @param array $select
4896 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
4897 foreach ($field['statistics'] as $stat => $label) {
4898 $alias = "{$tableName}_{$fieldName}_{$stat}";
4899 switch (strtolower($stat)) {
4902 $select[] = "$stat({$field['dbAlias']}) as $alias";
4903 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4904 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4905 $this->_statFields
[$label] = $alias;
4906 $this->_selectAliases
[] = $alias;
4910 $select[] = "COUNT({$field['dbAlias']}) as $alias";
4911 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4912 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4913 $this->_statFields
[$label] = $alias;
4914 $this->_selectAliases
[] = $alias;
4917 case 'count_distinct':
4918 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
4919 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4920 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4921 $this->_statFields
[$label] = $alias;
4922 $this->_selectAliases
[] = $alias;
4926 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
4927 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4928 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4929 $this->_statFields
[$label] = $alias;
4930 $this->_selectAliases
[] = $alias;
4938 * Add a basic field to the select clause.
4940 * @param string $tableName
4941 * @param string $fieldName
4942 * @param array $field
4943 * @param string $select
4946 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
4947 $alias = "{$tableName}_{$fieldName}";
4948 $select[] = "{$field['dbAlias']} as $alias";
4949 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
4950 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
4951 $this->_selectAliases
[] = $alias;
4958 * @param array $table
4959 * @param string $tableName
4964 protected function setTableAlias($table, $tableName) {
4965 if (!isset($table['alias'])) {
4966 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
4970 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
4973 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
4974 return $this->_aliases
[$tableName];