3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 protected $_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;
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 * SQL being run in this report.
447 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
455 * SQL being run in this report as an array.
457 * The sql in the report is stored in this variable in order to be returned to api & test calls.
466 public function __construct() {
467 parent
::__construct();
469 $this->addClass('crm-report-form');
471 if ($this->_tagFilter
) {
472 $this->buildTagFilter();
474 if ($this->_exposeContactID
) {
475 if (array_key_exists('civicrm_contact', $this->_columns
)) {
476 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
478 'title' => ts('Contact ID'),
484 if ($this->_groupFilter
) {
485 $this->buildGroupFilter();
488 // Get all custom groups
489 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
491 // Get the custom groupIds for which the user has VIEW permission
492 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
493 // and addCustomDataToColumns() will allow access to all custom groups.
494 $permCustomGroupIds = array();
495 if (!CRM_Core_Permission
::check('access all custom data')) {
496 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
497 // do not allow custom data for reports if user doesn't have
498 // permission to access custom data.
499 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
500 $this->_customGroupExtends
= array();
504 // merge custom data columns to _columns list, if any
505 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
507 // add / modify display columns, filters ..etc
508 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
510 //assign currencyColumn variable to tpl
511 $this->assign('currencyColumn', $this->_currencyColumn
);
515 * Shared pre-process function.
517 * If overriding preProcess function this should still be called.
521 public function preProcessCommon() {
523 = CRM_Utils_Request
::retrieve(
526 CRM_Core_DAO
::$_nullObject
529 $this->_dashBoardRowCount
530 = CRM_Utils_Request
::retrieve(
533 CRM_Core_DAO
::$_nullObject
536 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
538 $this->assign('section', $this->_section
);
539 CRM_Core_Region
::instance('page-header')->add(array(
540 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
542 if (!$this->noController
) {
543 $this->setID($this->get('instanceId'));
546 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
548 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
552 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
553 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
554 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
558 $this->assign('instanceId', $this->_id
);
559 $params = array('id' => $this->_id
);
560 $this->_instanceValues
= array();
561 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
563 $this->_instanceValues
565 if (empty($this->_instanceValues
)) {
566 CRM_Core_Error
::fatal("Report could not be loaded.");
568 $this->_title
= $this->_instanceValues
['title'];
569 if (!empty($this->_instanceValues
['permission']) &&
570 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
571 CRM_Core_Permission
::check('administer Reports')
574 CRM_Utils_System
::permissionDenied();
575 CRM_Utils_System
::civiExit();
578 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
580 $this->_formValues
= unserialize($formValues);
583 $this->_formValues
= NULL;
586 $this->setOutputMode();
588 if ($this->_outputMode
== 'copy') {
589 $this->_createNew
= TRUE;
590 $this->_params
= $this->_formValues
;
591 $this->_params
['view_mode'] = 'criteria';
592 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
593 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
594 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
596 // Do not pass go. Do not collect another chance to re-run the same query.
597 CRM_Report_Form_Instance
::postProcess($this);
600 // lets always do a force if reset is found in the url.
601 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
602 // in the comment line above these 2.
603 if (!empty($_REQUEST['reset'])
604 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
609 $this->assign('mode', 'instance');
611 elseif (!$this->noController
) {
612 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
613 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
614 if (($instanceCount > 0) && $optionValueID) {
615 $this->assign('instanceUrl',
616 CRM_Utils_System
::url('civicrm/report/list',
617 "reset=1&ovid=$optionValueID"
621 if ($optionValueID) {
622 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
626 $this->assign('mode', 'template');
629 // lets display the Report Settings section
630 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
632 // Do not display Report Settings section if administer Reports permission is absent OR
633 // if report instance is reserved and administer reserved reports absent
634 if (!CRM_Core_Permission
::check('administer Reports') ||
635 ($this->_instanceValues
['is_reserved'] &&
636 !CRM_Core_Permission
::check('administer reserved reports'))
638 $this->_instanceForm
= FALSE;
641 $this->assign('criteriaForm', FALSE);
642 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
643 if (CRM_Core_Permission
::check('administer Reports') ||
644 CRM_Core_Permission
::check('access Report Criteria')
646 if (!$this->_instanceValues
['is_reserved'] ||
647 CRM_Core_Permission
::check('administer reserved reports')
649 $this->assign('criteriaForm', TRUE);
650 $this->_criteriaForm
= TRUE;
654 // Special permissions check for private instance if it's not the current contact instance
656 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
657 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
658 if (!CRM_Core_Permission
::check('access all private reports')) {
659 $this->_instanceForm
= FALSE;
660 $this->assign('criteriaForm', FALSE);
664 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
665 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
666 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
667 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
673 public function addBreadCrumb() {
677 'title' => ts('Report Templates'),
678 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
682 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
686 * Pre process function.
688 * Called prior to build form.
690 public function preProcess() {
691 $this->preProcessCommon();
694 $this->addBreadCrumb();
697 foreach ($this->_columns
as $tableName => $table) {
699 if (!isset($table['alias'])) {
700 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
704 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
707 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
709 $daoOrBaoName = NULL;
710 // higher preference to bao object
711 if (array_key_exists('bao', $table)) {
712 $daoOrBaoName = $table['bao'];
713 $expFields = $daoOrBaoName::exportableFields();
715 elseif (array_key_exists('dao', $table)) {
716 $daoOrBaoName = $table['dao'];
717 $expFields = $daoOrBaoName::export();
720 $expFields = array();
723 $doNotCopy = array('required');
725 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
726 foreach ($fieldGroups as $fieldGrp) {
727 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
728 foreach ($table[$fieldGrp] as $fieldName => $field) {
729 // $name is the field name used to reference the BAO/DAO export fields array
730 $name = isset($field['name']) ?
$field['name'] : $fieldName;
732 // Sometimes the field name key in the BAO/DAO export fields array is
733 // different from the actual database field name.
734 // Unset $field['name'] so that actual database field name can be obtained
735 // from the BAO/DAO export fields array.
736 unset($field['name']);
738 if (array_key_exists($name, $expFields)) {
739 foreach ($doNotCopy as $dnc) {
740 // unset the values we don't want to be copied.
741 unset($expFields[$name][$dnc]);
744 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
747 foreach ($expFields[$name] as $property => $val) {
748 if (!array_key_exists($property, $field)) {
749 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
756 if (!empty($field['no_repeat'])) {
757 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
759 if (!empty($field['no_display'])) {
760 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
763 // set alias = table-name, unless already set
764 $alias = isset($field['alias']) ?
$field['alias'] : (
765 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
767 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
769 // set name = fieldName, unless already set
770 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
771 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
774 // set dbAlias = alias.name, unless already set
775 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
776 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
778 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
781 // a few auto fills for filters
782 if ($fieldGrp == 'filters') {
783 // fill operator types
784 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
785 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
786 case CRM_Utils_Type
::T_MONEY
:
787 case CRM_Utils_Type
::T_FLOAT
:
788 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
791 case CRM_Utils_Type
::T_INT
:
792 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
795 case CRM_Utils_Type
::T_DATE
:
796 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
799 case CRM_Utils_Type
::T_BOOLEAN
:
800 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
801 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
802 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
813 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
815 // with multiple options operator-type is generally multi-select
816 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
817 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
819 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
830 // copy filters to a separate handy variable
831 if (array_key_exists('filters', $table)) {
832 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
835 if (array_key_exists('group_bys', $table)) {
836 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
839 if (array_key_exists('fields', $table)) {
840 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
845 $this->setDefaultValues(FALSE);
848 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
849 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
850 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
851 CRM_Report_Utils_Get
::processChart($this->_defaults
);
854 $this->_formValues
= $this->_defaults
;
855 $this->postProcess();
860 * Set default values.
862 * @param bool $freeze
866 public function setDefaultValues($freeze = TRUE) {
867 $freezeGroup = array();
869 // FIXME: generalizing form field naming conventions would reduce
870 // Lots of lines below.
871 foreach ($this->_columns
as $tableName => $table) {
872 if (array_key_exists('fields', $table)) {
873 foreach ($table['fields'] as $fieldName => $field) {
874 if (empty($field['no_display'])) {
875 if (isset($field['required'])) {
877 $this->_defaults
['fields'][$fieldName] = 1;
880 // find element object, so that we could use quickform's freeze method
881 // for required elements
882 $obj = $this->getElementFromGroup("fields", $fieldName);
884 $freezeGroup[] = $obj;
888 elseif (isset($field['default'])) {
889 $this->_defaults
['fields'][$fieldName] = $field['default'];
895 if (array_key_exists('group_bys', $table)) {
896 foreach ($table['group_bys'] as $fieldName => $field) {
897 if (isset($field['default'])) {
898 if (!empty($field['frequency'])) {
899 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
901 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
905 if (array_key_exists('filters', $table)) {
906 foreach ($table['filters'] as $fieldName => $field) {
907 if (isset($field['default'])) {
908 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
910 if (is_array($field['default'])) {
911 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
912 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
913 $this->_defaults
["{$fieldName}_relative"] = 0;
916 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
920 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
921 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
922 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
924 $this->_defaults
["{$fieldName}_value"] = $field['default'];
927 //assign default value as "in" for multiselect
928 //operator, To freeze the select element
929 if (CRM_Utils_Array
::value('operatorType', $field) ==
930 CRM_Report_Form
::OP_MULTISELECT
932 $this->_defaults
["{$fieldName}_op"] = 'in';
934 if (CRM_Utils_Array
::value('operatorType', $field) ==
935 CRM_Report_Form
::OP_ENTITYREF
937 $this->_defaults
["{$fieldName}_op"] = 'in';
939 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
940 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
942 $this->_defaults
["{$fieldName}_op"] = 'mhas';
944 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
945 $this->_defaults
["{$fieldName}_op"] = $op;
951 empty($this->_formValues
['order_bys']) &&
952 (array_key_exists('order_bys', $table) &&
953 is_array($table['order_bys']))
955 if (!array_key_exists('order_bys', $this->_defaults
)) {
956 $this->_defaults
['order_bys'] = array();
958 foreach ($table['order_bys'] as $fieldName => $field) {
959 if (!empty($field['default']) ||
!empty($field['default_order']) ||
960 CRM_Utils_Array
::value('default_is_section', $field) ||
961 !empty($field['default_weight'])
964 'column' => $fieldName,
965 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
966 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
969 if (!empty($field['default_weight'])) {
970 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
973 array_unshift($this->_defaults
['order_bys'], $order_by);
979 foreach ($this->_options
as $fieldName => $field) {
980 if (isset($field['default'])) {
981 $this->_defaults
['options'][$fieldName] = $field['default'];
986 if (!empty($this->_submitValues
)) {
987 $this->preProcessOrderBy($this->_submitValues
);
990 $this->preProcessOrderBy($this->_defaults
);
993 // lets finish freezing task here itself
994 if (!empty($freezeGroup)) {
995 foreach ($freezeGroup as $elem) {
1000 if ($this->_formValues
) {
1001 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1004 if ($this->_instanceValues
) {
1005 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1008 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1010 return $this->_defaults
;
1014 * Get element from group.
1016 * @param string $group
1017 * @param string $grpFieldName
1021 public function getElementFromGroup($group, $grpFieldName) {
1022 $eleObj = $this->getElement($group);
1023 foreach ($eleObj->_elements
as $index => $obj) {
1024 if ($grpFieldName == $obj->_attributes
['name']) {
1032 * Setter for $_params.
1034 * @param array $params
1036 public function setParams($params) {
1037 $this->_params
= $params;
1043 * @param int $instanceID
1045 public function setID($instanceID) {
1046 $this->_id
= $instanceID;
1050 * Setter for $_force.
1052 * @param bool $isForce
1054 public function setForce($isForce) {
1055 $this->_force
= $isForce;
1059 * Setter for $_limitValue.
1061 * @param int $_limitValue
1063 public function setLimitValue($_limitValue) {
1064 $this->_limitValue
= $_limitValue;
1068 * Setter for $_offsetValue.
1070 * @param int $_offsetValue
1072 public function setOffsetValue($_offsetValue) {
1073 $this->_offsetValue
= $_offsetValue;
1077 * Setter for $addPaging.
1079 * @param bool $value
1081 public function setAddPaging($value) {
1082 $this->addPaging
= $value;
1086 * Getter for $_defaultValues.
1090 public function getDefaultValues() {
1091 return $this->_defaults
;
1095 * Add columns to report.
1097 public function addColumns() {
1100 foreach ($this->_columns
as $tableName => $table) {
1101 if (array_key_exists('fields', $table)) {
1102 foreach ($table['fields'] as $fieldName => $field) {
1104 if (empty($field['no_display'])) {
1105 foreach (array('table', 'field') as $var) {
1106 if (!empty($
{$var}['grouping'])) {
1107 if (!is_array($
{$var}['grouping'])) {
1108 $tableName = $
{$var}['grouping'];
1111 $tableName = array_keys($
{$var}['grouping']);
1112 $tableName = $tableName[0];
1113 $groupTitle = array_values($
{$var}['grouping']);
1114 $groupTitle = $groupTitle[0];
1119 if (!$groupTitle && isset($table['group_title'])) {
1120 $groupTitle = $table['group_title'];
1121 // Having a group_title is secret code for being a custom group
1122 // which cryptically translates to needing an accordion.
1123 // here we make that explicit.
1124 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1127 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1128 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1129 $colGroups[$tableName]['group_title'] = $groupTitle;
1131 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1137 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1138 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1140 if (!empty($colGroups)) {
1141 $this->tabs
['FieldSelection'] = array(
1142 'title' => ts('Columns'),
1143 'tpl' => 'FieldSelection',
1144 'div_label' => 'col-groups',
1147 // Note this assignment is only really required in buildForm. It is being 'over-called'
1148 // to reduce risk of being missed due to overridden functions.
1149 $this->assign('tabs', $this->tabs
);
1152 $this->assign('colGroups', $colGroups);
1156 * Add filters to report.
1158 public function addFilters() {
1159 $filters = $filterGroups = array();
1162 foreach ($this->_filters
as $table => $attributes) {
1163 if (isset($this->_columns
[$table]['group_title'])) {
1164 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1165 // which magically means to 'display in an accordian'
1166 // here we make this explicit.
1167 $filterGroups[$table] = array(
1168 'group_title' => $this->_columns
[$table]['group_title'],
1169 'use_accordian_for_field_selection' => TRUE,
1173 foreach ($attributes as $fieldName => $field) {
1174 // get ready with option value pair
1175 // @ 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
1177 $operations = $this->getOperationPair(
1178 CRM_Utils_Array
::value('operatorType', $field),
1181 $filters[$table][$fieldName] = $field;
1183 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1184 case CRM_Report_Form
::OP_MONTH
:
1185 if (!array_key_exists('options', $field) ||
1186 !is_array($field['options']) ||
empty($field['options'])
1188 // If there's no option list for this filter, define one.
1189 $field['options'] = array(
1191 2 => ts('February'),
1198 9 => ts('September'),
1199 10 => ts('October'),
1200 11 => ts('November'),
1201 12 => ts('December'),
1203 // Add this option list to this column _columns. This is
1204 // required so that filter statistics show properly.
1205 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1207 case CRM_Report_Form
::OP_MULTISELECT
:
1208 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1209 // assume a multi-select field
1210 if (!empty($field['options']) ||
1211 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1213 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1214 if (count($operations) <= 1) {
1217 if ($fieldName == 'state_province_id' ||
1218 $fieldName == 'county_id'
1220 $this->addChainSelect($fieldName . '_value', array(
1227 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1228 'style' => 'min-width:250px',
1229 'class' => 'crm-select2 huge',
1231 'placeholder' => ts('- select -'),
1237 case CRM_Report_Form
::OP_SELECT
:
1238 // assume a select field
1239 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1240 if (!empty($field['options'])) {
1241 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1245 case CRM_Report_Form
::OP_ENTITYREF
:
1246 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1247 $this->setEntityRefDefaults($field, $table);
1248 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1251 case CRM_Report_Form
::OP_DATE
:
1252 // build datetime fields
1253 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1257 case CRM_Report_Form
::OP_DATETIME
:
1258 // build datetime fields
1259 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1263 case CRM_Report_Form
::OP_INT
:
1264 case CRM_Report_Form
::OP_FLOAT
:
1265 // and a min value input box
1266 $this->add('text', "{$fieldName}_min", ts('Min'));
1267 // and a max value input box
1268 $this->add('text', "{$fieldName}_max", ts('Max'));
1270 // default type is string
1271 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1272 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1274 // we need text box for value input
1275 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1280 if (!empty($filters)) {
1281 $this->tabs
['Filters'] = array(
1282 'title' => ts('Filters'),
1284 'div_label' => 'set-filters',
1287 $this->assign('filters', $filters);
1288 $this->assign('filterGroups', $filterGroups);
1292 * Function to assign the tabs to the template in the correct order.
1294 * We want the tabs to wind up in this order (if not overridden).
1302 protected function assignTabs() {
1310 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1311 $order = array_merge($order, $this->tabs
);
1312 $this->assign('tabs', $order);
1316 * The intent is to add a tab for developers to view the sql.
1318 * Currently using dpm.
1320 * @param string $sql
1322 protected function addToDeveloperTab($sql) {
1323 if (!CRM_Core_Permission
::check('view report sql')) {
1326 $this->tabs
['Developer'] = array(
1327 'title' => ts('Developer'),
1328 'tpl' => 'Developer',
1329 'div_label' => 'set-developer',
1332 $this->assignTabs();
1333 $this->sqlArray
[] = $sql;
1334 foreach ($this->sqlArray
as $sql) {
1335 foreach (array('LEFT JOIN') as $term) {
1336 $sql = str_replace($term, '<br>  ' . $term, $sql);
1338 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1339 $sql = str_replace($term, '<br><br>' . $term, $sql);
1341 $this->sqlFormattedArray
[] = $sql;
1342 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1347 * Add options defined in $this->_options to the report.
1349 public function addOptions() {
1350 if (!empty($this->_options
)) {
1351 // FIXME: For now lets build all elements as checkboxes.
1352 // Once we clear with the format we can build elements based on type
1354 foreach ($this->_options
as $fieldName => $field) {
1357 if ($field['type'] == 'select') {
1358 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1360 elseif ($field['type'] == 'checkbox') {
1361 $options[$field['title']] = $fieldName;
1362 $this->addCheckBox($fieldName, NULL,
1364 NULL, NULL, NULL, $this->_fourColumnAttribute
1369 if (!empty($this->_options
) &&
1371 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1373 $this->tabs
['ReportOptions'] = array(
1374 'title' => ts('Display Options'),
1375 'tpl' => 'ReportOptions',
1376 'div_label' => 'other-options',
1379 $this->assign('otherOptions', $this->_options
);
1383 * Add chart options to the report.
1385 public function addChartOptions() {
1386 if (!empty($this->_charts
)) {
1387 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1388 $this->assign('charts', $this->_charts
);
1389 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1394 * Add group by options to the report.
1396 public function addGroupBys() {
1397 $options = $freqElements = array();
1399 foreach ($this->_columns
as $tableName => $table) {
1400 if (array_key_exists('group_bys', $table)) {
1401 foreach ($table['group_bys'] as $fieldName => $field) {
1402 if (!empty($field)) {
1403 $options[$field['title']] = $fieldName;
1404 if (!empty($field['frequency'])) {
1405 $freqElements[$field['title']] = $fieldName;
1411 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1412 NULL, NULL, NULL, $this->_fourColumnAttribute
1414 $this->assign('groupByElements', $options);
1415 if (!empty($options)) {
1416 $this->tabs
['GroupBy'] = array(
1417 'title' => ts('Grouping'),
1419 'div_label' => 'group-by-elements',
1423 foreach ($freqElements as $name) {
1424 $this->addElement('select', "group_bys_freq[$name]",
1425 ts('Frequency'), $this->_groupByDateFreq
1431 * Add data for order by tab.
1433 public function addOrderBys() {
1435 foreach ($this->_columns
as $tableName => $table) {
1437 // Report developer may define any column to order by; include these as order-by options.
1438 if (array_key_exists('order_bys', $table)) {
1439 foreach ($table['order_bys'] as $fieldName => $field) {
1440 if (!empty($field)) {
1441 $options[$fieldName] = $field['title'];
1446 // Add searchable custom fields as order-by options, if so requested
1447 // (These are already indexed, so allowing to order on them is cheap.)
1449 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1450 array_key_exists('extends', $table) && !empty($table['extends'])
1452 foreach ($table['fields'] as $fieldName => $field) {
1453 if (empty($field['no_display'])) {
1454 $options[$fieldName] = $field['title'];
1462 $this->assign('orderByOptions', $options);
1463 if (!empty($options)) {
1464 $this->tabs
['OrderBy'] = array(
1465 'title' => ts('Sorting'),
1467 'div_label' => 'order-by-elements',
1471 if (!empty($options)) {
1473 '-' => ' - none - ',
1475 for ($i = 1; $i <= 5; $i++
) {
1476 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1477 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1478 'ASC' => ts('Ascending'),
1479 'DESC' => ts('Descending'),
1481 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1482 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1488 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1490 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1491 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1494 public function buildInstanceAndButtons() {
1495 CRM_Report_Form_Instance
::buildForm($this);
1496 $this->_actionButtonName
= $this->getButtonName('submit');
1497 $this->addTaskMenu($this->getActions($this->_id
));
1499 $this->assign('instanceForm', $this->_instanceForm
);
1501 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1502 $permission = CRM_Core_Permission
::getPermission();
1503 if ($permission == CRM_Core_Permission
::EDIT
&&
1504 $this->_add2groupSupported
1506 $this->addElement('select', 'groups', ts('Group'),
1507 array('' => ts('Add Contacts to Group')) +
1508 CRM_Core_PseudoConstant
::nestedGroup(),
1509 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1511 $this->assign('group', TRUE);
1514 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1516 $this->addChartOptions();
1517 $showResultsLabel = $this->getResultsLabel();
1518 $this->addButtons(array(
1521 'name' => $showResultsLabel,
1522 'isDefault' => TRUE,
1529 * Has this form been submitted already?
1533 public function resultsDisplayed() {
1534 $buttonName = $this->controller
->getButtonName();
1535 return ($buttonName ||
$this->_outputMode
);
1539 * Get the actions for this report instance.
1541 * @param int $instanceId
1545 protected function getActions($instanceId) {
1546 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1547 if (empty($instanceId)) {
1548 $actions['report_instance.save'] = array(
1549 'title' => ts('Create Report'),
1551 'is_confirm' => TRUE,
1552 'confirm_title' => ts('Create Report'),
1553 'confirm_refresh_fields' => json_encode(array(
1554 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1555 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1561 if (!$this->_csvSupported
) {
1562 unset($actions['report_instance.csv']);
1569 * Main build form function.
1571 public function buildQuickForm() {
1572 $this->addColumns();
1574 $this->addFilters();
1576 $this->addOptions();
1578 $this->addGroupBys();
1580 $this->addOrderBys();
1582 $this->buildInstanceAndButtons();
1584 // Add form rule for report.
1585 if (is_callable(array(
1589 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1591 $this->assignTabs();
1595 * A form rule function for custom data.
1597 * The rule ensures that fields selected in group_by if any) should only be the ones
1598 * present in display/select fields criteria;
1599 * note: works if and only if any custom field selected in group_by.
1601 * @param array $fields
1602 * @param array $ignoreFields
1606 public function customDataFormRule($fields, $ignoreFields = array()) {
1608 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1609 !empty($fields['group_bys'])
1611 foreach ($this->_columns
as $tableName => $table) {
1612 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1613 substr($tableName, 0, 12) == 'custom_value') &&
1614 !empty($this->_columns
[$tableName]['fields'])
1616 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1617 if (array_key_exists($fieldName, $fields['group_bys']) &&
1618 !array_key_exists($fieldName, $fields['fields'])
1620 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1622 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1623 foreach ($fields['fields'] as $fld => $val) {
1624 if (!array_key_exists($fld, $fields['group_bys']) &&
1625 !in_array($fld, $ignoreFields)
1627 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1639 * Get operators to display on form.
1641 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1643 * @param string $type
1644 * @param string $fieldName
1648 public function getOperationPair($type = "string", $fieldName = NULL) {
1649 // FIXME: At some point we should move these key-val pairs
1650 // to option_group and option_value table.
1652 case CRM_Report_Form
::OP_INT
:
1653 case CRM_Report_Form
::OP_FLOAT
:
1656 'lte' => ts('Is less than or equal to'),
1657 'gte' => ts('Is greater than or equal to'),
1658 'bw' => ts('Is between'),
1659 'eq' => ts('Is equal to'),
1660 'lt' => ts('Is less than'),
1661 'gt' => ts('Is greater than'),
1662 'neq' => ts('Is not equal to'),
1663 'nbw' => ts('Is not between'),
1664 'nll' => ts('Is empty (Null)'),
1665 'nnll' => ts('Is not empty (Null)'),
1669 case CRM_Report_Form
::OP_SELECT
:
1671 'eq' => ts('Is equal to'),
1675 case CRM_Report_Form
::OP_MONTH
:
1676 case CRM_Report_Form
::OP_MULTISELECT
:
1677 case CRM_Report_Form
::OP_ENTITYREF
:
1680 'in' => ts('Is one of'),
1681 'notin' => ts('Is not one of'),
1685 case CRM_Report_Form
::OP_DATE
:
1688 'nll' => ts('Is empty (Null)'),
1689 'nnll' => ts('Is not empty (Null)'),
1693 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1694 // use this operator for the values, concatenated with separator. For e.g if
1695 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1697 'mhas' => ts('Is one of'),
1698 'mnot' => ts('Is not one of'),
1705 'has' => ts('Contains'),
1706 'sw' => ts('Starts with'),
1707 'ew' => ts('Ends with'),
1708 'nhas' => ts('Does not contain'),
1709 'eq' => ts('Is equal to'),
1710 'neq' => ts('Is not equal to'),
1711 'nll' => ts('Is empty (Null)'),
1712 'nnll' => ts('Is not empty (Null)'),
1719 * Build the tag filter field to display on the filters tab.
1721 public function buildTagFilter() {
1722 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1723 if (!empty($contactTags)) {
1724 $this->_columns
['civicrm_tag'] = array(
1725 'dao' => 'CRM_Core_DAO_Tag',
1729 'title' => ts('Tag'),
1730 'type' => CRM_Utils_Type
::T_INT
,
1732 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1733 'options' => $contactTags,
1741 * Adds group filters to _columns (called from _Construct).
1743 public function buildGroupFilter() {
1744 $this->_columns
['civicrm_group']['filters'] = array(
1746 'name' => 'group_id',
1747 'title' => ts('Group'),
1748 'type' => CRM_Utils_Type
::T_INT
,
1749 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1751 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1754 if (empty($this->_columns
['civicrm_group']['dao'])) {
1755 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1757 if (empty($this->_columns
['civicrm_group']['alias'])) {
1758 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1763 * Get SQL operator from form text version.
1765 * @param string $operator
1769 public function getSQLOperator($operator = "like") {
1770 switch ($operator) {
1803 return 'IS NOT NULL';
1812 * Generate where clause.
1814 * This can be overridden in reports for special treatment of a field
1816 * @param array $field Field specifications
1817 * @param string $op Query operator (not an exact match to sql)
1818 * @param mixed $value
1822 * @return null|string
1824 public function whereClause(&$field, $op, $value, $min, $max) {
1826 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1828 // CRM-18010: Ensure type of each report filters
1830 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1837 if (($min !== NULL && strlen($min) > 0) ||
1838 ($max !== NULL && strlen($max) > 0)
1842 $min = CRM_Utils_Type
::escape($min, $type);
1844 $clauses[] = "( {$field['dbAlias']} >= $min )";
1847 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1851 $max = CRM_Utils_Type
::escape($max, $type);
1853 $clauses[] = "( {$field['dbAlias']} <= $max )";
1856 $clauses[] = "( {$field['dbAlias']} > $max )";
1860 if (!empty($clauses)) {
1862 $clause = implode(' AND ', $clauses);
1865 $clause = '(' . implode('OR', $clauses) . ')';
1873 if ($value !== NULL && strlen($value) > 0) {
1874 $value = CRM_Utils_Type
::escape($value, $type);
1875 if (strpos($value, '%') === FALSE) {
1876 $value = "'%{$value}%'";
1879 $value = "'{$value}'";
1881 $sqlOP = $this->getSQLOperator($op);
1882 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1888 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1889 $value = explode(',', $value);
1891 if ($value !== NULL && is_array($value) && count($value) > 0) {
1892 $sqlOP = $this->getSQLOperator($op);
1893 if (CRM_Utils_Array
::value('type', $field) ==
1894 CRM_Utils_Type
::T_STRING
1896 //cycle through selections and escape values
1897 foreach ($value as $key => $selection) {
1898 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1901 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1905 // for numerical values
1906 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1909 if ($op == 'notin') {
1910 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1913 $clause = "( " . $clause . " )";
1920 // multiple has or multiple not
1921 if ($value !== NULL && count($value) > 0) {
1922 $value = CRM_Utils_Type
::escapeAll($value, $type);
1923 $operator = $op == 'mnot' ?
'NOT' : '';
1924 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1925 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1931 if ($value !== NULL && strlen($value) > 0) {
1932 $value = CRM_Utils_Type
::escape($value, $type);
1933 if (strpos($value, '%') === FALSE) {
1935 $value = "'{$value}%'";
1938 $value = "'%{$value}'";
1942 $value = "'{$value}'";
1944 $sqlOP = $this->getSQLOperator($op);
1945 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1951 $sqlOP = $this->getSQLOperator($op);
1952 $clause = "( {$field['dbAlias']} $sqlOP )";
1958 //CRM-18457: some custom field passes value in array format against binary operator
1959 if (is_array($value) && count($value)) {
1964 if ($value !== NULL && $value !== '') {
1965 if (isset($field['clause'])) {
1966 // FIXME: we not doing escape here. Better solution is to use two
1967 // different types - data-type and filter-type
1968 $clause = $field['clause'];
1970 elseif (!is_array($value)) {
1971 $value = CRM_Utils_Type
::escape($value, $type);
1972 $sqlOP = $this->getSQLOperator($op);
1973 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1974 $value = "'{$value}'";
1976 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1982 if (!empty($field['group']) && $clause) {
1983 $clause = $this->whereGroupClause($field, $value, $op);
1985 elseif (!empty($field['tag']) && $clause) {
1986 // not using left join in query because if any contact
1987 // belongs to more than one tag, results duplicate
1989 $clause = $this->whereTagClause($field, $value, $op);
1991 elseif (!empty($field['membership_org']) && $clause) {
1992 $clause = $this->whereMembershipOrgClause($value, $op);
1994 elseif (!empty($field['membership_type']) && $clause) {
1995 $clause = $this->whereMembershipTypeClause($value, $op);
2001 * Get SQL where clause for a date field.
2003 * @param string $fieldName
2004 * @param string $relative
2005 * @param string $from
2007 * @param string $type
2008 * @param string $fromTime
2009 * @param string $toTime
2011 * @return null|string
2013 public function dateClause(
2015 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2018 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2019 $sqlOP = $this->getSQLOperator($relative);
2020 return "( {$fieldName} {$sqlOP} )";
2023 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2026 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2027 $clauses[] = "( {$fieldName} >= $from )";
2031 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2032 $clauses[] = "( {$fieldName} <= {$to} )";
2035 if (!empty($clauses)) {
2036 return implode(' AND ', $clauses);
2043 * Get values for from and to for date ranges.
2045 * @param bool $relative
2046 * @param string $from
2048 * @param string $fromTime
2049 * @param string $toTime
2053 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2054 if (empty($toTime)) {
2057 //FIX ME not working for relative
2059 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2060 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2061 $from = substr($dateRange['from'], 0, 8);
2062 //Take only Date Part, Sometime Time part is also present in 'to'
2063 $to = substr($dateRange['to'], 0, 8);
2065 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2066 $to = CRM_Utils_Date
::processDate($to, $toTime);
2067 return array($from, $to);
2071 * Alter display of rows.
2073 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2074 * such as rendering contacts as links.
2076 * @param array $rows
2077 * Rows generated by SQL, with an array for each row.
2079 public function alterDisplay(&$rows) {
2083 * Alter the way in which custom data fields are displayed.
2085 * @param array $rows
2087 public function alterCustomDataDisplay(&$rows) {
2088 // custom code to alter rows having custom values
2089 if (empty($this->_customGroupExtends
)) {
2093 $customFields = array();
2094 $customFieldIds = array();
2095 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2096 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2097 $customFieldIds[$fieldAlias] = $fieldId;
2100 if (empty($customFieldIds)) {
2104 // skip for type date and ContactReference since date format is already handled
2106 SELECT cg.table_name, cf.id
2107 FROM civicrm_custom_field cf
2108 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2109 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2110 cg.is_active = 1 AND
2111 cf.is_active = 1 AND
2112 cf.is_searchable = 1 AND
2113 cf.data_type NOT IN ('ContactReference', 'Date') AND
2114 cf.id IN (" . implode(",", $customFieldIds) . ")";
2116 $dao = CRM_Core_DAO
::executeQuery($query);
2117 while ($dao->fetch()) {
2118 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2122 $entryFound = FALSE;
2123 foreach ($rows as $rowNum => $row) {
2124 foreach ($row as $tableCol => $val) {
2125 if (array_key_exists($tableCol, $customFields)) {
2126 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2131 // skip looking further in rows, if first row itself doesn't
2132 // have the column we need
2140 * Remove duplicate rows.
2142 * @param array $rows
2144 public function removeDuplicates(&$rows) {
2145 if (empty($this->_noRepeats
)) {
2148 $checkList = array();
2150 foreach ($rows as $key => $list) {
2151 foreach ($list as $colName => $colVal) {
2152 if (array_key_exists($colName, $checkList) &&
2153 $checkList[$colName] == $colVal
2155 $rows[$key][$colName] = "";
2157 if (in_array($colName, $this->_noRepeats
)) {
2158 $checkList[$colName] = $colVal;
2165 * Fix subtotal display.
2168 * @param array $fields
2169 * @param bool $subtotal
2171 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2172 foreach ($row as $colName => $colVal) {
2173 if (in_array($colName, $fields)) {
2175 elseif (isset($this->_columnHeaders
[$colName])) {
2177 $row[$colName] = 'Subtotal';
2181 unset($row[$colName]);
2188 * Calculate grant total.
2190 * @param array $rows
2194 public function grandTotal(&$rows) {
2195 if (!$this->_rollup ||
count($rows) == 1) {
2199 $this->moveSummaryColumnsToTheRightHandSide();
2201 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2205 $this->rollupRow
= array_pop($rows);
2207 foreach ($this->_columnHeaders
as $fld => $val) {
2208 if (!in_array($fld, $this->_statFields
)) {
2209 if (!$this->_grandFlag
) {
2210 $this->rollupRow
[$fld] = ts('Grand Total');
2211 $this->_grandFlag
= TRUE;
2214 $this->rollupRow
[$fld] = "";
2219 $this->assign('grandStat', $this->rollupRow
);
2224 * Format display output.
2226 * @param array $rows
2227 * @param bool $pager
2229 public function formatDisplay(&$rows, $pager = TRUE) {
2230 // set pager based on if any limit was applied in the query.
2235 // allow building charts if any
2236 if (!empty($this->_params
['charts']) && !empty($rows)) {
2237 $this->buildChart($rows);
2238 $this->assign('chartEnabled', TRUE);
2239 $this->_chartId
= "{$this->_params['charts']}_" .
2240 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2242 $this->assign('chartId', $this->_chartId
);
2245 // unset columns not to be displayed.
2246 foreach ($this->_columnHeaders
as $key => $value) {
2247 if (!empty($value['no_display'])) {
2248 unset($this->_columnHeaders
[$key]);
2252 // unset columns not to be displayed.
2253 if (!empty($rows)) {
2254 foreach ($this->_noDisplay
as $noDisplayField) {
2255 foreach ($rows as $rowNum => $row) {
2256 unset($this->_columnHeaders
[$noDisplayField]);
2261 // build array of section totals
2262 $this->sectionTotals();
2264 // process grand-total row
2265 $this->grandTotal($rows);
2267 // use this method for formatting rows for display purpose.
2268 $this->alterDisplay($rows);
2269 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2271 // use this method for formatting custom rows for display purpose.
2272 $this->alterCustomDataDisplay($rows);
2278 * @param array $rows
2280 public function buildChart(&$rows) {
2281 // override this method for building charts.
2284 // select() method below has been added recently (v3.3), and many of the report templates might
2285 // still be having their own select() method. We should fix them as and when encountered and move
2286 // towards generalizing the select() method below.
2289 * Generate the SELECT clause and set class variable $_select.
2291 public function select() {
2292 $select = $this->_selectAliases
= array();
2294 foreach ($this->_columns
as $tableName => $table) {
2295 if (array_key_exists('fields', $table)) {
2296 foreach ($table['fields'] as $fieldName => $field) {
2297 if ($tableName == 'civicrm_address') {
2298 $this->_addressField
= TRUE;
2300 if ($tableName == 'civicrm_email') {
2301 $this->_emailField
= TRUE;
2303 if ($tableName == 'civicrm_phone') {
2304 $this->_phoneField
= TRUE;
2307 if (!empty($field['required']) ||
2308 !empty($this->_params
['fields'][$fieldName])
2311 // 1. In many cases we want select clause to be built in slightly different way
2312 // for a particular field of a particular type.
2313 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2315 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2316 if ($selectClause) {
2317 $select[] = $selectClause;
2321 // include statistics columns only if set
2322 if (!empty($field['statistics'])) {
2323 foreach ($field['statistics'] as $stat => $label) {
2324 $alias = "{$tableName}_{$fieldName}_{$stat}";
2325 switch (strtolower($stat)) {
2328 $select[] = "$stat({$field['dbAlias']}) as $alias";
2329 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2330 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2331 $this->_statFields
[$label] = $alias;
2332 $this->_selectAliases
[] = $alias;
2336 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2337 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2338 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2339 $this->_statFields
[$label] = $alias;
2340 $this->_selectAliases
[] = $alias;
2343 case 'count_distinct':
2344 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2345 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2346 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2347 $this->_statFields
[$label] = $alias;
2348 $this->_selectAliases
[] = $alias;
2352 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2353 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2354 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2355 $this->_statFields
[$label] = $alias;
2356 $this->_selectAliases
[] = $alias;
2362 $alias = "{$tableName}_{$fieldName}";
2363 $select[] = "{$field['dbAlias']} as $alias";
2364 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2365 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2366 $this->_selectAliases
[] = $alias;
2372 // select for group bys
2373 if (array_key_exists('group_bys', $table)) {
2374 foreach ($table['group_bys'] as $fieldName => $field) {
2376 if ($tableName == 'civicrm_address') {
2377 $this->_addressField
= TRUE;
2379 if ($tableName == 'civicrm_email') {
2380 $this->_emailField
= TRUE;
2382 if ($tableName == 'civicrm_phone') {
2383 $this->_phoneField
= TRUE;
2385 // 1. In many cases we want select clause to be built in slightly different way
2386 // for a particular field of a particular type.
2387 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2389 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2390 if ($selectClause) {
2391 $select[] = $selectClause;
2395 if (!empty($this->_params
['group_bys']) &&
2396 !empty($this->_params
['group_bys'][$fieldName]) &&
2397 !empty($this->_params
['group_bys_freq'])
2399 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2401 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2402 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2403 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2404 $field['title'] = 'Week';
2408 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2409 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2410 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2411 $field['title'] = 'Year';
2415 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2416 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2417 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2418 $field['title'] = 'Month';
2422 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2423 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2424 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2425 $field['title'] = 'Quarter';
2428 // for graphs and charts -
2429 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2430 $this->_interval
= $field['title'];
2431 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2432 = $field['title'] . ' Beginning';
2433 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2434 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2436 // just to make sure these values are transferred to rows.
2437 // since we 'll need them for calculation purpose,
2438 // e.g making subtotals look nicer or graphs
2439 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2440 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2447 $this->_selectClauses
= $select;
2448 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2452 * Build select clause for a single field.
2454 * @param string $tableName
2455 * @param string $tableKey
2456 * @param string $fieldName
2457 * @param string $field
2461 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2466 * Build where clause.
2468 public function where() {
2469 $this->storeWhereHavingClauseArray();
2471 if (empty($this->_whereClauses
)) {
2472 $this->_where
= "WHERE ( 1 ) ";
2473 $this->_having
= "";
2476 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2479 if ($this->_aclWhere
) {
2480 $this->_where
.= " AND {$this->_aclWhere} ";
2483 if (!empty($this->_havingClauses
)) {
2484 // use this clause to construct group by clause.
2485 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2490 * Store Where clauses into an array.
2492 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2493 * temp table that may not be part of the final where clause or added
2494 * in other functions
2496 public function storeWhereHavingClauseArray() {
2497 foreach ($this->_columns
as $tableName => $table) {
2498 if (array_key_exists('filters', $table)) {
2499 foreach ($table['filters'] as $fieldName => $field) {
2500 // respect pseudofield to filter spec so fields can be marked as
2501 // not to be handled here
2502 if (!empty($field['pseudofield'])) {
2506 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2507 if (CRM_Utils_Array
::value('operatorType', $field) ==
2508 CRM_Report_Form
::OP_MONTH
2510 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2511 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2512 if (is_array($value) && !empty($value)) {
2514 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2519 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2520 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2521 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2522 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2523 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2524 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2528 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2530 $clause = $this->whereClause($field,
2532 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2533 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2534 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2539 if (!empty($clause)) {
2540 if (!empty($field['having'])) {
2541 $this->_havingClauses
[] = $clause;
2544 $this->_whereClauses
[] = $clause;
2556 public function processReportMode() {
2557 $this->setOutputMode();
2560 = CRM_Utils_Request
::retrieve(
2563 CRM_Core_DAO
::$_nullObject
2566 $this->_absoluteUrl
= FALSE;
2568 $this->assign('printOnly', FALSE);
2570 if ($this->_outputMode
== 'print' ||
2571 ($this->_sendmail
&& !$this->_outputMode
)
2573 $this->assign('printOnly', TRUE);
2575 $this->addPaging
= FALSE;
2576 $this->assign('outputMode', 'print');
2577 $this->_outputMode
= 'print';
2578 if ($this->_sendmail
) {
2579 $this->_absoluteUrl
= TRUE;
2582 elseif ($this->_outputMode
== 'pdf') {
2584 $this->addPaging
= FALSE;
2585 $this->_absoluteUrl
= TRUE;
2587 elseif ($this->_outputMode
== 'csv') {
2589 $this->_absoluteUrl
= TRUE;
2590 $this->addPaging
= FALSE;
2592 elseif ($this->_outputMode
== 'group') {
2593 $this->assign('outputMode', 'group');
2595 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2596 $this->assign('outputMode', 'create_report');
2598 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2599 $this->_createNew
= TRUE;
2602 $this->assign('outputMode', $this->_outputMode
);
2603 $this->assign('printOnly', $printOnly);
2604 // Get today's date to include in printed reports
2606 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2607 $this->assign('reportDate', $reportDate);
2612 * Post Processing function for Form.
2614 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2615 * This function is not accessed when the api calls the report.
2617 public function beginPostProcess() {
2618 $this->setParams($this->controller
->exportValues($this->_name
));
2619 if (empty($this->_params
) &&
2622 $this->setParams($this->_formValues
);
2625 // hack to fix params when submitted from dashboard, CRM-8532
2626 // fields array is missing because form building etc is skipped
2627 // in dashboard mode for report
2628 //@todo - this could be done in the dashboard no we have a setter
2629 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2630 $this->setParams($this->_formValues
);
2633 $this->processReportMode();
2635 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2636 $this->_createNew
= ($this->_outputMode
== 'copy');
2637 CRM_Report_Form_Instance
::postProcess($this);
2639 if ($this->_outputMode
== 'delete') {
2640 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2643 $this->_formValues
= $this->_params
;
2645 $this->beginPostProcessCommon();
2649 * BeginPostProcess function run in both report mode and non-report mode (api).
2651 public function beginPostProcessCommon() {
2655 * Build the report query.
2657 * @param bool $applyLimit
2661 public function buildQuery($applyLimit = TRUE) {
2662 $this->buildGroupTempTable();
2665 $this->customDataFrom();
2667 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2668 $this->getPermissionedFTQuery($this);
2673 // order_by columns not selected for display need to be included in SELECT
2674 $unselectedSectionColumns = $this->unselectedSectionColumns();
2675 foreach ($unselectedSectionColumns as $alias => $section) {
2676 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2679 if ($applyLimit && empty($this->_params
['charts'])) {
2682 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2684 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2685 $this->addToDeveloperTab($sql);
2690 * Build group by clause.
2692 public function groupBy() {
2693 $groupBys = array();
2694 if (!empty($this->_params
['group_bys']) &&
2695 is_array($this->_params
['group_bys'])
2697 foreach ($this->_columns
as $tableName => $table) {
2698 if (array_key_exists('group_bys', $table)) {
2699 foreach ($table['group_bys'] as $fieldName => $field) {
2700 if (!empty($this->_params
['group_bys'][$fieldName])) {
2701 $groupBys[] = $field['dbAlias'];
2708 if (!empty($groupBys)) {
2709 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBys);
2714 * Build order by clause.
2716 public function orderBy() {
2717 $this->_orderBy
= "";
2718 $this->_sections
= array();
2719 $this->storeOrderByArray();
2720 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2721 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2723 $this->assign('sections', $this->_sections
);
2727 * Extract order by fields and store as an array.
2729 * In some cases other functions want to know which fields are selected for ordering by
2730 * Separating this into a separate function allows it to be called separately from constructing
2731 * the order by clause
2733 public function storeOrderByArray() {
2734 $orderBys = array();
2736 if (!empty($this->_params
['order_bys']) &&
2737 is_array($this->_params
['order_bys']) &&
2738 !empty($this->_params
['order_bys'])
2741 // Process order_bys in user-specified order
2742 foreach ($this->_params
['order_bys'] as $orderBy) {
2743 $orderByField = array();
2744 foreach ($this->_columns
as $tableName => $table) {
2745 if (array_key_exists('order_bys', $table)) {
2746 // For DAO columns defined in $this->_columns
2747 $fields = $table['order_bys'];
2749 elseif (array_key_exists('extends', $table)) {
2750 // For custom fields referenced in $this->_customGroupExtends
2751 $fields = CRM_Utils_Array
::value('fields', $table, array());
2756 if (!empty($fields) && is_array($fields)) {
2757 foreach ($fields as $fieldName => $field) {
2758 if ($fieldName == $orderBy['column']) {
2759 $orderByField = array_merge($field, $orderBy);
2760 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2767 if (!empty($orderByField)) {
2768 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2769 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2771 // Record any section headers for assignment to the template
2772 if (!empty($orderBy['section'])) {
2773 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2774 $this->_sections
[$orderByField['tplField']] = $orderByField;
2780 $this->_orderByArray
= $orderBys;
2782 $this->assign('sections', $this->_sections
);
2786 * Determine unselected columns.
2790 public function unselectedSectionColumns() {
2791 if (is_array($this->_sections
)) {
2792 return array_diff_key($this->_sections
, $this->getSelectColumns());
2800 * Build output rows.
2802 * @param string $sql
2803 * @param array $rows
2805 public function buildRows($sql, &$rows) {
2806 $dao = CRM_Core_DAO
::executeQuery($sql);
2807 if (!is_array($rows)) {
2811 // use this method to modify $this->_columnHeaders
2812 $this->modifyColumnHeaders();
2814 $unselectedSectionColumns = $this->unselectedSectionColumns();
2816 while ($dao->fetch()) {
2818 foreach ($this->_columnHeaders
as $key => $value) {
2819 if (property_exists($dao, $key)) {
2820 $row[$key] = $dao->$key;
2824 // section headers not selected for display need to be added to row
2825 foreach ($unselectedSectionColumns as $key => $values) {
2826 if (property_exists($dao, $key)) {
2827 $row[$key] = $dao->$key;
2836 * Calculate section totals.
2838 * When "order by" fields are marked as sections, this assigns to the template
2839 * an array of total counts for each section. This data is used by the Smarty
2840 * plugin {sectionTotal}.
2842 public function sectionTotals() {
2844 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2845 if (empty($this->_selectAliases
)) {
2849 if (!empty($this->_sections
)) {
2850 // build the query with no LIMIT clause
2851 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2852 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2854 // pull section aliases out of $this->_sections
2855 $sectionAliases = array_keys($this->_sections
);
2858 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2859 $ifnulls[] = "ifnull($alias, '') as $alias";
2861 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2862 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2864 // Group (un-limited) report by all aliases and get counts. This might
2865 // be done more efficiently when the contents of $sql are known, ie. by
2866 // overriding this method in the report class.
2868 $query = $this->_select
.
2869 ", count(*) as ct from ($sql) as subquery group by " .
2870 implode(", ", $sectionAliases);
2872 // initialize array of total counts
2874 $dao = CRM_Core_DAO
::executeQuery($query);
2875 while ($dao->fetch()) {
2877 // let $this->_alterDisplay translate any integer ids to human-readable values.
2878 $rows[0] = $dao->toArray();
2879 $this->alterDisplay($rows);
2882 // add totals for all permutations of section values
2885 $aliasCount = count($sectionAliases);
2886 foreach ($sectionAliases as $alias) {
2887 $values[] = $row[$alias];
2888 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2889 if ($i == $aliasCount) {
2890 // the last alias is the lowest-level section header; use count as-is
2891 $totals[$key] = $dao->ct
;
2894 // other aliases are higher level; roll count into their total
2895 $totals[$key] +
= $dao->ct
;
2899 $this->assign('sectionTotals', $totals);
2904 * Modify column headers.
2906 public function modifyColumnHeaders() {
2907 // use this method to modify $this->_columnHeaders
2911 * Move totals columns to the right edge of the table.
2913 * It seems like a more logical layout to have any totals columns on the far right regardless of
2914 * the location of the rest of their table.
2916 public function moveSummaryColumnsToTheRightHandSide() {
2917 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2918 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2922 * Assign rows to the template.
2924 * @param array $rows
2926 public function doTemplateAssignment(&$rows) {
2927 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2928 $this->assign_by_ref('rows', $rows);
2929 $this->assign('statistics', $this->statistics($rows));
2933 * Build report statistics.
2935 * Override this method to build your own statistics.
2937 * @param array $rows
2941 public function statistics(&$rows) {
2942 $statistics = array();
2944 $count = count($rows);
2945 // Why do we increment the count for rollup seems to artificially inflate the count.
2946 // It seems perhaps intentional to include the summary row in the count of results - although
2947 // this just seems odd.
2948 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2952 $this->countStat($statistics, $count);
2954 $this->groupByStat($statistics);
2956 $this->filterStat($statistics);
2962 * Add count statistics.
2964 * @param array $statistics
2967 public function countStat(&$statistics, $count) {
2968 $statistics['counts']['rowCount'] = array(
2969 'title' => ts('Row(s) Listed'),
2973 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2974 $statistics['counts']['rowsFound'] = array(
2975 'title' => ts('Total Row(s)'),
2976 'value' => $this->_rowsFound
,
2982 * Add group by statistics.
2984 * @param array $statistics
2986 public function groupByStat(&$statistics) {
2987 if (!empty($this->_params
['group_bys']) &&
2988 is_array($this->_params
['group_bys']) &&
2989 !empty($this->_params
['group_bys'])
2991 foreach ($this->_columns
as $tableName => $table) {
2992 if (array_key_exists('group_bys', $table)) {
2993 foreach ($table['group_bys'] as $fieldName => $field) {
2994 if (!empty($this->_params
['group_bys'][$fieldName])) {
2995 $combinations[] = $field['title'];
3000 $statistics['groups'][] = array(
3001 'title' => ts('Grouping(s)'),
3002 'value' => implode(' & ', $combinations),
3008 * Filter statistics.
3010 * @param array $statistics
3012 public function filterStat(&$statistics) {
3013 foreach ($this->_columns
as $tableName => $table) {
3014 if (array_key_exists('filters', $table)) {
3015 foreach ($table['filters'] as $fieldName => $field) {
3016 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3017 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3018 CRM_Utils_Array
::value('operatorType', $field) !=
3019 CRM_Report_Form
::OP_MONTH
3023 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3024 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3025 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3026 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3027 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3029 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3030 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3032 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3033 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3036 $statistics['filters'][] = array(
3037 'title' => $field['title'],
3038 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3041 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3042 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3044 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3045 $statistics['filters'][] = array(
3046 'title' => $field['title'],
3047 'value' => $pair[$rel],
3052 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3055 $pair = $this->getOperationPair(
3056 CRM_Utils_Array
::value('operatorType', $field),
3059 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3060 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3061 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3062 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3063 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3065 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3066 $this->setEntityRefDefaults($field, $tableName);
3067 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3068 array('id' => $val) +
3069 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3071 foreach ($result['values'] as $v) {
3072 $values[] = $v['label'];
3074 $value = "{$pair[$op]} " . implode(', ', $values);
3076 elseif ($op == 'nll' ||
$op == 'nnll') {
3077 $value = $pair[$op];
3079 elseif (is_array($val) && (!empty($val))) {
3080 $options = CRM_Utils_Array
::value('options', $field, array());
3081 foreach ($val as $key => $valIds) {
3082 if (isset($options[$valIds])) {
3083 $val[$key] = $options[$valIds];
3086 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3087 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3088 $val = implode(', ', $val);
3089 $value = "{$pair[$op]} " . $val;
3091 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3092 isset($field['options']) &&
3093 is_array($field['options']) && !empty($field['options'])
3095 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3096 CRM_Utils_Array
::value($val, $field['options'], $val);
3099 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3103 $statistics['filters'][] = array(
3104 'title' => CRM_Utils_Array
::value('title', $field),
3115 * End post processing.
3117 * @param array|null $rows
3119 public function endPostProcess(&$rows = NULL) {
3120 if ($this->_storeResultSet
) {
3121 $this->_resultSet
= $rows;
3124 if ($this->_outputMode
== 'print' ||
3125 $this->_outputMode
== 'pdf' ||
3129 $content = $this->compileContent();
3130 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3134 if ($this->_sendmail
) {
3135 $config = CRM_Core_Config
::singleton();
3136 $attachments = array();
3138 if ($this->_outputMode
== 'csv') {
3140 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3141 ": {$url}</p>" . '<p>' .
3142 ts('The report is attached as a CSV file.') . '</p>' .
3143 $this->_formValues
['report_footer'];
3145 $csvFullFilename = $config->templateCompileDir
.
3146 CRM_Utils_File
::makeFileName('CiviReport.csv');
3147 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3148 file_put_contents($csvFullFilename, $csvContent);
3149 $attachments[] = array(
3150 'fullPath' => $csvFullFilename,
3151 'mime_type' => 'text/csv',
3152 'cleanName' => 'CiviReport.csv',
3155 if ($this->_outputMode
== 'pdf') {
3156 // generate PDF content
3157 $pdfFullFilename = $config->templateCompileDir
.
3158 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3159 file_put_contents($pdfFullFilename,
3160 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3161 TRUE, array('orientation' => 'landscape')
3164 // generate Email Content
3166 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3167 ": {$url}</p>" . '<p>' .
3168 ts('The report is attached as a PDF file.') . '</p>' .
3169 $this->_formValues
['report_footer'];
3171 $attachments[] = array(
3172 'fullPath' => $pdfFullFilename,
3173 'mime_type' => 'application/pdf',
3174 'cleanName' => 'CiviReport.pdf',
3178 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3179 $this->_outputMode
, $attachments
3182 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3185 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3189 elseif ($this->_outputMode
== 'print') {
3193 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3194 $config = CRM_Core_Config
::singleton();
3195 //get chart image name
3196 $chartImg = $this->_chartId
. '.png';
3197 //get image url path
3199 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3201 $uploadUrl .= $chartImg;
3202 //get image doc path to overwrite
3204 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3205 'openFlashChart/' . $chartImg;
3207 $chart = imagecreatefrompng($uploadUrl);
3208 //convert it into formatted png
3209 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3210 //overwrite with same image
3211 imagepng($chart, $uploadImg);
3213 imagedestroy($chart);
3215 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3217 CRM_Utils_System
::civiExit();
3219 elseif ($this->_outputMode
== 'csv') {
3220 CRM_Report_Utils_Report
::export2csv($this, $rows);
3222 elseif ($this->_outputMode
== 'group') {
3223 $group = $this->_params
['groups'];
3224 $this->add2group($group);
3229 * Set store result set indicator to TRUE.
3231 * @todo explain what this does
3233 public function storeResultSet() {
3234 $this->_storeResultSet
= TRUE;
3242 public function getResultSet() {
3243 return $this->_resultSet
;
3247 * Get the sql used to generate the report.
3251 public function getReportSql() {
3252 return $this->sqlArray
;
3256 * Use the form name to create the tpl file name.
3260 public function getTemplateFileName() {
3261 $defaultTpl = parent
::getTemplateFileName();
3262 $template = CRM_Core_Smarty
::singleton();
3263 if (!$template->template_exists($defaultTpl)) {
3264 $defaultTpl = 'CRM/Report/Form.tpl';
3270 * Compile the report content.
3272 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3276 public function compileContent() {
3277 $templateFile = $this->getHookedTemplateFileName();
3278 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3279 CRM_Core_Form
::$_template->fetch($templateFile) .
3280 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3285 * Post process function.
3287 public function postProcess() {
3288 // get ready with post process params
3289 $this->beginPostProcess();
3292 $sql = $this->buildQuery();
3294 // build array of result based on column headers. This method also allows
3295 // modifying column headers before using it to build result set i.e $rows.
3297 $this->buildRows($sql, $rows);
3299 // format result set.
3300 $this->formatDisplay($rows);
3302 // assign variables to templates
3303 $this->doTemplateAssignment($rows);
3305 // do print / pdf / instance stuff if needed
3306 $this->endPostProcess($rows);
3312 * @param int $rowCount
3316 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3317 // lets do the pager if in html mode
3318 $this->_limit
= NULL;
3320 // CRM-14115, over-ride row count if rowCount is specified in URL
3321 if ($this->_dashBoardRowCount
) {
3322 $rowCount = $this->_dashBoardRowCount
;
3324 if ($this->addPaging
) {
3325 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3327 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3329 // @todo all http vars should be extracted in the preProcess
3330 // - not randomly in the class
3331 if (!$pageId && !empty($_POST)) {
3332 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3333 $pageId = max((int) $_POST['crmPID_B'], 1);
3335 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3336 $pageId = max((int) $_POST['crmPID'], 1);
3338 unset($_POST['crmPID_B'], $_POST['crmPID']);
3341 $pageId = $pageId ?
$pageId : 1;
3342 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3343 $offset = ($pageId - 1) * $rowCount;
3345 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3346 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3348 $this->_limit
= " LIMIT $offset, $rowCount";
3349 return array($offset, $rowCount);
3351 if ($this->_limitValue
) {
3352 if ($this->_offsetValue
) {
3353 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3356 $this->_limit
= " LIMIT " . $this->_limitValue
;
3364 * @param int $rowCount
3366 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3367 // CRM-14115, over-ride row count if rowCount is specified in URL
3368 if ($this->_dashBoardRowCount
) {
3369 $rowCount = $this->_dashBoardRowCount
;
3372 if ($this->_limit
&& ($this->_limit
!= '')) {
3373 if (!$this->_rowsFound
) {
3374 $sql = "SELECT FOUND_ROWS();";
3375 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3378 'total' => $this->_rowsFound
,
3379 'rowCount' => $rowCount,
3380 'status' => ts('Records') . ' %%StatusMessage%%',
3381 'buttonBottom' => 'PagerBottomButton',
3382 'buttonTop' => 'PagerTopButton',
3384 if (!empty($this->controller
)) {
3385 // This happens when being called from the api Really we want the api to be able to
3386 // pass paging parameters, but at this stage just preventing test crashes.
3387 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3390 $pager = new CRM_Utils_Pager($params);
3391 $this->assign_by_ref('pager', $pager);
3392 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3397 * Build a group filter with contempt for large data sets.
3399 * This function has been retained as it takes time to migrate the reports over
3400 * to the new method which will not crash on large datasets.
3404 * @param string $field
3405 * @param mixed $value
3410 public function legacySlowGroupFilterClause($field, $value, $op) {
3411 $smartGroupQuery = "";
3413 $group = new CRM_Contact_DAO_Group();
3414 $group->is_active
= 1;
3416 $smartGroups = array();
3417 while ($group->fetch()) {
3418 if (in_array($group->id
, $this->_params
['gid_value']) &&
3419 $group->saved_search_id
3421 $smartGroups[] = $group->id
;
3425 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3427 $smartGroupQuery = '';
3428 if (!empty($smartGroups)) {
3429 $smartGroups = implode(',', $smartGroups);
3430 $smartGroupQuery = " UNION DISTINCT
3431 SELECT DISTINCT smartgroup_contact.contact_id
3432 FROM civicrm_group_contact_cache smartgroup_contact
3433 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3436 $sqlOp = $this->getSQLOperator($op);
3437 if (!is_array($value)) {
3438 $value = array($value);
3440 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3442 $contactAlias = $this->_aliases
['civicrm_contact'];
3443 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3444 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3446 return " {$contactAlias}.id {$sqlOp} (
3447 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3448 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3449 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3450 {$smartGroupQuery} ) ";
3454 * Build where clause for groups.
3456 * @param string $field
3457 * @param mixed $value
3462 public function whereGroupClause($field, $value, $op) {
3463 if ($this->groupFilterNotOptimised
) {
3464 return $this->legacySlowGroupFilterClause($field, $value, $op);
3466 if ($op === 'notin') {
3467 return " group_temp_table.id IS NULL ";
3469 // We will have used an inner join instead.
3475 * Create a table of the contact ids included by the group filter.
3477 * This function is called by both the api (tests) and the UI.
3479 public function buildGroupTempTable() {
3480 if (!empty($this->groupTempTable
) ||
empty ($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3483 $filteredGroups = (array) $this->_params
['gid_value'];
3485 $groups = civicrm_api3('Group', 'get', array(
3487 'id' => array('IN' => $filteredGroups),
3488 'saved_search_id' => array('>' => 0),
3491 $smartGroups = array_keys($groups['values']);
3494 SELECT group_contact.contact_id as id
3495 FROM civicrm_group_contact group_contact
3496 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3497 AND group_contact.status = 'Added' ";
3499 if (!empty($smartGroups)) {
3500 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3501 $smartGroups = implode(',', $smartGroups);
3504 SELECT smartgroup_contact.contact_id as id
3505 FROM civicrm_group_contact_cache smartgroup_contact
3506 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3509 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3510 $this->executeReportQuery("
3511 CREATE TEMPORARY TABLE $this->groupTempTable
3514 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3518 * Execute query and add it to the developer tab.
3520 * @param string $query
3521 * @param array $params
3523 * @return \CRM_Core_DAO|object
3525 protected function executeReportQuery($query, $params = array()) {
3526 $this->addToDeveloperTab($query);
3527 return CRM_Core_DAO
::executeQuery($query, $params);
3531 * Build where clause for tags.
3533 * @param string $field
3534 * @param mixed $value
3539 public function whereTagClause($field, $value, $op) {
3540 // not using left join in query because if any contact
3541 // belongs to more than one tag, results duplicate
3543 $sqlOp = $this->getSQLOperator($op);
3544 if (!is_array($value)) {
3545 $value = array($value);
3547 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3548 $entity_table = $this->_tagFilterTable
;
3549 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3550 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3551 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3552 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3556 * Generate membership organization clause.
3558 * @param mixed $value
3559 * @param string $op SQL Operator
3563 public function whereMembershipOrgClause($value, $op) {
3564 $sqlOp = $this->getSQLOperator($op);
3565 if (!is_array($value)) {
3566 $value = array($value);
3569 $tmp_membership_org_sql_list = implode(', ', $value);
3570 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3571 SELECT DISTINCT mem.contact_id
3572 FROM civicrm_membership mem
3573 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3574 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3575 WHERE mt.member_of_contact_id IN (" .
3576 $tmp_membership_org_sql_list . ")
3577 AND mt.is_active = '1'
3578 AND mem_status.is_current_member = '1'
3579 AND mem_status.is_active = '1' ) ";
3583 * Generate Membership Type SQL Clause.
3585 * @param mixed $value
3591 public function whereMembershipTypeClause($value, $op) {
3592 $sqlOp = $this->getSQLOperator($op);
3593 if (!is_array($value)) {
3594 $value = array($value);
3597 $tmp_membership_sql_list = implode(', ', $value);
3598 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3599 SELECT DISTINCT mem.contact_id
3600 FROM civicrm_membership mem
3601 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3602 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3603 WHERE mem.membership_type_id IN (" .
3604 $tmp_membership_sql_list . ")
3605 AND mt.is_active = '1'
3606 AND mem_status.is_current_member = '1'
3607 AND mem_status.is_active = '1' ) ";
3611 * Build acl clauses.
3613 * @param string $tableAlias
3615 public function buildACLClause($tableAlias = 'contact_a') {
3616 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3620 * Add custom data to the columns.
3622 * @param bool $addFields
3623 * @param array $permCustomGroupIds
3625 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3626 if (empty($this->_customGroupExtends
)) {
3629 if (!is_array($this->_customGroupExtends
)) {
3630 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3632 $customGroupWhere = '';
3633 if (!empty($permCustomGroupIds)) {
3634 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3638 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3639 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3640 FROM civicrm_custom_group cg
3641 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3642 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3644 cg.is_active = 1 AND
3645 cf.is_active = 1 AND
3646 cf.is_searchable = 1
3647 ORDER BY cg.weight, cf.weight";
3648 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3651 while ($customDAO->fetch()) {
3652 if ($customDAO->table_name
!= $curTable) {
3653 $curTable = $customDAO->table_name
;
3654 $curFields = $curFilters = array();
3657 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3658 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3659 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3660 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3662 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3663 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3664 $this->_columns
[$curTable][$colKey] = array();
3668 $fieldName = 'custom_' . $customDAO->cf_id
;
3671 // this makes aliasing work in favor
3672 $curFields[$fieldName] = array(
3673 'name' => $customDAO->column_name
,
3674 'title' => $customDAO->label
,
3675 'dataType' => $customDAO->data_type
,
3676 'htmlType' => $customDAO->html_type
,
3679 if ($this->_customGroupFilters
) {
3680 // this makes aliasing work in favor
3681 $curFilters[$fieldName] = array(
3682 'name' => $customDAO->column_name
,
3683 'title' => $customDAO->label
,
3684 'dataType' => $customDAO->data_type
,
3685 'htmlType' => $customDAO->html_type
,
3689 switch ($customDAO->data_type
) {
3692 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3693 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3694 // CRM-6946, show time part for datetime date fields
3695 if ($customDAO->time_format
) {
3696 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3701 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3702 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3703 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3707 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3708 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3712 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3713 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3714 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3718 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3719 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3723 case 'StateProvince':
3725 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3727 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3728 if ($options !== FALSE) {
3729 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3730 $curFilters[$fieldName]['options'] = $options;
3734 case 'ContactReference':
3735 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3736 $curFilters[$fieldName]['name'] = 'display_name';
3737 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3739 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3740 $curFields[$fieldName]['name'] = 'display_name';
3741 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3745 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3746 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3749 if (!array_key_exists('type', $curFields[$fieldName])) {
3750 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3754 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3756 if ($this->_customGroupFilters
) {
3757 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3759 if ($this->_customGroupGroupBy
) {
3760 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3766 * Build custom data from clause.
3768 * @param bool $joinsForFiltersOnly
3769 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3771 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3772 if (empty($this->_customGroupExtends
)) {
3775 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3776 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3777 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3778 $customTables = array();
3779 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3780 while ($customTablesDAO->fetch()) {
3781 $customTables[] = $customTablesDAO->table_name
;
3784 foreach ($this->_columns
as $table => $prop) {
3785 if (in_array($table, $customTables)) {
3786 $extendsTable = $mapper[$prop['extends']];
3787 // Check field is required for rendering the report.
3788 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3791 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3793 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3795 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3796 // handle for ContactReference
3797 if (array_key_exists('fields', $prop)) {
3798 foreach ($prop['fields'] as $fieldName => $field) {
3799 if (CRM_Utils_Array
::value('dataType', $field) ==
3802 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3804 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3813 * Check if the field is selected.
3815 * @param string $prop
3819 public function isFieldSelected($prop) {
3824 if (!empty($this->_params
['fields'])) {
3825 foreach (array_keys($prop['fields']) as $fieldAlias) {
3826 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3827 if ($customFieldId) {
3828 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3832 //might be survey response field.
3833 if (!empty($this->_params
['fields']['survey_response']) &&
3834 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3842 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3843 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3844 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3845 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3852 if (!empty($this->_params
['order_bys'])) {
3853 foreach (array_keys($prop['fields']) as $fieldAlias) {
3854 foreach ($this->_params
['order_bys'] as $orderBy) {
3855 if ($fieldAlias == $orderBy['column'] &&
3856 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3863 return $this->isFieldFiltered($prop);
3868 * Check if the field is used as a filter.
3870 * @param string $prop
3874 protected function isFieldFiltered($prop) {
3875 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3876 foreach ($prop['filters'] as $fieldAlias => $val) {
3885 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3886 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3887 ||
($attach != 'relative' &&
3888 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3894 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3895 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3906 * Check for empty order_by configurations and remove them.
3908 * Also set template to hide them.
3910 * @param array $formValues
3912 public function preProcessOrderBy(&$formValues) {
3913 // Object to show/hide form elements
3914 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3916 $_showHide->addShow('optionField_1');
3918 // Cycle through order_by options; skip any empty ones, and hide them as well
3921 if (!empty($formValues['order_bys'])) {
3922 foreach ($formValues['order_bys'] as $order_by) {
3923 if ($order_by['column'] && $order_by['column'] != '-') {
3924 $_showHide->addShow('optionField_' . $n);
3925 $orderBys[$n] = $order_by;
3930 for ($i = $n; $i <= 5; $i++
) {
3932 $_showHide->addHide('optionField_' . $i);
3936 // overwrite order_by options with modified values
3937 if (!empty($orderBys)) {
3938 $formValues['order_bys'] = $orderBys;
3941 $formValues['order_bys'] = array(1 => array('column' => '-'));
3944 // assign show/hide data to template
3945 $_showHide->addToTemplate();
3949 * Check if table name has columns in SELECT clause.
3951 * @param string $tableName
3952 * Name of table (index of $this->_columns array).
3956 public function isTableSelected($tableName) {
3957 return in_array($tableName, $this->selectedTables());
3961 * Check if table name has columns in WHERE or HAVING clause.
3963 * @param string $tableName
3964 * Name of table (index of $this->_columns array).
3968 public function isTableFiltered($tableName) {
3969 // Cause the array to be generated if not previously done.
3970 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3971 $this->selectedTables();
3973 return in_array($tableName, $this->filteredTables
);
3977 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3979 * If the array is unset it will be built.
3984 public function selectedTables() {
3985 if (!$this->_selectedTables
) {
3986 $orderByColumns = array();
3987 if (array_key_exists('order_bys', $this->_params
) &&
3988 is_array($this->_params
['order_bys'])
3990 foreach ($this->_params
['order_bys'] as $orderBy) {
3991 $orderByColumns[] = $orderBy['column'];
3995 foreach ($this->_columns
as $tableName => $table) {
3996 if (array_key_exists('fields', $table)) {
3997 foreach ($table['fields'] as $fieldName => $field) {
3998 if (!empty($field['required']) ||
3999 !empty($this->_params
['fields'][$fieldName])
4001 $this->_selectedTables
[] = $tableName;
4006 if (array_key_exists('order_bys', $table)) {
4007 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4008 if (in_array($orderByName, $orderByColumns)) {
4009 $this->_selectedTables
[] = $tableName;
4014 if (array_key_exists('filters', $table)) {
4015 foreach ($table['filters'] as $filterName => $filter) {
4016 if (!empty($this->_params
["{$filterName}_value"]) ||
4017 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4019 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4022 $this->_selectedTables
[] = $tableName;
4023 $this->filteredTables
[] = $tableName;
4030 return $this->_selectedTables
;
4034 * Add address fields.
4036 * @deprecated - use getAddressColumns which is a more accurate description
4037 * and also accepts an array of options rather than a long list
4039 * adding address fields to construct function in reports
4041 * @param bool $groupBy
4042 * Add GroupBy? Not appropriate for detail report.
4043 * @param bool $orderBy
4044 * Add GroupBy? Not appropriate for detail report.
4045 * @param bool $filters
4046 * @param array $defaults
4049 * address fields for construct clause
4051 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4052 $addressFields = array(
4053 'civicrm_address' => array(
4054 'dao' => 'CRM_Core_DAO_Address',
4056 'address_name' => array(
4057 'title' => ts('Address Name'),
4058 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4061 'street_address' => array(
4062 'title' => ts('Street Address'),
4063 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
4065 'supplemental_address_1' => array(
4066 'title' => ts('Supplementary Address Field 1'),
4067 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
4069 'supplemental_address_2' => array(
4070 'title' => ts('Supplementary Address Field 2'),
4071 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
4073 'street_number' => array(
4074 'name' => 'street_number',
4075 'title' => ts('Street Number'),
4077 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
4079 'street_name' => array(
4080 'name' => 'street_name',
4081 'title' => ts('Street Name'),
4083 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
4085 'street_unit' => array(
4086 'name' => 'street_unit',
4087 'title' => ts('Street Unit'),
4089 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
4092 'title' => ts('City'),
4093 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
4095 'postal_code' => array(
4096 'title' => ts('Postal Code'),
4097 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
4099 'postal_code_suffix' => array(
4100 'title' => ts('Postal Code Suffix'),
4101 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
4103 'country_id' => array(
4104 'title' => ts('Country'),
4105 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
4107 'state_province_id' => array(
4108 'title' => ts('State/Province'),
4109 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
4111 'county_id' => array(
4112 'title' => ts('County'),
4113 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
4116 'grouping' => 'location-fields',
4121 // Address filter depends on whether street address parsing is enabled.
4123 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4126 if ($addressOptions['street_address_parsing']) {
4127 $street_address_filters = array(
4128 'street_number' => array(
4129 'title' => ts('Street Number'),
4131 'name' => 'street_number',
4133 'street_name' => array(
4134 'title' => ts('Street Name'),
4135 'name' => 'street_name',
4136 'operator' => 'like',
4141 $street_address_filters = array(
4142 'street_address' => array(
4143 'title' => ts('Street Address'),
4144 'operator' => 'like',
4145 'name' => 'street_address',
4149 $general_address_filters = array(
4150 'postal_code' => array(
4151 'title' => ts('Postal Code'),
4153 'name' => 'postal_code',
4156 'title' => ts('City'),
4157 'operator' => 'like',
4160 'country_id' => array(
4161 'name' => 'country_id',
4162 'title' => ts('Country'),
4163 'type' => CRM_Utils_Type
::T_INT
,
4164 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4165 'options' => CRM_Core_PseudoConstant
::country(),
4167 'state_province_id' => array(
4168 'name' => 'state_province_id',
4169 'title' => ts('State/Province'),
4170 'type' => CRM_Utils_Type
::T_INT
,
4171 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4172 'options' => array(),
4174 'county_id' => array(
4175 'name' => 'county_id',
4176 'title' => ts('County'),
4177 'type' => CRM_Utils_Type
::T_INT
,
4178 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4179 'options' => array(),
4183 $addressFields['civicrm_address']['filters'] = array_merge(
4184 $street_address_filters,
4185 $general_address_filters);
4188 $addressFields['civicrm_address']['order_bys'] = array(
4189 'street_name' => array('title' => ts('Street Name')),
4190 'street_number' => array('title' => ts('Odd / Even Street Number')),
4191 'street_address' => NULL,
4193 'postal_code' => NULL,
4198 $addressFields['civicrm_address']['group_bys'] = array(
4199 'street_address' => NULL,
4201 'postal_code' => NULL,
4202 'state_province_id' => array(
4203 'title' => ts('State/Province'),
4205 'country_id' => array(
4206 'title' => ts('Country'),
4208 'county_id' => array(
4209 'title' => ts('County'),
4213 return $addressFields;
4217 * Do AlterDisplay processing on Address Fields.
4220 * @param array $rows
4221 * @param int $rowNum
4222 * @param string $baseUrl
4223 * @param string $linkText
4227 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4228 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4229 $entryFound = FALSE;
4231 if (array_key_exists('civicrm_address_country_id', $row)) {
4232 if ($value = $row['civicrm_address_country_id']) {
4233 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4235 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4236 "reset=1&force=1&{$criteriaQueryParams}&" .
4237 "country_id_op=in&country_id_value={$value}",
4238 $this->_absoluteUrl
, $this->_id
4240 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4241 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4242 array(1 => $linkText)
4249 if (array_key_exists('civicrm_address_county_id', $row)) {
4250 if ($value = $row['civicrm_address_county_id']) {
4251 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4253 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4254 "reset=1&force=1&{$criteriaQueryParams}&" .
4255 "county_id_op=in&county_id_value={$value}",
4256 $this->_absoluteUrl
, $this->_id
4258 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4259 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4260 array(1 => $linkText)
4266 // handle state province
4267 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4268 if ($value = $row['civicrm_address_state_province_id']) {
4269 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4271 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4272 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4273 $this->_absoluteUrl
, $this->_id
4275 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4276 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4277 array(1 => $linkText)
4288 * Do AlterDisplay processing on Address Fields.
4291 * @param array $rows
4292 * @param int $rowNum
4293 * @param string $baseUrl
4294 * @param string $linkText
4298 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4299 $entryFound = FALSE;
4300 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4301 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4302 $addLinks = array('gender_id' => 'Gender');
4303 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4304 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4305 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4306 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4307 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4308 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4314 $yesNoFields = array(
4315 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4317 foreach ($yesNoFields as $fieldName) {
4318 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4319 // Since these are essentially 'negative fields' it feels like it
4320 // makes sense to only highlight the exceptions hence no 'No'.
4321 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4329 * Adjusts dates passed in to YEAR() for fiscal year.
4331 * @param string $fieldName
4335 public function fiscalYearOffset($fieldName) {
4336 $config = CRM_Core_Config
::singleton();
4337 $fy = $config->fiscalYearStart
;
4338 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4339 ($fy['d'] == 1 && $fy['M'] == 1)
4341 return "YEAR( $fieldName )";
4343 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4344 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4348 * Add Address into From Table if required.
4350 public function addAddressFromClause() {
4351 // include address field if address column is to be included
4352 if ((isset($this->_addressField
) &&
4353 $this->_addressField
4355 $this->isTableSelected('civicrm_address')
4358 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4359 ON ({$this->_aliases['civicrm_contact']}.id =
4360 {$this->_aliases['civicrm_address']}.contact_id) AND
4361 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4366 * Add Phone into From Table if required.
4368 public function addPhoneFromClause() {
4369 // include address field if address column is to be included
4370 if ($this->isTableSelected('civicrm_phone')
4373 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4374 ON ({$this->_aliases['civicrm_contact']}.id =
4375 {$this->_aliases['civicrm_phone']}.contact_id) AND
4376 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4381 * Get phone columns to add to array.
4383 * @param array $options
4384 * - prefix Prefix to add to table (in case of more than one instance of the table)
4385 * - prefix_label Label to give columns from this phone table instance
4388 * phone columns definition
4390 public function getPhoneColumns($options = array()) {
4391 $defaultOptions = array(
4393 'prefix_label' => '',
4396 $options = array_merge($defaultOptions, $options);
4399 $options['prefix'] . 'civicrm_phone' => array(
4400 'dao' => 'CRM_Core_DAO_Phone',
4402 $options['prefix'] . 'phone' => array(
4403 'title' => ts($options['prefix_label'] . 'Phone'),
4413 * Get address columns to add to array.
4415 * @param array $options
4416 * - prefix Prefix to add to table (in case of more than one instance of the table)
4417 * - prefix_label Label to give columns from this address table instance
4420 * address columns definition
4422 public function getAddressColumns($options = array()) {
4425 'prefix_label' => '',
4429 'defaults' => array(),
4431 return $this->addAddressFields(
4432 $options['group_by'],
4433 $options['order_by'],
4434 $options['filters'],
4435 $options['defaults']
4440 * Get a standard set of contact fields.
4444 public function getBasicContactFields() {
4446 'sort_name' => array(
4447 'title' => ts('Contact Name'),
4452 'no_display' => TRUE,
4455 'prefix_id' => array(
4456 'title' => ts('Contact Prefix'),
4458 'first_name' => array(
4459 'title' => ts('First Name'),
4461 'nick_name' => array(
4462 'title' => ts('Nick Name'),
4464 'middle_name' => array(
4465 'title' => ts('Middle Name'),
4467 'last_name' => array(
4468 'title' => ts('Last Name'),
4470 'suffix_id' => array(
4471 'title' => ts('Contact Suffix'),
4473 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4474 'email_greeting_display' => array('title' => ts('Email Greeting')),
4475 'addressee_display' => array('title' => ts('Addressee')),
4476 'contact_type' => array(
4477 'title' => ts('Contact Type'),
4479 'contact_sub_type' => array(
4480 'title' => ts('Contact Subtype'),
4482 'gender_id' => array(
4483 'title' => ts('Gender'),
4485 'birth_date' => array(
4486 'title' => ts('Birth Date'),
4489 'title' => ts('Age'),
4490 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4492 'job_title' => array(
4493 'title' => ts('Contact Job title'),
4495 'organization_name' => array(
4496 'title' => ts('Organization Name'),
4498 'external_identifier' => array(
4499 'title' => ts('Contact identifier from external system'),
4501 'do_not_email' => array(),
4502 'do_not_phone' => array(),
4503 'do_not_mail' => array(),
4504 'do_not_sms' => array(),
4505 'is_opt_out' => array(),
4506 'is_deceased' => array(),
4511 * Get a standard set of contact filters.
4515 public function getBasicContactFilters() {
4517 'sort_name' => array(
4518 'title' => ts('Contact Name'),
4521 'title' => ts('Contact Source'),
4522 'type' => CRM_Utils_Type
::T_STRING
,
4525 'title' => ts('Contact ID'),
4526 'no_display' => TRUE,
4528 'gender_id' => array(
4529 'title' => ts('Gender'),
4530 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4531 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4533 'birth_date' => array(
4534 'title' => ts('Birth Date'),
4535 'operatorType' => CRM_Report_Form
::OP_DATE
,
4537 'contact_type' => array(
4538 'title' => ts('Contact Type'),
4540 'contact_sub_type' => array(
4541 'title' => ts('Contact Subtype'),
4543 'modified_date' => array(
4544 'title' => ts('Contact Modified'),
4545 'operatorType' => CRM_Report_Form
::OP_DATE
,
4546 'type' => CRM_Utils_Type
::T_DATE
,
4548 'is_deceased' => array(
4549 'title' => ts('Deceased'),
4550 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4553 'do_not_email' => array(
4554 'title' => ts('Do not email'),
4555 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4557 'do_not_phone' => array(
4558 'title' => ts('Do not phone'),
4559 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4561 'do_not_mail' => array(
4562 'title' => ts('Do not mail'),
4563 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4565 'do_not_sms' => array(
4566 'title' => ts('Do not SMS'),
4567 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4569 'is_opt_out' => array(
4570 'title' => ts('Do not bulk email'),
4571 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4577 * Add contact to group.
4579 * @param int $groupID
4581 public function add2group($groupID) {
4582 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4583 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4585 // here are we are prepending / adding contact id field that could be used for adding group
4586 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4587 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select
)) {
4588 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4591 $select = str_ireplace('SELECT ', $select, $this->_select
);
4594 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4595 $sql = str_replace('WITH ROLLUP', '', $sql);
4596 $dao = CRM_Core_DAO
::executeQuery($sql);
4598 $contact_ids = array();
4599 // Add resulting contacts to group
4600 while ($dao->fetch()) {
4601 if ($dao->addtogroup_contact_id
) {
4602 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4606 if (!empty($contact_ids)) {
4607 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4608 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4611 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4617 * Show charts on print screen.
4619 public static function uploadChartImage() {
4620 // upload strictly for '.png' images
4621 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4622 if (preg_match('/\.png$/', $name)) {
4624 // POST data is usually string data, but we are passing a RAW .png
4625 // so PHP is a bit confused and $_POST is empty. But it has saved
4626 // the raw bits into $HTTP_RAW_POST_DATA
4628 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4630 // prepare the directory
4631 $config = CRM_Core_Config
::singleton();
4633 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4635 if (!file_exists($defaultPath)) {
4636 mkdir($defaultPath, 0777, TRUE);
4639 // full path to the saved image including filename
4640 $destination = $defaultPath . $name;
4643 $jfh = fopen($destination, 'w') or die("can't open file");
4644 fwrite($jfh, $httpRawPostData);
4646 CRM_Utils_System
::civiExit();
4651 * Apply common settings to entityRef fields.
4653 * @param array $field
4654 * @param string $table
4656 private function setEntityRefDefaults(&$field, $table) {
4657 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4658 $field['attributes'] +
= array(
4659 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4661 'placeholder' => ts('- select -'),
4666 * Add link fields to the row.
4668 * Function adds the _link & _hover fields to the row.
4671 * @param string $baseUrl
4672 * @param string $linkText
4673 * @param string $value
4674 * @param string $fieldName
4675 * @param string $tablePrefix
4676 * @param string $fieldLabel
4680 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4681 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4682 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4683 "reset=1&force=1&{$criteriaQueryParams}&" .
4684 $fieldName . "_op=in&{$fieldName}_value={$value}",
4685 $this->_absoluteUrl
, $this->_id
4687 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4688 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4689 array(1 => $linkText, 2 => $fieldLabel)
4694 * Generate temporary table to hold all contributions with permissioned FTs.
4696 * @param object $query
4697 * @param string $alias
4698 * @param bool $return
4700 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4701 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4704 $financialTypes = NULL;
4705 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4706 if (empty($financialTypes)) {
4708 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4711 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4713 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4715 $query->_aliases
['civicrm_line_item'] = $alias;
4718 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4720 if (empty($query->_where
)) {
4721 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4723 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4724 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4725 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4726 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4727 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4728 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4730 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4731 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4732 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4733 CRM_Core_DAO
::executeQuery($sql);
4735 $query->_aliases
['civicrm_line_item'] = $temp;
4737 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4741 $query->_from
.= $from;
4745 * Get label for show results buttons.
4749 public function getResultsLabel() {
4750 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4751 return $showResultsLabel;
4755 * Determine the output mode from the url or input.
4758 * - pdf : Render as pdf
4759 * - csv : Render as csv
4760 * - print : Render in print format
4761 * - save : save the report and display the new report
4762 * - copy : save the report as a new instance and display that.
4763 * - group : go to the add to group screen.
4765 * Potentially chart variations could also be included but the complexity
4766 * is that we might print a bar chart as a pdf.
4768 protected function setOutputMode() {
4769 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4772 CRM_Core_DAO
::$_nullObject,
4774 CRM_Utils_Array
::value('task', $this->_params
)
4776 // if contacts are added to group
4777 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4778 $this->_outputMode
= 'group';
4780 if (isset($this->_params
['task'])) {
4781 unset($this->_params
['task']);
4786 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4789 * @param $columnName
4791 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4792 // add new column with date value for the datetime field
4793 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4794 CRM_Core_DAO
::executeQuery($tempQuery);
4795 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4796 CRM_Core_DAO
::executeQuery($updateQuery);
4797 $this->_selectClauses
[] = "{$columnName}_date";
4798 $this->_select
.= ", {$columnName}_date";
4799 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4800 unset($this->_sections
["{$columnName}"]);
4801 $this->assign('sections', $this->_sections
);
4805 * Get an array of the columns that have been selected for display.
4809 public function getSelectColumns() {
4810 $selectColumns = array();
4811 foreach ($this->_columns
as $tableName => $table) {
4812 if (array_key_exists('fields', $table)) {
4813 foreach ($table['fields'] as $fieldName => $field) {
4814 if (!empty($field['required']) ||
4815 !empty($this->_params
['fields'][$fieldName])
4818 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4823 return $selectColumns;
4827 * Add location tables to the query if they are used for filtering.
4829 * This is for when we are running the query separately for filtering and retrieving display fields.
4831 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4832 if ($this->isTableFiltered('civicrm_email')) {
4834 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4835 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4836 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4838 if ($this->isTableFiltered('civicrm_phone')) {
4840 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4841 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4842 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4844 if ($this->isTableFiltered('civicrm_address')) {
4846 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4847 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4848 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4853 * Set the base table for the FROM clause.
4855 * Sets up the from clause, allowing for the possibility it might be a
4856 * temp table pre-filtered by groups if a group filter is in use.
4858 * @param string $baseTable
4859 * @param string $field
4860 * @param null $tableAlias
4862 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4864 $tableAlias = $this->_aliases
[$baseTable];
4866 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4867 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4868 $this->_from
.= " {$this->_aclFrom} ";
4872 * Join the temp table contacting contacts who are members of the filtered groups.
4874 * If we are using an IN filter we use an inner join, otherwise a left join.
4876 * @param string $baseTable
4877 * @param string $field
4878 * @param string $tableAlias
4880 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4881 if ($this->groupTempTable
) {
4882 if ($this->_params
['gid_op'] == 'in') {
4883 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4884 ON group_temp_table.id = $tableAlias.{$field} ";
4888 LEFT JOIN $this->groupTempTable group_temp_table
4889 ON $tableAlias.{$field} = group_temp_table.id ";