3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 public $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
156 * Has the report been optimised for group filtering.
158 * The functionality for group filtering has been improved but not
159 * all reports have been adjusted to take care of it.
161 * This property exists to highlight the reports which are still using the
162 * slow method & allow group filtering to still work for them until they
165 * In order to protect extensions we have to default to TRUE - but I have
166 * separately marked every class with a groupFilter in the hope that will trigger
167 * people to fix them as they touch them.
173 protected $groupFilterNotOptimised = TRUE;
180 public $_navigation = array();
182 public $_drilldownReport = array();
185 * Array of tabs to display on report.
187 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
189 * $this->tabs['OrderBy'] = array(
190 * 'title' => ts('Sorting'),
191 * 'tpl' => 'OrderBy',
192 * 'div_label' => 'order-by',
197 protected $tabs = array();
200 * Should we add paging.
204 protected $addPaging = TRUE;
207 * An attribute for checkbox/radio form field layout
211 protected $_fourColumnAttribute = array(
212 '</td><td width="25%">',
213 '</td><td width="25%">',
214 '</td><td width="25%">',
218 protected $_force = 1;
220 protected $_params = NULL;
221 protected $_formValues = NULL;
222 protected $_instanceValues = NULL;
224 protected $_instanceForm = FALSE;
225 protected $_criteriaForm = FALSE;
227 protected $_instanceButtonName = NULL;
228 protected $_createNewButtonName = NULL;
229 protected $_printButtonName = NULL;
230 protected $_pdfButtonName = NULL;
231 protected $_csvButtonName = NULL;
232 protected $_groupButtonName = NULL;
233 protected $_chartButtonName = NULL;
234 protected $_csvSupported = TRUE;
235 protected $_add2groupSupported = TRUE;
236 protected $_groups = NULL;
237 protected $_grandFlag = FALSE;
238 protected $_rowsFound = NULL;
239 protected $_selectAliases = array();
240 protected $_rollup = NULL;
243 * Table containing list of contact IDs within the group filter.
247 protected $groupTempTable = '';
252 protected $_aliases = array();
268 protected $_limit = NULL;
271 * This can be set to specify a limit to the number of rows
272 * Since it is currently envisaged as part of the api usage it is only being applied
273 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
274 * of the code (see limit() fn.
278 protected $_limitValue = NULL;
281 * This can be set to specify row offset
282 * See notes on _limitValue
285 protected $_offsetValue = NULL;
289 protected $_sections = NULL;
290 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
291 protected $_absoluteUrl = FALSE;
294 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
298 protected $_storeResultSet = FALSE;
301 * When _storeResultSet Flag is set use this var to store result set in form of array
305 protected $_resultSet = array();
308 * To what frequency group-by a date column
312 protected $_groupByDateFreq = array(
314 'YEARWEEK' => 'Week',
315 'QUARTER' => 'Quarter',
320 * Variables to hold the acl inner join and where clause
322 protected $_aclFrom = NULL;
323 protected $_aclWhere = NULL;
326 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
328 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
332 protected $_selectedTables;
335 * Array of DAO tables having columns included in WHERE or HAVING clause
339 protected $filteredTables;
342 * Output mode e.g 'print', 'csv', 'pdf'.
346 protected $_outputMode;
349 * Format of any chart in use.
351 * (it's unclear if this could be merged with outputMode at this stage)
357 public $_having = NULL;
358 public $_select = NULL;
359 public $_selectClauses = array();
360 public $_columnHeaders = array();
361 public $_orderBy = NULL;
362 public $_orderByFields = array();
363 public $_orderByArray = array();
364 public $_groupBy = NULL;
365 public $_whereClauses = array();
366 public $_havingClauses = array();
369 * DashBoardRowCount Dashboard row count
372 public $_dashBoardRowCount;
375 * Is this being called without a form controller (ie. the report is being render outside the normal form
376 * - e.g the api is retrieving the rows
379 public $noController = FALSE;
382 * Variable to hold the currency alias
384 protected $_currencyColumn = NULL;
389 protected $_interval;
394 protected $_sendmail;
407 * @var string Report description.
409 public $_description;
412 * @var bool Is an address field selected.
413 * This was intended to determine if the address table should be joined in
414 * The isTableSelected function is now preferred for this purpose
416 protected $_addressField;
419 * @var bool Is an email field selected.
420 * This was intended to determine if the email table should be joined in
421 * The isTableSelected function is now preferred for this purpose
423 protected $_emailField;
426 * @var bool Is a phone field selected.
427 * This was intended to determine if the phone table should be joined in
428 * The isTableSelected function is now preferred for this purpose
430 protected $_phoneField;
433 * @var bool Create new report instance? (or update existing) on save.
435 protected $_createNew;
438 * When a grand total row has calculated the status we pop it off to here.
440 * This allows us to access it from the stats function and avoid recalculating.
442 protected $rollupRow = array();
445 * @var string Database attributes - character set and collation
447 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
450 * SQL being run in this report.
452 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
460 * SQL being run in this report as an array.
462 * The sql in the report is stored in this variable in order to be returned to api & test calls.
471 public function __construct() {
472 parent
::__construct();
474 $this->addClass('crm-report-form');
476 if ($this->_tagFilter
) {
477 $this->buildTagFilter();
479 if ($this->_exposeContactID
) {
480 if (array_key_exists('civicrm_contact', $this->_columns
)) {
481 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
483 'title' => ts('Contact ID'),
489 if ($this->_groupFilter
) {
490 $this->buildGroupFilter();
493 // Get all custom groups
494 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
496 // Get the custom groupIds for which the user has VIEW permission
497 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
498 // and addCustomDataToColumns() will allow access to all custom groups.
499 $permCustomGroupIds = array();
500 if (!CRM_Core_Permission
::check('access all custom data')) {
501 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
502 // do not allow custom data for reports if user doesn't have
503 // permission to access custom data.
504 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
505 $this->_customGroupExtends
= array();
509 // merge custom data columns to _columns list, if any
510 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
512 // add / modify display columns, filters ..etc
513 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
515 //assign currencyColumn variable to tpl
516 $this->assign('currencyColumn', $this->_currencyColumn
);
520 * Shared pre-process function.
522 * If overriding preProcess function this should still be called.
526 public function preProcessCommon() {
527 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
529 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
531 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
533 $this->assign('section', $this->_section
);
534 CRM_Core_Region
::instance('page-header')->add(array(
535 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
537 if (!$this->noController
) {
538 $this->setID($this->get('instanceId'));
541 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
543 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
547 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
548 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
549 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
553 $this->assign('instanceId', $this->_id
);
554 $params = array('id' => $this->_id
);
555 $this->_instanceValues
= array();
556 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
558 $this->_instanceValues
560 if (empty($this->_instanceValues
)) {
561 CRM_Core_Error
::fatal("Report could not be loaded.");
563 $this->_title
= $this->_instanceValues
['title'];
564 if (!empty($this->_instanceValues
['permission']) &&
565 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
566 CRM_Core_Permission
::check('administer Reports')
569 CRM_Utils_System
::permissionDenied();
570 CRM_Utils_System
::civiExit();
573 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
575 $this->_formValues
= unserialize($formValues);
578 $this->_formValues
= NULL;
581 $this->setOutputMode();
583 if ($this->_outputMode
== 'copy') {
584 $this->_createNew
= TRUE;
585 $this->_params
= $this->_formValues
;
586 $this->_params
['view_mode'] = 'criteria';
587 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
588 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
589 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
591 // Do not pass go. Do not collect another chance to re-run the same query.
592 CRM_Report_Form_Instance
::postProcess($this);
595 // lets always do a force if reset is found in the url.
596 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
597 // in the comment line above these 2.
598 if (!empty($_REQUEST['reset'])
599 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
604 $this->assign('mode', 'instance');
606 elseif (!$this->noController
) {
607 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
608 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
609 if (($instanceCount > 0) && $optionValueID) {
610 $this->assign('instanceUrl',
611 CRM_Utils_System
::url('civicrm/report/list',
612 "reset=1&ovid=$optionValueID"
616 if ($optionValueID) {
617 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
621 $this->assign('mode', 'template');
624 // lets display the Report Settings section
625 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
627 // Do not display Report Settings section if administer Reports permission is absent OR
628 // if report instance is reserved and administer reserved reports absent
629 if (!CRM_Core_Permission
::check('administer Reports') ||
630 ($this->_instanceValues
['is_reserved'] &&
631 !CRM_Core_Permission
::check('administer reserved reports'))
633 $this->_instanceForm
= FALSE;
636 $this->assign('criteriaForm', FALSE);
637 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
638 if (CRM_Core_Permission
::check('administer Reports') ||
639 CRM_Core_Permission
::check('access Report Criteria')
641 if (!$this->_instanceValues
['is_reserved'] ||
642 CRM_Core_Permission
::check('administer reserved reports')
644 $this->assign('criteriaForm', TRUE);
645 $this->_criteriaForm
= TRUE;
649 // Special permissions check for private instance if it's not the current contact instance
651 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
652 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
653 if (!CRM_Core_Permission
::check('access all private reports')) {
654 $this->_instanceForm
= FALSE;
655 $this->assign('criteriaForm', FALSE);
659 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
660 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
661 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
662 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
668 public function addBreadCrumb() {
672 'title' => ts('Report Templates'),
673 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
677 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
681 * Pre process function.
683 * Called prior to build form.
685 public function preProcess() {
686 $this->preProcessCommon();
689 $this->addBreadCrumb();
692 foreach ($this->_columns
as $tableName => $table) {
694 if (!isset($table['alias'])) {
695 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
699 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
702 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
704 $daoOrBaoName = NULL;
705 // higher preference to bao object
706 if (array_key_exists('bao', $table)) {
707 $daoOrBaoName = $table['bao'];
708 $expFields = $daoOrBaoName::exportableFields();
710 elseif (array_key_exists('dao', $table)) {
711 $daoOrBaoName = $table['dao'];
712 $expFields = $daoOrBaoName::export();
715 $expFields = array();
718 $doNotCopy = array('required');
720 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
721 foreach ($fieldGroups as $fieldGrp) {
722 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
723 foreach ($table[$fieldGrp] as $fieldName => $field) {
724 // $name is the field name used to reference the BAO/DAO export fields array
725 $name = isset($field['name']) ?
$field['name'] : $fieldName;
727 // Sometimes the field name key in the BAO/DAO export fields array is
728 // different from the actual database field name.
729 // Unset $field['name'] so that actual database field name can be obtained
730 // from the BAO/DAO export fields array.
731 unset($field['name']);
733 if (array_key_exists($name, $expFields)) {
734 foreach ($doNotCopy as $dnc) {
735 // unset the values we don't want to be copied.
736 unset($expFields[$name][$dnc]);
739 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
742 foreach ($expFields[$name] as $property => $val) {
743 if (!array_key_exists($property, $field)) {
744 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
751 if (!empty($field['no_repeat'])) {
752 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
754 if (!empty($field['no_display'])) {
755 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
758 // set alias = table-name, unless already set
759 $alias = isset($field['alias']) ?
$field['alias'] : (
760 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
762 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
764 // set name = fieldName, unless already set
765 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
766 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
769 // set dbAlias = alias.name, unless already set
770 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
771 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
773 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
776 // a few auto fills for filters
777 if ($fieldGrp == 'filters') {
778 // fill operator types
779 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
780 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
781 case CRM_Utils_Type
::T_MONEY
:
782 case CRM_Utils_Type
::T_FLOAT
:
783 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
786 case CRM_Utils_Type
::T_INT
:
787 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
790 case CRM_Utils_Type
::T_DATE
:
791 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
794 case CRM_Utils_Type
::T_BOOLEAN
:
795 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
796 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
797 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
808 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
810 // with multiple options operator-type is generally multi-select
811 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
812 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
814 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
825 // copy filters to a separate handy variable
826 if (array_key_exists('filters', $table)) {
827 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
830 if (array_key_exists('group_bys', $table)) {
831 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
834 if (array_key_exists('fields', $table)) {
835 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
840 $this->setDefaultValues(FALSE);
843 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
844 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
845 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
846 CRM_Report_Utils_Get
::processChart($this->_defaults
);
849 $this->_formValues
= $this->_defaults
;
850 $this->postProcess();
855 * Set default values.
857 * @param bool $freeze
861 public function setDefaultValues($freeze = TRUE) {
862 $freezeGroup = array();
864 // FIXME: generalizing form field naming conventions would reduce
865 // Lots of lines below.
866 foreach ($this->_columns
as $tableName => $table) {
867 if (array_key_exists('fields', $table)) {
868 foreach ($table['fields'] as $fieldName => $field) {
869 if (empty($field['no_display'])) {
870 if (isset($field['required'])) {
872 $this->_defaults
['fields'][$fieldName] = 1;
875 // find element object, so that we could use quickform's freeze method
876 // for required elements
877 $obj = $this->getElementFromGroup("fields", $fieldName);
879 $freezeGroup[] = $obj;
883 elseif (isset($field['default'])) {
884 $this->_defaults
['fields'][$fieldName] = $field['default'];
890 if (array_key_exists('group_bys', $table)) {
891 foreach ($table['group_bys'] as $fieldName => $field) {
892 if (isset($field['default'])) {
893 if (!empty($field['frequency'])) {
894 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
896 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
900 if (array_key_exists('filters', $table)) {
901 foreach ($table['filters'] as $fieldName => $field) {
902 if (isset($field['default'])) {
903 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
905 if (is_array($field['default'])) {
906 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
907 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
908 $this->_defaults
["{$fieldName}_relative"] = 0;
911 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
915 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
916 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
917 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
919 $this->_defaults
["{$fieldName}_value"] = $field['default'];
922 //assign default value as "in" for multiselect
923 //operator, To freeze the select element
924 if (CRM_Utils_Array
::value('operatorType', $field) ==
925 CRM_Report_Form
::OP_MULTISELECT
927 $this->_defaults
["{$fieldName}_op"] = 'in';
929 if (CRM_Utils_Array
::value('operatorType', $field) ==
930 CRM_Report_Form
::OP_ENTITYREF
932 $this->_defaults
["{$fieldName}_op"] = 'in';
934 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
935 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
937 $this->_defaults
["{$fieldName}_op"] = 'mhas';
939 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
940 $this->_defaults
["{$fieldName}_op"] = $op;
946 empty($this->_formValues
['order_bys']) &&
947 (array_key_exists('order_bys', $table) &&
948 is_array($table['order_bys']))
950 if (!array_key_exists('order_bys', $this->_defaults
)) {
951 $this->_defaults
['order_bys'] = array();
953 foreach ($table['order_bys'] as $fieldName => $field) {
954 if (!empty($field['default']) ||
!empty($field['default_order']) ||
955 CRM_Utils_Array
::value('default_is_section', $field) ||
956 !empty($field['default_weight'])
959 'column' => $fieldName,
960 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
961 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
964 if (!empty($field['default_weight'])) {
965 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
968 array_unshift($this->_defaults
['order_bys'], $order_by);
974 foreach ($this->_options
as $fieldName => $field) {
975 if (isset($field['default'])) {
976 $this->_defaults
['options'][$fieldName] = $field['default'];
981 if (!empty($this->_submitValues
)) {
982 $this->preProcessOrderBy($this->_submitValues
);
985 $this->preProcessOrderBy($this->_defaults
);
988 // lets finish freezing task here itself
989 if (!empty($freezeGroup)) {
990 foreach ($freezeGroup as $elem) {
995 if ($this->_formValues
) {
996 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
999 if ($this->_instanceValues
) {
1000 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1003 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1005 return $this->_defaults
;
1009 * Get element from group.
1011 * @param string $group
1012 * @param string $grpFieldName
1016 public function getElementFromGroup($group, $grpFieldName) {
1017 $eleObj = $this->getElement($group);
1018 foreach ($eleObj->_elements
as $index => $obj) {
1019 if ($grpFieldName == $obj->_attributes
['name']) {
1027 * Setter for $_params.
1029 * @param array $params
1031 public function setParams($params) {
1032 $this->_params
= $params;
1038 * @param int $instanceID
1040 public function setID($instanceID) {
1041 $this->_id
= $instanceID;
1045 * Setter for $_force.
1047 * @param bool $isForce
1049 public function setForce($isForce) {
1050 $this->_force
= $isForce;
1054 * Setter for $_limitValue.
1056 * @param int $_limitValue
1058 public function setLimitValue($_limitValue) {
1059 $this->_limitValue
= $_limitValue;
1063 * Setter for $_offsetValue.
1065 * @param int $_offsetValue
1067 public function setOffsetValue($_offsetValue) {
1068 $this->_offsetValue
= $_offsetValue;
1072 * Setter for $addPaging.
1074 * @param bool $value
1076 public function setAddPaging($value) {
1077 $this->addPaging
= $value;
1081 * Getter for $_defaultValues.
1085 public function getDefaultValues() {
1086 return $this->_defaults
;
1090 * Add columns to report.
1092 public function addColumns() {
1095 foreach ($this->_columns
as $tableName => $table) {
1096 if (array_key_exists('fields', $table)) {
1097 foreach ($table['fields'] as $fieldName => $field) {
1099 if (empty($field['no_display'])) {
1100 foreach (array('table', 'field') as $var) {
1101 if (!empty($
{$var}['grouping'])) {
1102 if (!is_array($
{$var}['grouping'])) {
1103 $tableName = $
{$var}['grouping'];
1106 $tableName = array_keys($
{$var}['grouping']);
1107 $tableName = $tableName[0];
1108 $groupTitle = array_values($
{$var}['grouping']);
1109 $groupTitle = $groupTitle[0];
1114 if (!$groupTitle && isset($table['group_title'])) {
1115 $groupTitle = $table['group_title'];
1116 // Having a group_title is secret code for being a custom group
1117 // which cryptically translates to needing an accordion.
1118 // here we make that explicit.
1119 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1122 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1123 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1124 $colGroups[$tableName]['group_title'] = $groupTitle;
1126 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1132 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1133 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1135 if (!empty($colGroups)) {
1136 $this->tabs
['FieldSelection'] = array(
1137 'title' => ts('Columns'),
1138 'tpl' => 'FieldSelection',
1139 'div_label' => 'col-groups',
1142 // Note this assignment is only really required in buildForm. It is being 'over-called'
1143 // to reduce risk of being missed due to overridden functions.
1144 $this->assign('tabs', $this->tabs
);
1147 $this->assign('colGroups', $colGroups);
1151 * Add filters to report.
1153 public function addFilters() {
1154 $filters = $filterGroups = array();
1157 foreach ($this->_filters
as $table => $attributes) {
1158 if (isset($this->_columns
[$table]['group_title'])) {
1159 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1160 // which magically means to 'display in an accordian'
1161 // here we make this explicit.
1162 $filterGroups[$table] = array(
1163 'group_title' => $this->_columns
[$table]['group_title'],
1164 'use_accordian_for_field_selection' => TRUE,
1168 foreach ($attributes as $fieldName => $field) {
1169 // get ready with option value pair
1170 // @ todo being able to specific options for a field (e.g a date field) in the field spec as an array rather than an override
1172 $operations = $this->getOperationPair(
1173 CRM_Utils_Array
::value('operatorType', $field),
1176 $filters[$table][$fieldName] = $field;
1178 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1179 case CRM_Report_Form
::OP_MONTH
:
1180 if (!array_key_exists('options', $field) ||
1181 !is_array($field['options']) ||
empty($field['options'])
1183 // If there's no option list for this filter, define one.
1184 $field['options'] = array(
1186 2 => ts('February'),
1193 9 => ts('September'),
1194 10 => ts('October'),
1195 11 => ts('November'),
1196 12 => ts('December'),
1198 // Add this option list to this column _columns. This is
1199 // required so that filter statistics show properly.
1200 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1202 case CRM_Report_Form
::OP_MULTISELECT
:
1203 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1204 // assume a multi-select field
1205 if (!empty($field['options']) ||
1206 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1208 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1209 if (count($operations) <= 1) {
1212 if ($fieldName == 'state_province_id' ||
1213 $fieldName == 'county_id'
1215 $this->addChainSelect($fieldName . '_value', array(
1222 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1223 'style' => 'min-width:250px',
1224 'class' => 'crm-select2 huge',
1226 'placeholder' => ts('- select -'),
1232 case CRM_Report_Form
::OP_SELECT
:
1233 // assume a select field
1234 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1235 if (!empty($field['options'])) {
1236 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1240 case CRM_Report_Form
::OP_ENTITYREF
:
1241 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1242 $this->setEntityRefDefaults($field, $table);
1243 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1246 case CRM_Report_Form
::OP_DATE
:
1247 // build datetime fields
1248 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1252 case CRM_Report_Form
::OP_DATETIME
:
1253 // build datetime fields
1254 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1258 case CRM_Report_Form
::OP_INT
:
1259 case CRM_Report_Form
::OP_FLOAT
:
1260 // and a min value input box
1261 $this->add('text', "{$fieldName}_min", ts('Min'));
1262 // and a max value input box
1263 $this->add('text', "{$fieldName}_max", ts('Max'));
1265 // default type is string
1266 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1267 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1269 // we need text box for value input
1270 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1275 if (!empty($filters)) {
1276 $this->tabs
['Filters'] = array(
1277 'title' => ts('Filters'),
1279 'div_label' => 'set-filters',
1282 $this->assign('filters', $filters);
1283 $this->assign('filterGroups', $filterGroups);
1287 * Function to assign the tabs to the template in the correct order.
1289 * We want the tabs to wind up in this order (if not overridden).
1297 protected function assignTabs() {
1305 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1306 $order = array_merge($order, $this->tabs
);
1307 $this->assign('tabs', $order);
1311 * The intent is to add a tab for developers to view the sql.
1313 * Currently using dpm.
1315 * @param string $sql
1317 protected function addToDeveloperTab($sql) {
1318 if (!CRM_Core_Permission
::check('view report sql')) {
1321 $this->tabs
['Developer'] = array(
1322 'title' => ts('Developer'),
1323 'tpl' => 'Developer',
1324 'div_label' => 'set-developer',
1327 $this->assignTabs();
1328 $this->sqlArray
[] = $sql;
1329 foreach ($this->sqlArray
as $sql) {
1330 foreach (array('LEFT JOIN') as $term) {
1331 $sql = str_replace($term, '<br>  ' . $term, $sql);
1333 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1334 $sql = str_replace($term, '<br><br>' . $term, $sql);
1336 $this->sqlFormattedArray
[] = $sql;
1337 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1342 * Add options defined in $this->_options to the report.
1344 public function addOptions() {
1345 if (!empty($this->_options
)) {
1346 // FIXME: For now lets build all elements as checkboxes.
1347 // Once we clear with the format we can build elements based on type
1349 foreach ($this->_options
as $fieldName => $field) {
1352 if ($field['type'] == 'select') {
1353 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1355 elseif ($field['type'] == 'checkbox') {
1356 $options[$field['title']] = $fieldName;
1357 $this->addCheckBox($fieldName, NULL,
1359 NULL, NULL, NULL, $this->_fourColumnAttribute
1364 if (!empty($this->_options
) &&
1366 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1368 $this->tabs
['ReportOptions'] = array(
1369 'title' => ts('Display Options'),
1370 'tpl' => 'ReportOptions',
1371 'div_label' => 'other-options',
1374 $this->assign('otherOptions', $this->_options
);
1378 * Add chart options to the report.
1380 public function addChartOptions() {
1381 if (!empty($this->_charts
)) {
1382 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1383 $this->assign('charts', $this->_charts
);
1384 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1389 * Add group by options to the report.
1391 public function addGroupBys() {
1392 $options = $freqElements = array();
1394 foreach ($this->_columns
as $tableName => $table) {
1395 if (array_key_exists('group_bys', $table)) {
1396 foreach ($table['group_bys'] as $fieldName => $field) {
1397 if (!empty($field)) {
1398 $options[$field['title']] = $fieldName;
1399 if (!empty($field['frequency'])) {
1400 $freqElements[$field['title']] = $fieldName;
1406 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1407 NULL, NULL, NULL, $this->_fourColumnAttribute
1409 $this->assign('groupByElements', $options);
1410 if (!empty($options)) {
1411 $this->tabs
['GroupBy'] = array(
1412 'title' => ts('Grouping'),
1414 'div_label' => 'group-by-elements',
1418 foreach ($freqElements as $name) {
1419 $this->addElement('select', "group_bys_freq[$name]",
1420 ts('Frequency'), $this->_groupByDateFreq
1426 * Add data for order by tab.
1428 public function addOrderBys() {
1430 foreach ($this->_columns
as $tableName => $table) {
1432 // Report developer may define any column to order by; include these as order-by options.
1433 if (array_key_exists('order_bys', $table)) {
1434 foreach ($table['order_bys'] as $fieldName => $field) {
1435 if (!empty($field)) {
1436 $options[$fieldName] = $field['title'];
1441 // Add searchable custom fields as order-by options, if so requested
1442 // (These are already indexed, so allowing to order on them is cheap.)
1444 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1445 array_key_exists('extends', $table) && !empty($table['extends'])
1447 foreach ($table['fields'] as $fieldName => $field) {
1448 if (empty($field['no_display'])) {
1449 $options[$fieldName] = $field['title'];
1457 $this->assign('orderByOptions', $options);
1458 if (!empty($options)) {
1459 $this->tabs
['OrderBy'] = array(
1460 'title' => ts('Sorting'),
1462 'div_label' => 'order-by-elements',
1466 if (!empty($options)) {
1468 '-' => ' - none - ',
1470 for ($i = 1; $i <= 5; $i++
) {
1471 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1472 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1473 'ASC' => ts('Ascending'),
1474 'DESC' => ts('Descending'),
1476 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1477 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1483 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1485 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1486 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1489 public function buildInstanceAndButtons() {
1490 CRM_Report_Form_Instance
::buildForm($this);
1491 $this->_actionButtonName
= $this->getButtonName('submit');
1492 $this->addTaskMenu($this->getActions($this->_id
));
1494 $this->assign('instanceForm', $this->_instanceForm
);
1496 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1497 $permission = CRM_Core_Permission
::getPermission();
1498 if ($permission == CRM_Core_Permission
::EDIT
&&
1499 $this->_add2groupSupported
1501 $this->addElement('select', 'groups', ts('Group'),
1502 array('' => ts('Add Contacts to Group')) +
1503 CRM_Core_PseudoConstant
::nestedGroup(),
1504 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1506 $this->assign('group', TRUE);
1509 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1511 $this->addChartOptions();
1512 $showResultsLabel = $this->getResultsLabel();
1513 $this->addButtons(array(
1516 'name' => $showResultsLabel,
1517 'isDefault' => TRUE,
1524 * Has this form been submitted already?
1528 public function resultsDisplayed() {
1529 $buttonName = $this->controller
->getButtonName();
1530 return ($buttonName ||
$this->_outputMode
);
1534 * Get the actions for this report instance.
1536 * @param int $instanceId
1540 protected function getActions($instanceId) {
1541 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1542 if (empty($instanceId)) {
1543 $actions['report_instance.save'] = array(
1544 'title' => ts('Create Report'),
1546 'is_confirm' => TRUE,
1547 'confirm_title' => ts('Create Report'),
1548 'confirm_refresh_fields' => json_encode(array(
1549 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1550 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1556 if (!$this->_csvSupported
) {
1557 unset($actions['report_instance.csv']);
1564 * Main build form function.
1566 public function buildQuickForm() {
1567 $this->addColumns();
1569 $this->addFilters();
1571 $this->addOptions();
1573 $this->addGroupBys();
1575 $this->addOrderBys();
1577 $this->buildInstanceAndButtons();
1579 // Add form rule for report.
1580 if (is_callable(array(
1584 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1586 $this->assignTabs();
1590 * A form rule function for custom data.
1592 * The rule ensures that fields selected in group_by if any) should only be the ones
1593 * present in display/select fields criteria;
1594 * note: works if and only if any custom field selected in group_by.
1596 * @param array $fields
1597 * @param array $ignoreFields
1601 public function customDataFormRule($fields, $ignoreFields = array()) {
1603 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1604 !empty($fields['group_bys'])
1606 foreach ($this->_columns
as $tableName => $table) {
1607 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1608 substr($tableName, 0, 12) == 'custom_value') &&
1609 !empty($this->_columns
[$tableName]['fields'])
1611 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1612 if (array_key_exists($fieldName, $fields['group_bys']) &&
1613 !array_key_exists($fieldName, $fields['fields'])
1615 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1617 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1618 foreach ($fields['fields'] as $fld => $val) {
1619 if (!array_key_exists($fld, $fields['group_bys']) &&
1620 !in_array($fld, $ignoreFields)
1622 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1634 * Get operators to display on form.
1636 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1638 * @param string $type
1639 * @param string $fieldName
1643 public function getOperationPair($type = "string", $fieldName = NULL) {
1644 // FIXME: At some point we should move these key-val pairs
1645 // to option_group and option_value table.
1647 case CRM_Report_Form
::OP_INT
:
1648 case CRM_Report_Form
::OP_FLOAT
:
1651 'lte' => ts('Is less than or equal to'),
1652 'gte' => ts('Is greater than or equal to'),
1653 'bw' => ts('Is between'),
1654 'eq' => ts('Is equal to'),
1655 'lt' => ts('Is less than'),
1656 'gt' => ts('Is greater than'),
1657 'neq' => ts('Is not equal to'),
1658 'nbw' => ts('Is not between'),
1659 'nll' => ts('Is empty (Null)'),
1660 'nnll' => ts('Is not empty (Null)'),
1664 case CRM_Report_Form
::OP_SELECT
:
1666 'eq' => ts('Is equal to'),
1670 case CRM_Report_Form
::OP_MONTH
:
1671 case CRM_Report_Form
::OP_MULTISELECT
:
1672 case CRM_Report_Form
::OP_ENTITYREF
:
1675 'in' => ts('Is one of'),
1676 'notin' => ts('Is not one of'),
1680 case CRM_Report_Form
::OP_DATE
:
1683 'nll' => ts('Is empty (Null)'),
1684 'nnll' => ts('Is not empty (Null)'),
1688 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1689 // use this operator for the values, concatenated with separator. For e.g if
1690 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1692 'mhas' => ts('Is one of'),
1693 'mnot' => ts('Is not one of'),
1700 'has' => ts('Contains'),
1701 'sw' => ts('Starts with'),
1702 'ew' => ts('Ends with'),
1703 'nhas' => ts('Does not contain'),
1704 'eq' => ts('Is equal to'),
1705 'neq' => ts('Is not equal to'),
1706 'nll' => ts('Is empty (Null)'),
1707 'nnll' => ts('Is not empty (Null)'),
1714 * Build the tag filter field to display on the filters tab.
1716 public function buildTagFilter() {
1717 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1718 if (!empty($contactTags)) {
1719 $this->_columns
['civicrm_tag'] = array(
1720 'dao' => 'CRM_Core_DAO_Tag',
1724 'title' => ts('Tag'),
1725 'type' => CRM_Utils_Type
::T_INT
,
1727 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1728 'options' => $contactTags,
1736 * Adds group filters to _columns (called from _Construct).
1738 public function buildGroupFilter() {
1739 $this->_columns
['civicrm_group']['filters'] = array(
1741 'name' => 'group_id',
1742 'title' => ts('Group'),
1743 'type' => CRM_Utils_Type
::T_INT
,
1744 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1746 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1749 if (empty($this->_columns
['civicrm_group']['dao'])) {
1750 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1752 if (empty($this->_columns
['civicrm_group']['alias'])) {
1753 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1758 * Get SQL operator from form text version.
1760 * @param string $operator
1764 public function getSQLOperator($operator = "like") {
1765 switch ($operator) {
1798 return 'IS NOT NULL';
1807 * Generate where clause.
1809 * This can be overridden in reports for special treatment of a field
1811 * @param array $field Field specifications
1812 * @param string $op Query operator (not an exact match to sql)
1813 * @param mixed $value
1817 * @return null|string
1819 public function whereClause(&$field, $op, $value, $min, $max) {
1821 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1823 // CRM-18010: Ensure type of each report filters
1825 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1832 if (($min !== NULL && strlen($min) > 0) ||
1833 ($max !== NULL && strlen($max) > 0)
1837 $min = CRM_Utils_Type
::escape($min, $type);
1839 $clauses[] = "( {$field['dbAlias']} >= $min )";
1842 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1846 $max = CRM_Utils_Type
::escape($max, $type);
1848 $clauses[] = "( {$field['dbAlias']} <= $max )";
1851 $clauses[] = "( {$field['dbAlias']} > $max )";
1855 if (!empty($clauses)) {
1857 $clause = implode(' AND ', $clauses);
1860 $clause = '(' . implode('OR', $clauses) . ')';
1868 if ($value !== NULL && strlen($value) > 0) {
1869 $value = CRM_Utils_Type
::escape($value, $type);
1870 if (strpos($value, '%') === FALSE) {
1871 $value = "'%{$value}%'";
1874 $value = "'{$value}'";
1876 $sqlOP = $this->getSQLOperator($op);
1877 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1883 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1884 $value = explode(',', $value);
1886 if ($value !== NULL && is_array($value) && count($value) > 0) {
1887 $sqlOP = $this->getSQLOperator($op);
1888 if (CRM_Utils_Array
::value('type', $field) ==
1889 CRM_Utils_Type
::T_STRING
1891 //cycle through selections and escape values
1892 foreach ($value as $key => $selection) {
1893 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1896 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1900 // for numerical values
1901 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1904 if ($op == 'notin') {
1905 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1908 $clause = "( " . $clause . " )";
1915 // multiple has or multiple not
1916 if ($value !== NULL && count($value) > 0) {
1917 $value = CRM_Utils_Type
::escapeAll($value, $type);
1918 $operator = $op == 'mnot' ?
'NOT' : '';
1919 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1920 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1926 if ($value !== NULL && strlen($value) > 0) {
1927 $value = CRM_Utils_Type
::escape($value, $type);
1928 if (strpos($value, '%') === FALSE) {
1930 $value = "'{$value}%'";
1933 $value = "'%{$value}'";
1937 $value = "'{$value}'";
1939 $sqlOP = $this->getSQLOperator($op);
1940 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1946 $sqlOP = $this->getSQLOperator($op);
1947 $clause = "( {$field['dbAlias']} $sqlOP )";
1953 //CRM-18457: some custom field passes value in array format against binary operator
1954 if (is_array($value) && count($value)) {
1959 if ($value !== NULL && $value !== '') {
1960 if (isset($field['clause'])) {
1961 // FIXME: we not doing escape here. Better solution is to use two
1962 // different types - data-type and filter-type
1963 $clause = $field['clause'];
1965 elseif (!is_array($value)) {
1966 $value = CRM_Utils_Type
::escape($value, $type);
1967 $sqlOP = $this->getSQLOperator($op);
1968 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1969 $value = "'{$value}'";
1971 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1977 if (!empty($field['group']) && $clause) {
1978 $clause = $this->whereGroupClause($field, $value, $op);
1980 elseif (!empty($field['tag']) && $clause) {
1981 // not using left join in query because if any contact
1982 // belongs to more than one tag, results duplicate
1984 $clause = $this->whereTagClause($field, $value, $op);
1986 elseif (!empty($field['membership_org']) && $clause) {
1987 $clause = $this->whereMembershipOrgClause($value, $op);
1989 elseif (!empty($field['membership_type']) && $clause) {
1990 $clause = $this->whereMembershipTypeClause($value, $op);
1996 * Get SQL where clause for a date field.
1998 * @param string $fieldName
1999 * @param string $relative
2000 * @param string $from
2002 * @param string $type
2003 * @param string $fromTime
2004 * @param string $toTime
2006 * @return null|string
2008 public function dateClause(
2010 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2013 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2014 $sqlOP = $this->getSQLOperator($relative);
2015 return "( {$fieldName} {$sqlOP} )";
2018 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2021 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2022 $clauses[] = "( {$fieldName} >= $from )";
2026 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2027 $clauses[] = "( {$fieldName} <= {$to} )";
2030 if (!empty($clauses)) {
2031 return implode(' AND ', $clauses);
2038 * Get values for from and to for date ranges.
2040 * @param bool $relative
2041 * @param string $from
2043 * @param string $fromTime
2044 * @param string $toTime
2048 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2049 if (empty($toTime)) {
2052 //FIX ME not working for relative
2054 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2055 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2056 $from = substr($dateRange['from'], 0, 8);
2057 //Take only Date Part, Sometime Time part is also present in 'to'
2058 $to = substr($dateRange['to'], 0, 8);
2060 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2061 $to = CRM_Utils_Date
::processDate($to, $toTime);
2062 return array($from, $to);
2066 * Alter display of rows.
2068 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2069 * such as rendering contacts as links.
2071 * @param array $rows
2072 * Rows generated by SQL, with an array for each row.
2074 public function alterDisplay(&$rows) {
2078 * Alter the way in which custom data fields are displayed.
2080 * @param array $rows
2082 public function alterCustomDataDisplay(&$rows) {
2083 // custom code to alter rows having custom values
2084 if (empty($this->_customGroupExtends
)) {
2088 $customFields = array();
2089 $customFieldIds = array();
2090 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2091 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2092 $customFieldIds[$fieldAlias] = $fieldId;
2095 if (empty($customFieldIds)) {
2099 // skip for type date and ContactReference since date format is already handled
2101 SELECT cg.table_name, cf.id
2102 FROM civicrm_custom_field cf
2103 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2104 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2105 cg.is_active = 1 AND
2106 cf.is_active = 1 AND
2107 cf.is_searchable = 1 AND
2108 cf.data_type NOT IN ('ContactReference', 'Date') AND
2109 cf.id IN (" . implode(",", $customFieldIds) . ")";
2111 $dao = CRM_Core_DAO
::executeQuery($query);
2112 while ($dao->fetch()) {
2113 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2117 $entryFound = FALSE;
2118 foreach ($rows as $rowNum => $row) {
2119 foreach ($row as $tableCol => $val) {
2120 if (array_key_exists($tableCol, $customFields)) {
2121 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2126 // skip looking further in rows, if first row itself doesn't
2127 // have the column we need
2135 * Remove duplicate rows.
2137 * @param array $rows
2139 public function removeDuplicates(&$rows) {
2140 if (empty($this->_noRepeats
)) {
2143 $checkList = array();
2145 foreach ($rows as $key => $list) {
2146 foreach ($list as $colName => $colVal) {
2147 if (array_key_exists($colName, $checkList) &&
2148 $checkList[$colName] == $colVal
2150 $rows[$key][$colName] = "";
2152 if (in_array($colName, $this->_noRepeats
)) {
2153 $checkList[$colName] = $colVal;
2160 * Fix subtotal display.
2163 * @param array $fields
2164 * @param bool $subtotal
2166 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2167 foreach ($row as $colName => $colVal) {
2168 if (in_array($colName, $fields)) {
2170 elseif (isset($this->_columnHeaders
[$colName])) {
2172 $row[$colName] = 'Subtotal';
2176 unset($row[$colName]);
2183 * Calculate grant total.
2185 * @param array $rows
2189 public function grandTotal(&$rows) {
2190 if (!$this->_rollup ||
count($rows) == 1) {
2194 $this->moveSummaryColumnsToTheRightHandSide();
2196 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2200 $this->rollupRow
= array_pop($rows);
2202 foreach ($this->_columnHeaders
as $fld => $val) {
2203 if (!in_array($fld, $this->_statFields
)) {
2204 if (!$this->_grandFlag
) {
2205 $this->rollupRow
[$fld] = ts('Grand Total');
2206 $this->_grandFlag
= TRUE;
2209 $this->rollupRow
[$fld] = "";
2214 $this->assign('grandStat', $this->rollupRow
);
2219 * Format display output.
2221 * @param array $rows
2222 * @param bool $pager
2224 public function formatDisplay(&$rows, $pager = TRUE) {
2225 // set pager based on if any limit was applied in the query.
2230 // allow building charts if any
2231 if (!empty($this->_params
['charts']) && !empty($rows)) {
2232 $this->buildChart($rows);
2233 $this->assign('chartEnabled', TRUE);
2234 $this->_chartId
= "{$this->_params['charts']}_" .
2235 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2237 $this->assign('chartId', $this->_chartId
);
2240 // unset columns not to be displayed.
2241 foreach ($this->_columnHeaders
as $key => $value) {
2242 if (!empty($value['no_display'])) {
2243 unset($this->_columnHeaders
[$key]);
2247 // unset columns not to be displayed.
2248 if (!empty($rows)) {
2249 foreach ($this->_noDisplay
as $noDisplayField) {
2250 foreach ($rows as $rowNum => $row) {
2251 unset($this->_columnHeaders
[$noDisplayField]);
2256 // build array of section totals
2257 $this->sectionTotals();
2259 // process grand-total row
2260 $this->grandTotal($rows);
2262 // use this method for formatting rows for display purpose.
2263 $this->alterDisplay($rows);
2264 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2266 // use this method for formatting custom rows for display purpose.
2267 $this->alterCustomDataDisplay($rows);
2273 * @param array $rows
2275 public function buildChart(&$rows) {
2276 // override this method for building charts.
2279 // select() method below has been added recently (v3.3), and many of the report templates might
2280 // still be having their own select() method. We should fix them as and when encountered and move
2281 // towards generalizing the select() method below.
2284 * Generate the SELECT clause and set class variable $_select.
2286 public function select() {
2287 $select = $this->_selectAliases
= array();
2289 foreach ($this->_columns
as $tableName => $table) {
2290 if (array_key_exists('fields', $table)) {
2291 foreach ($table['fields'] as $fieldName => $field) {
2292 if ($tableName == 'civicrm_address') {
2293 $this->_addressField
= TRUE;
2295 if ($tableName == 'civicrm_email') {
2296 $this->_emailField
= TRUE;
2298 if ($tableName == 'civicrm_phone') {
2299 $this->_phoneField
= TRUE;
2302 if (!empty($field['required']) ||
2303 !empty($this->_params
['fields'][$fieldName])
2306 // 1. In many cases we want select clause to be built in slightly different way
2307 // for a particular field of a particular type.
2308 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2310 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2311 if ($selectClause) {
2312 $select[] = $selectClause;
2316 // include statistics columns only if set
2317 if (!empty($field['statistics'])) {
2318 foreach ($field['statistics'] as $stat => $label) {
2319 $alias = "{$tableName}_{$fieldName}_{$stat}";
2320 switch (strtolower($stat)) {
2323 $select[] = "$stat({$field['dbAlias']}) as $alias";
2324 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2325 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2326 $this->_statFields
[$label] = $alias;
2327 $this->_selectAliases
[] = $alias;
2331 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2332 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2333 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2334 $this->_statFields
[$label] = $alias;
2335 $this->_selectAliases
[] = $alias;
2338 case 'count_distinct':
2339 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2340 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2341 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2342 $this->_statFields
[$label] = $alias;
2343 $this->_selectAliases
[] = $alias;
2347 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2348 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2349 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2350 $this->_statFields
[$label] = $alias;
2351 $this->_selectAliases
[] = $alias;
2357 $alias = "{$tableName}_{$fieldName}";
2358 $select[] = "{$field['dbAlias']} as $alias";
2359 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2360 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2361 $this->_selectAliases
[] = $alias;
2367 // select for group bys
2368 if (array_key_exists('group_bys', $table)) {
2369 foreach ($table['group_bys'] as $fieldName => $field) {
2371 if ($tableName == 'civicrm_address') {
2372 $this->_addressField
= TRUE;
2374 if ($tableName == 'civicrm_email') {
2375 $this->_emailField
= TRUE;
2377 if ($tableName == 'civicrm_phone') {
2378 $this->_phoneField
= TRUE;
2380 // 1. In many cases we want select clause to be built in slightly different way
2381 // for a particular field of a particular type.
2382 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2384 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2385 if ($selectClause) {
2386 $select[] = $selectClause;
2390 if (!empty($this->_params
['group_bys']) &&
2391 !empty($this->_params
['group_bys'][$fieldName]) &&
2392 !empty($this->_params
['group_bys_freq'])
2394 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2396 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2397 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2398 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2399 $field['title'] = 'Week';
2403 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2404 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2405 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2406 $field['title'] = 'Year';
2410 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2411 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2412 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2413 $field['title'] = 'Month';
2417 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2418 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2419 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2420 $field['title'] = 'Quarter';
2423 // for graphs and charts -
2424 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2425 $this->_interval
= $field['title'];
2426 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2427 = $field['title'] . ' Beginning';
2428 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2429 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2431 // just to make sure these values are transferred to rows.
2432 // since we 'll need them for calculation purpose,
2433 // e.g making subtotals look nicer or graphs
2434 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2435 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2442 $this->_selectClauses
= $select;
2443 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2447 * Build select clause for a single field.
2449 * @param string $tableName
2450 * @param string $tableKey
2451 * @param string $fieldName
2452 * @param string $field
2456 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2461 * Build where clause.
2463 public function where() {
2464 $this->storeWhereHavingClauseArray();
2466 if (empty($this->_whereClauses
)) {
2467 $this->_where
= "WHERE ( 1 ) ";
2468 $this->_having
= "";
2471 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2474 if ($this->_aclWhere
) {
2475 $this->_where
.= " AND {$this->_aclWhere} ";
2478 if (!empty($this->_havingClauses
)) {
2479 // use this clause to construct group by clause.
2480 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2485 * Store Where clauses into an array.
2487 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2488 * temp table that may not be part of the final where clause or added
2489 * in other functions
2491 public function storeWhereHavingClauseArray() {
2492 foreach ($this->_columns
as $tableName => $table) {
2493 if (array_key_exists('filters', $table)) {
2494 foreach ($table['filters'] as $fieldName => $field) {
2495 // respect pseudofield to filter spec so fields can be marked as
2496 // not to be handled here
2497 if (!empty($field['pseudofield'])) {
2501 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2502 if (CRM_Utils_Array
::value('operatorType', $field) ==
2503 CRM_Report_Form
::OP_MONTH
2505 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2506 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2507 if (is_array($value) && !empty($value)) {
2509 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2514 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2515 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2516 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2517 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2518 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2519 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2523 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2525 $clause = $this->whereClause($field,
2527 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2528 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2529 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2534 if (!empty($clause)) {
2535 if (!empty($field['having'])) {
2536 $this->_havingClauses
[] = $clause;
2539 $this->_whereClauses
[] = $clause;
2551 public function processReportMode() {
2552 $this->setOutputMode();
2555 = CRM_Utils_Request
::retrieve(
2558 CRM_Core_DAO
::$_nullObject
2561 $this->_absoluteUrl
= FALSE;
2563 $this->assign('printOnly', FALSE);
2565 if ($this->_outputMode
== 'print' ||
2566 ($this->_sendmail
&& !$this->_outputMode
)
2568 $this->assign('printOnly', TRUE);
2570 $this->addPaging
= FALSE;
2571 $this->assign('outputMode', 'print');
2572 $this->_outputMode
= 'print';
2573 if ($this->_sendmail
) {
2574 $this->_absoluteUrl
= TRUE;
2577 elseif ($this->_outputMode
== 'pdf') {
2579 $this->addPaging
= FALSE;
2580 $this->_absoluteUrl
= TRUE;
2582 elseif ($this->_outputMode
== 'csv') {
2584 $this->_absoluteUrl
= TRUE;
2585 $this->addPaging
= FALSE;
2587 elseif ($this->_outputMode
== 'group') {
2588 $this->assign('outputMode', 'group');
2590 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2591 $this->assign('outputMode', 'create_report');
2593 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2594 $this->_createNew
= TRUE;
2597 $this->assign('outputMode', $this->_outputMode
);
2598 $this->assign('printOnly', $printOnly);
2599 // Get today's date to include in printed reports
2601 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2602 $this->assign('reportDate', $reportDate);
2607 * Post Processing function for Form.
2609 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2610 * This function is not accessed when the api calls the report.
2612 public function beginPostProcess() {
2613 $this->setParams($this->controller
->exportValues($this->_name
));
2614 if (empty($this->_params
) &&
2617 $this->setParams($this->_formValues
);
2620 // hack to fix params when submitted from dashboard, CRM-8532
2621 // fields array is missing because form building etc is skipped
2622 // in dashboard mode for report
2623 //@todo - this could be done in the dashboard no we have a setter
2624 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2625 $this->setParams($this->_formValues
);
2628 $this->processReportMode();
2630 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2631 $this->_createNew
= ($this->_outputMode
== 'copy');
2632 CRM_Report_Form_Instance
::postProcess($this);
2634 if ($this->_outputMode
== 'delete') {
2635 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2638 $this->_formValues
= $this->_params
;
2640 $this->beginPostProcessCommon();
2644 * BeginPostProcess function run in both report mode and non-report mode (api).
2646 public function beginPostProcessCommon() {
2650 * Build the report query.
2652 * @param bool $applyLimit
2656 public function buildQuery($applyLimit = TRUE) {
2657 $this->buildGroupTempTable();
2660 $this->customDataFrom();
2662 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2663 $this->getPermissionedFTQuery($this);
2668 // order_by columns not selected for display need to be included in SELECT
2669 $unselectedSectionColumns = $this->unselectedSectionColumns();
2670 foreach ($unselectedSectionColumns as $alias => $section) {
2671 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2674 if ($applyLimit && empty($this->_params
['charts'])) {
2677 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2679 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2680 $this->addToDeveloperTab($sql);
2685 * Build group by clause.
2687 public function groupBy() {
2688 $groupBys = array();
2689 if (!empty($this->_params
['group_bys']) &&
2690 is_array($this->_params
['group_bys'])
2692 foreach ($this->_columns
as $tableName => $table) {
2693 if (array_key_exists('group_bys', $table)) {
2694 foreach ($table['group_bys'] as $fieldName => $field) {
2695 if (!empty($this->_params
['group_bys'][$fieldName])) {
2696 $groupBys[] = $field['dbAlias'];
2703 if (!empty($groupBys)) {
2704 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBys);
2709 * Build order by clause.
2711 public function orderBy() {
2712 $this->_orderBy
= "";
2713 $this->_sections
= array();
2714 $this->storeOrderByArray();
2715 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2716 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2718 $this->assign('sections', $this->_sections
);
2722 * Extract order by fields and store as an array.
2724 * In some cases other functions want to know which fields are selected for ordering by
2725 * Separating this into a separate function allows it to be called separately from constructing
2726 * the order by clause
2728 public function storeOrderByArray() {
2729 $orderBys = array();
2731 if (!empty($this->_params
['order_bys']) &&
2732 is_array($this->_params
['order_bys']) &&
2733 !empty($this->_params
['order_bys'])
2736 // Process order_bys in user-specified order
2737 foreach ($this->_params
['order_bys'] as $orderBy) {
2738 $orderByField = array();
2739 foreach ($this->_columns
as $tableName => $table) {
2740 if (array_key_exists('order_bys', $table)) {
2741 // For DAO columns defined in $this->_columns
2742 $fields = $table['order_bys'];
2744 elseif (array_key_exists('extends', $table)) {
2745 // For custom fields referenced in $this->_customGroupExtends
2746 $fields = CRM_Utils_Array
::value('fields', $table, array());
2751 if (!empty($fields) && is_array($fields)) {
2752 foreach ($fields as $fieldName => $field) {
2753 if ($fieldName == $orderBy['column']) {
2754 $orderByField = array_merge($field, $orderBy);
2755 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2762 if (!empty($orderByField)) {
2763 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2764 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2766 // Record any section headers for assignment to the template
2767 if (!empty($orderBy['section'])) {
2768 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2769 $this->_sections
[$orderByField['tplField']] = $orderByField;
2775 $this->_orderByArray
= $orderBys;
2777 $this->assign('sections', $this->_sections
);
2781 * Determine unselected columns.
2785 public function unselectedSectionColumns() {
2786 if (is_array($this->_sections
)) {
2787 return array_diff_key($this->_sections
, $this->getSelectColumns());
2795 * Build output rows.
2797 * @param string $sql
2798 * @param array $rows
2800 public function buildRows($sql, &$rows) {
2801 $dao = CRM_Core_DAO
::executeQuery($sql);
2802 if (!is_array($rows)) {
2806 // use this method to modify $this->_columnHeaders
2807 $this->modifyColumnHeaders();
2809 $unselectedSectionColumns = $this->unselectedSectionColumns();
2811 while ($dao->fetch()) {
2813 foreach ($this->_columnHeaders
as $key => $value) {
2814 if (property_exists($dao, $key)) {
2815 $row[$key] = $dao->$key;
2819 // section headers not selected for display need to be added to row
2820 foreach ($unselectedSectionColumns as $key => $values) {
2821 if (property_exists($dao, $key)) {
2822 $row[$key] = $dao->$key;
2831 * Calculate section totals.
2833 * When "order by" fields are marked as sections, this assigns to the template
2834 * an array of total counts for each section. This data is used by the Smarty
2835 * plugin {sectionTotal}.
2837 public function sectionTotals() {
2839 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2840 if (empty($this->_selectAliases
)) {
2844 if (!empty($this->_sections
)) {
2845 // build the query with no LIMIT clause
2846 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2847 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2849 // pull section aliases out of $this->_sections
2850 $sectionAliases = array_keys($this->_sections
);
2853 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2854 $ifnulls[] = "ifnull($alias, '') as $alias";
2856 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2857 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2859 // Group (un-limited) report by all aliases and get counts. This might
2860 // be done more efficiently when the contents of $sql are known, ie. by
2861 // overriding this method in the report class.
2863 $query = $this->_select
.
2864 ", count(*) as ct from ($sql) as subquery group by " .
2865 implode(", ", $sectionAliases);
2867 // initialize array of total counts
2869 $dao = CRM_Core_DAO
::executeQuery($query);
2870 while ($dao->fetch()) {
2872 // let $this->_alterDisplay translate any integer ids to human-readable values.
2873 $rows[0] = $dao->toArray();
2874 $this->alterDisplay($rows);
2877 // add totals for all permutations of section values
2880 $aliasCount = count($sectionAliases);
2881 foreach ($sectionAliases as $alias) {
2882 $values[] = $row[$alias];
2883 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2884 if ($i == $aliasCount) {
2885 // the last alias is the lowest-level section header; use count as-is
2886 $totals[$key] = $dao->ct
;
2889 // other aliases are higher level; roll count into their total
2890 $totals[$key] +
= $dao->ct
;
2894 $this->assign('sectionTotals', $totals);
2899 * Modify column headers.
2901 public function modifyColumnHeaders() {
2902 // use this method to modify $this->_columnHeaders
2906 * Move totals columns to the right edge of the table.
2908 * It seems like a more logical layout to have any totals columns on the far right regardless of
2909 * the location of the rest of their table.
2911 public function moveSummaryColumnsToTheRightHandSide() {
2912 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2913 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2917 * Assign rows to the template.
2919 * @param array $rows
2921 public function doTemplateAssignment(&$rows) {
2922 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2923 $this->assign_by_ref('rows', $rows);
2924 $this->assign('statistics', $this->statistics($rows));
2928 * Build report statistics.
2930 * Override this method to build your own statistics.
2932 * @param array $rows
2936 public function statistics(&$rows) {
2937 $statistics = array();
2939 $count = count($rows);
2940 // Why do we increment the count for rollup seems to artificially inflate the count.
2941 // It seems perhaps intentional to include the summary row in the count of results - although
2942 // this just seems odd.
2943 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2947 $this->countStat($statistics, $count);
2949 $this->groupByStat($statistics);
2951 $this->filterStat($statistics);
2957 * Add count statistics.
2959 * @param array $statistics
2962 public function countStat(&$statistics, $count) {
2963 $statistics['counts']['rowCount'] = array(
2964 'title' => ts('Row(s) Listed'),
2968 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2969 $statistics['counts']['rowsFound'] = array(
2970 'title' => ts('Total Row(s)'),
2971 'value' => $this->_rowsFound
,
2977 * Add group by statistics.
2979 * @param array $statistics
2981 public function groupByStat(&$statistics) {
2982 if (!empty($this->_params
['group_bys']) &&
2983 is_array($this->_params
['group_bys']) &&
2984 !empty($this->_params
['group_bys'])
2986 foreach ($this->_columns
as $tableName => $table) {
2987 if (array_key_exists('group_bys', $table)) {
2988 foreach ($table['group_bys'] as $fieldName => $field) {
2989 if (!empty($this->_params
['group_bys'][$fieldName])) {
2990 $combinations[] = $field['title'];
2995 $statistics['groups'][] = array(
2996 'title' => ts('Grouping(s)'),
2997 'value' => implode(' & ', $combinations),
3003 * Filter statistics.
3005 * @param array $statistics
3007 public function filterStat(&$statistics) {
3008 foreach ($this->_columns
as $tableName => $table) {
3009 if (array_key_exists('filters', $table)) {
3010 foreach ($table['filters'] as $fieldName => $field) {
3011 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3012 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3013 CRM_Utils_Array
::value('operatorType', $field) !=
3014 CRM_Report_Form
::OP_MONTH
3018 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3019 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3020 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3021 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3022 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3024 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3025 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3027 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3028 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3031 $statistics['filters'][] = array(
3032 'title' => $field['title'],
3033 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3036 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3037 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3039 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3040 $statistics['filters'][] = array(
3041 'title' => $field['title'],
3042 'value' => $pair[$rel],
3047 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3050 $pair = $this->getOperationPair(
3051 CRM_Utils_Array
::value('operatorType', $field),
3054 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3055 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3056 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3057 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3058 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3060 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3061 $this->setEntityRefDefaults($field, $tableName);
3062 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3063 array('id' => $val) +
3064 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3066 foreach ($result['values'] as $v) {
3067 $values[] = $v['label'];
3069 $value = "{$pair[$op]} " . implode(', ', $values);
3071 elseif ($op == 'nll' ||
$op == 'nnll') {
3072 $value = $pair[$op];
3074 elseif (is_array($val) && (!empty($val))) {
3075 $options = CRM_Utils_Array
::value('options', $field, array());
3076 foreach ($val as $key => $valIds) {
3077 if (isset($options[$valIds])) {
3078 $val[$key] = $options[$valIds];
3081 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3082 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3083 $val = implode(', ', $val);
3084 $value = "{$pair[$op]} " . $val;
3086 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3087 isset($field['options']) &&
3088 is_array($field['options']) && !empty($field['options'])
3090 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3091 CRM_Utils_Array
::value($val, $field['options'], $val);
3094 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3098 $statistics['filters'][] = array(
3099 'title' => CRM_Utils_Array
::value('title', $field),
3110 * End post processing.
3112 * @param array|null $rows
3114 public function endPostProcess(&$rows = NULL) {
3115 $this->assign('report_class', get_class($this));
3116 if ($this->_storeResultSet
) {
3117 $this->_resultSet
= $rows;
3120 if ($this->_outputMode
== 'print' ||
3121 $this->_outputMode
== 'pdf' ||
3125 $content = $this->compileContent();
3126 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3130 if ($this->_sendmail
) {
3131 $config = CRM_Core_Config
::singleton();
3132 $attachments = array();
3134 if ($this->_outputMode
== 'csv') {
3136 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3137 ": {$url}</p>" . '<p>' .
3138 ts('The report is attached as a CSV file.') . '</p>' .
3139 $this->_formValues
['report_footer'];
3141 $csvFullFilename = $config->templateCompileDir
.
3142 CRM_Utils_File
::makeFileName('CiviReport.csv');
3143 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3144 file_put_contents($csvFullFilename, $csvContent);
3145 $attachments[] = array(
3146 'fullPath' => $csvFullFilename,
3147 'mime_type' => 'text/csv',
3148 'cleanName' => 'CiviReport.csv',
3151 if ($this->_outputMode
== 'pdf') {
3152 // generate PDF content
3153 $pdfFullFilename = $config->templateCompileDir
.
3154 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3155 file_put_contents($pdfFullFilename,
3156 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3157 TRUE, array('orientation' => 'landscape')
3160 // generate Email Content
3162 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3163 ": {$url}</p>" . '<p>' .
3164 ts('The report is attached as a PDF file.') . '</p>' .
3165 $this->_formValues
['report_footer'];
3167 $attachments[] = array(
3168 'fullPath' => $pdfFullFilename,
3169 'mime_type' => 'application/pdf',
3170 'cleanName' => 'CiviReport.pdf',
3174 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3175 $this->_outputMode
, $attachments
3178 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3181 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3185 elseif ($this->_outputMode
== 'print') {
3189 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3190 $config = CRM_Core_Config
::singleton();
3191 //get chart image name
3192 $chartImg = $this->_chartId
. '.png';
3193 //get image url path
3195 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3197 $uploadUrl .= $chartImg;
3198 //get image doc path to overwrite
3200 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3201 'openFlashChart/' . $chartImg;
3203 $chart = imagecreatefrompng($uploadUrl);
3204 //convert it into formatted png
3205 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3206 //overwrite with same image
3207 imagepng($chart, $uploadImg);
3209 imagedestroy($chart);
3211 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3213 CRM_Utils_System
::civiExit();
3215 elseif ($this->_outputMode
== 'csv') {
3216 CRM_Report_Utils_Report
::export2csv($this, $rows);
3218 elseif ($this->_outputMode
== 'group') {
3219 $group = $this->_params
['groups'];
3220 $this->add2group($group);
3225 * Set store result set indicator to TRUE.
3227 * @todo explain what this does
3229 public function storeResultSet() {
3230 $this->_storeResultSet
= TRUE;
3238 public function getResultSet() {
3239 return $this->_resultSet
;
3243 * Get the sql used to generate the report.
3247 public function getReportSql() {
3248 return $this->sqlArray
;
3252 * Use the form name to create the tpl file name.
3256 public function getTemplateFileName() {
3257 $defaultTpl = parent
::getTemplateFileName();
3258 $template = CRM_Core_Smarty
::singleton();
3259 if (!$template->template_exists($defaultTpl)) {
3260 $defaultTpl = 'CRM/Report/Form.tpl';
3266 * Compile the report content.
3268 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3272 public function compileContent() {
3273 $templateFile = $this->getHookedTemplateFileName();
3274 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3275 CRM_Core_Form
::$_template->fetch($templateFile) .
3276 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3281 * Post process function.
3283 public function postProcess() {
3284 // get ready with post process params
3285 $this->beginPostProcess();
3288 $sql = $this->buildQuery();
3290 // build array of result based on column headers. This method also allows
3291 // modifying column headers before using it to build result set i.e $rows.
3293 $this->buildRows($sql, $rows);
3295 // format result set.
3296 $this->formatDisplay($rows);
3298 // assign variables to templates
3299 $this->doTemplateAssignment($rows);
3301 // do print / pdf / instance stuff if needed
3302 $this->endPostProcess($rows);
3308 * @param int $rowCount
3312 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3313 // lets do the pager if in html mode
3314 $this->_limit
= NULL;
3316 // CRM-14115, over-ride row count if rowCount is specified in URL
3317 if ($this->_dashBoardRowCount
) {
3318 $rowCount = $this->_dashBoardRowCount
;
3320 if ($this->addPaging
) {
3321 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3323 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3325 // @todo all http vars should be extracted in the preProcess
3326 // - not randomly in the class
3327 if (!$pageId && !empty($_POST)) {
3328 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3329 $pageId = max((int) $_POST['crmPID_B'], 1);
3331 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3332 $pageId = max((int) $_POST['crmPID'], 1);
3334 unset($_POST['crmPID_B'], $_POST['crmPID']);
3337 $pageId = $pageId ?
$pageId : 1;
3338 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3339 $offset = ($pageId - 1) * $rowCount;
3341 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3342 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3344 $this->_limit
= " LIMIT $offset, $rowCount";
3345 return array($offset, $rowCount);
3347 if ($this->_limitValue
) {
3348 if ($this->_offsetValue
) {
3349 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3352 $this->_limit
= " LIMIT " . $this->_limitValue
;
3360 * @param int $rowCount
3362 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3363 // CRM-14115, over-ride row count if rowCount is specified in URL
3364 if ($this->_dashBoardRowCount
) {
3365 $rowCount = $this->_dashBoardRowCount
;
3368 if ($this->_limit
&& ($this->_limit
!= '')) {
3369 if (!$this->_rowsFound
) {
3370 $sql = "SELECT FOUND_ROWS();";
3371 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3374 'total' => $this->_rowsFound
,
3375 'rowCount' => $rowCount,
3376 'status' => ts('Records') . ' %%StatusMessage%%',
3377 'buttonBottom' => 'PagerBottomButton',
3378 'buttonTop' => 'PagerTopButton',
3380 if (!empty($this->controller
)) {
3381 // This happens when being called from the api Really we want the api to be able to
3382 // pass paging parameters, but at this stage just preventing test crashes.
3383 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3386 $pager = new CRM_Utils_Pager($params);
3387 $this->assign_by_ref('pager', $pager);
3388 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3393 * Build a group filter with contempt for large data sets.
3395 * This function has been retained as it takes time to migrate the reports over
3396 * to the new method which will not crash on large datasets.
3400 * @param string $field
3401 * @param mixed $value
3406 public function legacySlowGroupFilterClause($field, $value, $op) {
3407 $smartGroupQuery = "";
3409 $group = new CRM_Contact_DAO_Group();
3410 $group->is_active
= 1;
3412 $smartGroups = array();
3413 while ($group->fetch()) {
3414 if (in_array($group->id
, $this->_params
['gid_value']) &&
3415 $group->saved_search_id
3417 $smartGroups[] = $group->id
;
3421 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3423 $smartGroupQuery = '';
3424 if (!empty($smartGroups)) {
3425 $smartGroups = implode(',', $smartGroups);
3426 $smartGroupQuery = " UNION DISTINCT
3427 SELECT DISTINCT smartgroup_contact.contact_id
3428 FROM civicrm_group_contact_cache smartgroup_contact
3429 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3432 $sqlOp = $this->getSQLOperator($op);
3433 if (!is_array($value)) {
3434 $value = array($value);
3436 //include child groups if any
3437 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3439 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3441 $contactAlias = $this->_aliases
['civicrm_contact'];
3442 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3443 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3445 return " {$contactAlias}.id {$sqlOp} (
3446 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3447 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3448 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3449 {$smartGroupQuery} ) ";
3453 * Build where clause for groups.
3455 * @param string $field
3456 * @param mixed $value
3461 public function whereGroupClause($field, $value, $op) {
3462 if ($this->groupFilterNotOptimised
) {
3463 return $this->legacySlowGroupFilterClause($field, $value, $op);
3465 if ($op === 'notin') {
3466 return " group_temp_table.id IS NULL ";
3468 // We will have used an inner join instead.
3474 * Create a table of the contact ids included by the group filter.
3476 * This function is called by both the api (tests) and the UI.
3478 public function buildGroupTempTable() {
3479 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3482 $filteredGroups = (array) $this->_params
['gid_value'];
3484 $groups = civicrm_api3('Group', 'get', array(
3486 'id' => array('IN' => $filteredGroups),
3487 'saved_search_id' => array('>' => 0),
3490 $smartGroups = array_keys($groups['values']);
3493 SELECT group_contact.contact_id as id
3494 FROM civicrm_group_contact group_contact
3495 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3496 AND group_contact.status = 'Added' ";
3498 if (!empty($smartGroups)) {
3499 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3500 $smartGroups = implode(',', $smartGroups);
3503 SELECT smartgroup_contact.contact_id as id
3504 FROM civicrm_group_contact_cache smartgroup_contact
3505 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3508 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3509 $this->executeReportQuery("
3510 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3513 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3517 * Execute query and add it to the developer tab.
3519 * @param string $query
3520 * @param array $params
3522 * @return \CRM_Core_DAO|object
3524 protected function executeReportQuery($query, $params = array()) {
3525 $this->addToDeveloperTab($query);
3526 return CRM_Core_DAO
::executeQuery($query, $params);
3530 * Build where clause for tags.
3532 * @param string $field
3533 * @param mixed $value
3538 public function whereTagClause($field, $value, $op) {
3539 // not using left join in query because if any contact
3540 // belongs to more than one tag, results duplicate
3542 $sqlOp = $this->getSQLOperator($op);
3543 if (!is_array($value)) {
3544 $value = array($value);
3546 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3547 $entity_table = $this->_tagFilterTable
;
3548 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3549 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3550 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3551 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3555 * Generate membership organization clause.
3557 * @param mixed $value
3558 * @param string $op SQL Operator
3562 public function whereMembershipOrgClause($value, $op) {
3563 $sqlOp = $this->getSQLOperator($op);
3564 if (!is_array($value)) {
3565 $value = array($value);
3568 $tmp_membership_org_sql_list = implode(', ', $value);
3569 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3570 SELECT DISTINCT mem.contact_id
3571 FROM civicrm_membership mem
3572 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3573 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3574 WHERE mt.member_of_contact_id IN (" .
3575 $tmp_membership_org_sql_list . ")
3576 AND mt.is_active = '1'
3577 AND mem_status.is_current_member = '1'
3578 AND mem_status.is_active = '1' ) ";
3582 * Generate Membership Type SQL Clause.
3584 * @param mixed $value
3590 public function whereMembershipTypeClause($value, $op) {
3591 $sqlOp = $this->getSQLOperator($op);
3592 if (!is_array($value)) {
3593 $value = array($value);
3596 $tmp_membership_sql_list = implode(', ', $value);
3597 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3598 SELECT DISTINCT mem.contact_id
3599 FROM civicrm_membership mem
3600 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3601 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3602 WHERE mem.membership_type_id IN (" .
3603 $tmp_membership_sql_list . ")
3604 AND mt.is_active = '1'
3605 AND mem_status.is_current_member = '1'
3606 AND mem_status.is_active = '1' ) ";
3610 * Build acl clauses.
3612 * @param string $tableAlias
3614 public function buildACLClause($tableAlias = 'contact_a') {
3615 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3619 * Add custom data to the columns.
3621 * @param bool $addFields
3622 * @param array $permCustomGroupIds
3624 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3625 if (empty($this->_customGroupExtends
)) {
3628 if (!is_array($this->_customGroupExtends
)) {
3629 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3631 $customGroupWhere = '';
3632 if (!empty($permCustomGroupIds)) {
3633 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3637 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3638 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3639 FROM civicrm_custom_group cg
3640 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3641 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3643 cg.is_active = 1 AND
3644 cf.is_active = 1 AND
3645 cf.is_searchable = 1
3646 ORDER BY cg.weight, cf.weight";
3647 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3650 while ($customDAO->fetch()) {
3651 if ($customDAO->table_name
!= $curTable) {
3652 $curTable = $customDAO->table_name
;
3653 $curFields = $curFilters = array();
3656 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3657 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3658 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3659 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3661 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3662 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3663 $this->_columns
[$curTable][$colKey] = array();
3667 $fieldName = 'custom_' . $customDAO->cf_id
;
3670 // this makes aliasing work in favor
3671 $curFields[$fieldName] = array(
3672 'name' => $customDAO->column_name
,
3673 'title' => $customDAO->label
,
3674 'dataType' => $customDAO->data_type
,
3675 'htmlType' => $customDAO->html_type
,
3678 if ($this->_customGroupFilters
) {
3679 // this makes aliasing work in favor
3680 $curFilters[$fieldName] = array(
3681 'name' => $customDAO->column_name
,
3682 'title' => $customDAO->label
,
3683 'dataType' => $customDAO->data_type
,
3684 'htmlType' => $customDAO->html_type
,
3688 switch ($customDAO->data_type
) {
3691 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3692 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3693 // CRM-6946, show time part for datetime date fields
3694 if ($customDAO->time_format
) {
3695 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3700 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3701 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3702 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3706 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3707 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3711 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3712 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3713 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3717 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3718 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3722 case 'StateProvince':
3724 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3726 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3727 if ($options !== FALSE) {
3728 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3729 $curFilters[$fieldName]['options'] = $options;
3733 case 'ContactReference':
3734 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3735 $curFilters[$fieldName]['name'] = 'display_name';
3736 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3738 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3739 $curFields[$fieldName]['name'] = 'display_name';
3740 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3744 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3745 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3749 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3750 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3751 if ($options !== FALSE) {
3752 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3753 $curFilters[$fieldName]['options'] = $options;
3757 if (!array_key_exists('type', $curFields[$fieldName])) {
3758 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3762 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3764 if ($this->_customGroupFilters
) {
3765 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3767 if ($this->_customGroupGroupBy
) {
3768 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3774 * Build custom data from clause.
3776 * @param bool $joinsForFiltersOnly
3777 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3779 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3780 if (empty($this->_customGroupExtends
)) {
3783 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3784 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3785 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3786 $customTables = array();
3787 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3788 while ($customTablesDAO->fetch()) {
3789 $customTables[] = $customTablesDAO->table_name
;
3792 foreach ($this->_columns
as $table => $prop) {
3793 if (in_array($table, $customTables)) {
3794 $extendsTable = $mapper[$prop['extends']];
3795 // Check field is required for rendering the report.
3796 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3799 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3801 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3803 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3804 // handle for ContactReference
3805 if (array_key_exists('fields', $prop)) {
3806 foreach ($prop['fields'] as $fieldName => $field) {
3807 if (CRM_Utils_Array
::value('dataType', $field) ==
3810 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3812 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3821 * Check if the field is selected.
3823 * @param string $prop
3827 public function isFieldSelected($prop) {
3832 if (!empty($this->_params
['fields'])) {
3833 foreach (array_keys($prop['fields']) as $fieldAlias) {
3834 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3835 if ($customFieldId) {
3836 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3840 //might be survey response field.
3841 if (!empty($this->_params
['fields']['survey_response']) &&
3842 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3850 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3851 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3852 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3853 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3860 if (!empty($this->_params
['order_bys'])) {
3861 foreach (array_keys($prop['fields']) as $fieldAlias) {
3862 foreach ($this->_params
['order_bys'] as $orderBy) {
3863 if ($fieldAlias == $orderBy['column'] &&
3864 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3871 return $this->isFieldFiltered($prop);
3876 * Check if the field is used as a filter.
3878 * @param string $prop
3882 protected function isFieldFiltered($prop) {
3883 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3884 foreach ($prop['filters'] as $fieldAlias => $val) {
3893 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3894 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3895 ||
($attach != 'relative' &&
3896 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3902 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3903 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3914 * Check for empty order_by configurations and remove them.
3916 * Also set template to hide them.
3918 * @param array $formValues
3920 public function preProcessOrderBy(&$formValues) {
3921 // Object to show/hide form elements
3922 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3924 $_showHide->addShow('optionField_1');
3926 // Cycle through order_by options; skip any empty ones, and hide them as well
3929 if (!empty($formValues['order_bys'])) {
3930 foreach ($formValues['order_bys'] as $order_by) {
3931 if ($order_by['column'] && $order_by['column'] != '-') {
3932 $_showHide->addShow('optionField_' . $n);
3933 $orderBys[$n] = $order_by;
3938 for ($i = $n; $i <= 5; $i++
) {
3940 $_showHide->addHide('optionField_' . $i);
3944 // overwrite order_by options with modified values
3945 if (!empty($orderBys)) {
3946 $formValues['order_bys'] = $orderBys;
3949 $formValues['order_bys'] = array(1 => array('column' => '-'));
3952 // assign show/hide data to template
3953 $_showHide->addToTemplate();
3957 * Check if table name has columns in SELECT clause.
3959 * @param string $tableName
3960 * Name of table (index of $this->_columns array).
3964 public function isTableSelected($tableName) {
3965 return in_array($tableName, $this->selectedTables());
3969 * Check if table name has columns in WHERE or HAVING clause.
3971 * @param string $tableName
3972 * Name of table (index of $this->_columns array).
3976 public function isTableFiltered($tableName) {
3977 // Cause the array to be generated if not previously done.
3978 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3979 $this->selectedTables();
3981 return in_array($tableName, $this->filteredTables
);
3985 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3987 * If the array is unset it will be built.
3992 public function selectedTables() {
3993 if (!$this->_selectedTables
) {
3994 $orderByColumns = array();
3995 if (array_key_exists('order_bys', $this->_params
) &&
3996 is_array($this->_params
['order_bys'])
3998 foreach ($this->_params
['order_bys'] as $orderBy) {
3999 $orderByColumns[] = $orderBy['column'];
4003 foreach ($this->_columns
as $tableName => $table) {
4004 if (array_key_exists('fields', $table)) {
4005 foreach ($table['fields'] as $fieldName => $field) {
4006 if (!empty($field['required']) ||
4007 !empty($this->_params
['fields'][$fieldName])
4009 $this->_selectedTables
[] = $tableName;
4014 if (array_key_exists('order_bys', $table)) {
4015 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4016 if (in_array($orderByName, $orderByColumns)) {
4017 $this->_selectedTables
[] = $tableName;
4022 if (array_key_exists('filters', $table)) {
4023 foreach ($table['filters'] as $filterName => $filter) {
4024 if (!empty($this->_params
["{$filterName}_value"]) ||
4025 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4027 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4030 $this->_selectedTables
[] = $tableName;
4031 $this->filteredTables
[] = $tableName;
4038 return $this->_selectedTables
;
4042 * Add address fields.
4044 * @deprecated - use getAddressColumns which is a more accurate description
4045 * and also accepts an array of options rather than a long list
4047 * adding address fields to construct function in reports
4049 * @param bool $groupBy
4050 * Add GroupBy? Not appropriate for detail report.
4051 * @param bool $orderBy
4052 * Add GroupBy? Not appropriate for detail report.
4053 * @param bool $filters
4054 * @param array $defaults
4057 * address fields for construct clause
4059 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4060 $defaultAddressFields = array(
4061 'street_address' => ts('Street Address'),
4062 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4063 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4064 'street_number' => ts('Street Number'),
4065 'street_name' => ts('Street Name'),
4066 'street_unit' => ts('Street Unit'),
4067 'city' => ts('City'),
4068 'postal_code' => ts('Postal Code'),
4069 'postal_code_suffix' => ts('Postal Code Suffix'),
4070 'country_id' => ts('Country'),
4071 'state_province_id' => ts('State/Province'),
4072 'county_id' => ts('County'),
4074 $addressFields = array(
4075 'civicrm_address' => array(
4076 'dao' => 'CRM_Core_DAO_Address',
4078 'address_name' => array(
4079 'title' => ts('Address Name'),
4080 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4084 'grouping' => 'location-fields',
4087 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4088 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4089 'title' => $fieldLabel,
4090 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4094 $street_address_filters = $general_address_filters = array();
4096 // Address filter depends on whether street address parsing is enabled.
4098 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4101 if ($addressOptions['street_address_parsing']) {
4102 $street_address_filters = array(
4103 'street_number' => array(
4104 'title' => ts('Street Number'),
4105 'type' => CRM_Utils_Type
::T_INT
,
4106 'name' => 'street_number',
4108 'street_name' => array(
4109 'title' => ts('Street Name'),
4110 'name' => 'street_name',
4111 'type' => CRM_Utils_Type
::T_STRING
,
4116 $street_address_filters = array(
4117 'street_address' => array(
4118 'title' => ts('Street Address'),
4119 'type' => CRM_Utils_Type
::T_STRING
,
4120 'name' => 'street_address',
4124 $general_address_filters = array(
4125 'postal_code' => array(
4126 'title' => ts('Postal Code'),
4127 'type' => CRM_Utils_Type
::T_STRING
,
4128 'name' => 'postal_code',
4131 'title' => ts('City'),
4132 'type' => CRM_Utils_Type
::T_STRING
,
4135 'country_id' => array(
4136 'name' => 'country_id',
4137 'title' => ts('Country'),
4138 'type' => CRM_Utils_Type
::T_INT
,
4139 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4140 'options' => CRM_Core_PseudoConstant
::country(),
4142 'state_province_id' => array(
4143 'name' => 'state_province_id',
4144 'title' => ts('State/Province'),
4145 'type' => CRM_Utils_Type
::T_INT
,
4146 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4147 'options' => array(),
4149 'county_id' => array(
4150 'name' => 'county_id',
4151 'title' => ts('County'),
4152 'type' => CRM_Utils_Type
::T_INT
,
4153 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4154 'options' => array(),
4158 $addressFields['civicrm_address']['filters'] = array_merge(
4159 $street_address_filters,
4160 $general_address_filters);
4163 $addressFields['civicrm_address']['order_bys'] = array(
4164 'street_name' => array('title' => ts('Street Name')),
4165 'street_number' => array('title' => ts('Odd / Even Street Number')),
4166 'street_address' => NULL,
4168 'postal_code' => NULL,
4173 $addressFields['civicrm_address']['group_bys'] = array(
4174 'street_address' => NULL,
4176 'postal_code' => NULL,
4177 'state_province_id' => array(
4178 'title' => ts('State/Province'),
4180 'country_id' => array(
4181 'title' => ts('Country'),
4183 'county_id' => array(
4184 'title' => ts('County'),
4188 return $addressFields;
4192 * Do AlterDisplay processing on Address Fields.
4195 * @param array $rows
4196 * @param int $rowNum
4197 * @param string $baseUrl
4198 * @param string $linkText
4202 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4203 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4204 $entryFound = FALSE;
4206 if (array_key_exists('civicrm_address_country_id', $row)) {
4207 if ($value = $row['civicrm_address_country_id']) {
4208 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4210 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4211 "reset=1&force=1&{$criteriaQueryParams}&" .
4212 "country_id_op=in&country_id_value={$value}",
4213 $this->_absoluteUrl
, $this->_id
4215 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4216 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4217 array(1 => $linkText)
4224 if (array_key_exists('civicrm_address_county_id', $row)) {
4225 if ($value = $row['civicrm_address_county_id']) {
4226 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4228 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4229 "reset=1&force=1&{$criteriaQueryParams}&" .
4230 "county_id_op=in&county_id_value={$value}",
4231 $this->_absoluteUrl
, $this->_id
4233 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4234 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4235 array(1 => $linkText)
4241 // handle state province
4242 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4243 if ($value = $row['civicrm_address_state_province_id']) {
4244 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4246 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4247 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4248 $this->_absoluteUrl
, $this->_id
4250 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4251 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4252 array(1 => $linkText)
4263 * Do AlterDisplay processing on Address Fields.
4266 * @param array $rows
4267 * @param int $rowNum
4268 * @param string $baseUrl
4269 * @param string $linkText
4273 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4274 $entryFound = FALSE;
4275 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4276 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4277 $addLinks = array('gender_id' => 'Gender');
4278 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4279 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4280 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4281 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4282 $rowLabels = array();
4283 foreach ($rowValues as $rowValue) {
4285 $rowLabels[] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4288 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4289 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4290 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4296 $yesNoFields = array(
4297 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4299 foreach ($yesNoFields as $fieldName) {
4300 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4301 // Since these are essentially 'negative fields' it feels like it
4302 // makes sense to only highlight the exceptions hence no 'No'.
4303 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4311 * Adjusts dates passed in to YEAR() for fiscal year.
4313 * @param string $fieldName
4317 public function fiscalYearOffset($fieldName) {
4318 $config = CRM_Core_Config
::singleton();
4319 $fy = $config->fiscalYearStart
;
4320 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4321 ($fy['d'] == 1 && $fy['M'] == 1)
4323 return "YEAR( $fieldName )";
4325 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4326 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4330 * Add Address into From Table if required.
4332 public function addAddressFromClause() {
4333 // include address field if address column is to be included
4334 if ((isset($this->_addressField
) &&
4335 $this->_addressField
4337 $this->isTableSelected('civicrm_address')
4340 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4341 ON ({$this->_aliases['civicrm_contact']}.id =
4342 {$this->_aliases['civicrm_address']}.contact_id) AND
4343 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4348 * Add Phone into From Table if required.
4350 public function addPhoneFromClause() {
4351 // include address field if address column is to be included
4352 if ($this->isTableSelected('civicrm_phone')
4355 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4356 ON ({$this->_aliases['civicrm_contact']}.id =
4357 {$this->_aliases['civicrm_phone']}.contact_id) AND
4358 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4363 * Get phone columns to add to array.
4365 * @param array $options
4366 * - prefix Prefix to add to table (in case of more than one instance of the table)
4367 * - prefix_label Label to give columns from this phone table instance
4370 * phone columns definition
4372 public function getPhoneColumns($options = array()) {
4373 $defaultOptions = array(
4375 'prefix_label' => '',
4378 $options = array_merge($defaultOptions, $options);
4381 $options['prefix'] . 'civicrm_phone' => array(
4382 'dao' => 'CRM_Core_DAO_Phone',
4384 $options['prefix'] . 'phone' => array(
4385 'title' => ts($options['prefix_label'] . 'Phone'),
4395 * Get address columns to add to array.
4397 * @param array $options
4398 * - prefix Prefix to add to table (in case of more than one instance of the table)
4399 * - prefix_label Label to give columns from this address table instance
4402 * address columns definition
4404 public function getAddressColumns($options = array()) {
4407 'prefix_label' => '',
4411 'defaults' => array(),
4413 return $this->addAddressFields(
4414 $options['group_by'],
4415 $options['order_by'],
4416 $options['filters'],
4417 $options['defaults']
4422 * Get a standard set of contact fields.
4426 public function getBasicContactFields() {
4428 'sort_name' => array(
4429 'title' => ts('Contact Name'),
4434 'no_display' => TRUE,
4437 'prefix_id' => array(
4438 'title' => ts('Contact Prefix'),
4440 'first_name' => array(
4441 'title' => ts('First Name'),
4443 'nick_name' => array(
4444 'title' => ts('Nick Name'),
4446 'middle_name' => array(
4447 'title' => ts('Middle Name'),
4449 'last_name' => array(
4450 'title' => ts('Last Name'),
4452 'suffix_id' => array(
4453 'title' => ts('Contact Suffix'),
4455 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4456 'email_greeting_display' => array('title' => ts('Email Greeting')),
4457 'addressee_display' => array('title' => ts('Addressee')),
4458 'contact_type' => array(
4459 'title' => ts('Contact Type'),
4461 'contact_sub_type' => array(
4462 'title' => ts('Contact Subtype'),
4464 'gender_id' => array(
4465 'title' => ts('Gender'),
4467 'birth_date' => array(
4468 'title' => ts('Birth Date'),
4471 'title' => ts('Age'),
4472 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4474 'job_title' => array(
4475 'title' => ts('Contact Job title'),
4477 'organization_name' => array(
4478 'title' => ts('Organization Name'),
4480 'external_identifier' => array(
4481 'title' => ts('Contact identifier from external system'),
4483 'do_not_email' => array(),
4484 'do_not_phone' => array(),
4485 'do_not_mail' => array(),
4486 'do_not_sms' => array(),
4487 'is_opt_out' => array(),
4488 'is_deceased' => array(),
4489 'preferred_language' => array(),
4494 * Get a standard set of contact filters.
4498 public function getBasicContactFilters() {
4500 'sort_name' => array(
4501 'title' => ts('Contact Name'),
4504 'title' => ts('Contact Source'),
4505 'type' => CRM_Utils_Type
::T_STRING
,
4508 'title' => ts('Contact ID'),
4509 'no_display' => TRUE,
4511 'gender_id' => array(
4512 'title' => ts('Gender'),
4513 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4514 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4516 'birth_date' => array(
4517 'title' => ts('Birth Date'),
4518 'operatorType' => CRM_Report_Form
::OP_DATE
,
4520 'contact_type' => array(
4521 'title' => ts('Contact Type'),
4523 'contact_sub_type' => array(
4524 'title' => ts('Contact Subtype'),
4526 'modified_date' => array(
4527 'title' => ts('Contact Modified'),
4528 'operatorType' => CRM_Report_Form
::OP_DATE
,
4529 'type' => CRM_Utils_Type
::T_DATE
,
4531 'is_deceased' => array(
4532 'title' => ts('Deceased'),
4533 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4536 'do_not_email' => array(
4537 'title' => ts('Do not email'),
4538 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4540 'do_not_phone' => array(
4541 'title' => ts('Do not phone'),
4542 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4544 'do_not_mail' => array(
4545 'title' => ts('Do not mail'),
4546 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4548 'do_not_sms' => array(
4549 'title' => ts('Do not SMS'),
4550 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4552 'is_opt_out' => array(
4553 'title' => ts('Do not bulk email'),
4554 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4556 'preferred_language' => array(
4557 'title' => ts('Preferred Language'),
4563 * Add contact to group.
4565 * @param int $groupID
4567 public function add2group($groupID) {
4568 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4569 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4570 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4571 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4572 $sql = str_replace('WITH ROLLUP', '', $sql);
4573 $dao = CRM_Core_DAO
::executeQuery($sql);
4575 $contact_ids = array();
4576 // Add resulting contacts to group
4577 while ($dao->fetch()) {
4578 if ($dao->addtogroup_contact_id
) {
4579 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4583 if (!empty($contact_ids)) {
4584 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4585 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4588 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4594 * Show charts on print screen.
4596 public static function uploadChartImage() {
4597 // upload strictly for '.png' images
4598 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4599 if (preg_match('/\.png$/', $name)) {
4601 // Get the RAW .png from the input.
4602 $httpRawPostData = file_get_contents("php://input");
4604 // prepare the directory
4605 $config = CRM_Core_Config
::singleton();
4607 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4609 if (!file_exists($defaultPath)) {
4610 mkdir($defaultPath, 0777, TRUE);
4613 // full path to the saved image including filename
4614 $destination = $defaultPath . $name;
4617 $jfh = fopen($destination, 'w') or die("can't open file");
4618 fwrite($jfh, $httpRawPostData);
4620 CRM_Utils_System
::civiExit();
4625 * Apply common settings to entityRef fields.
4627 * @param array $field
4628 * @param string $table
4630 private function setEntityRefDefaults(&$field, $table) {
4631 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4632 $field['attributes'] +
= array(
4633 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4635 'placeholder' => ts('- select -'),
4640 * Add link fields to the row.
4642 * Function adds the _link & _hover fields to the row.
4645 * @param string $baseUrl
4646 * @param string $linkText
4647 * @param string $value
4648 * @param string $fieldName
4649 * @param string $tablePrefix
4650 * @param string $fieldLabel
4654 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4655 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4656 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4657 "reset=1&force=1&{$criteriaQueryParams}&" .
4658 $fieldName . "_op=in&{$fieldName}_value={$value}",
4659 $this->_absoluteUrl
, $this->_id
4661 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4662 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4663 array(1 => $linkText, 2 => $fieldLabel)
4668 * Generate temporary table to hold all contributions with permissioned FTs.
4670 * @param object $query
4671 * @param string $alias
4672 * @param bool $return
4676 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4677 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4680 $financialTypes = NULL;
4681 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4682 if (empty($financialTypes)) {
4684 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4687 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4689 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4691 $query->_aliases
['civicrm_line_item'] = $alias;
4694 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4696 if (empty($query->_where
)) {
4697 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4699 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4700 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp {$this->_databaseAttributes} AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4701 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4702 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4703 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4704 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4706 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4707 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4708 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4709 CRM_Core_DAO
::executeQuery($sql);
4711 $query->_aliases
['civicrm_line_item'] = $temp;
4713 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4717 $query->_from
.= $from;
4721 * Get label for show results buttons.
4725 public function getResultsLabel() {
4726 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4727 return $showResultsLabel;
4731 * Determine the output mode from the url or input.
4734 * - pdf : Render as pdf
4735 * - csv : Render as csv
4736 * - print : Render in print format
4737 * - save : save the report and display the new report
4738 * - copy : save the report as a new instance and display that.
4739 * - group : go to the add to group screen.
4741 * Potentially chart variations could also be included but the complexity
4742 * is that we might print a bar chart as a pdf.
4744 protected function setOutputMode() {
4745 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4748 CRM_Core_DAO
::$_nullObject,
4750 CRM_Utils_Array
::value('task', $this->_params
)
4752 // if contacts are added to group
4753 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4754 $this->_outputMode
= 'group';
4756 if (isset($this->_params
['task'])) {
4757 unset($this->_params
['task']);
4762 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4765 * @param $columnName
4767 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4768 // add new column with date value for the datetime field
4769 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4770 CRM_Core_DAO
::executeQuery($tempQuery);
4771 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4772 CRM_Core_DAO
::executeQuery($updateQuery);
4773 $this->_selectClauses
[] = "{$columnName}_date";
4774 $this->_select
.= ", {$columnName}_date";
4775 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4776 unset($this->_sections
["{$columnName}"]);
4777 $this->assign('sections', $this->_sections
);
4781 * Get an array of the columns that have been selected for display.
4785 public function getSelectColumns() {
4786 $selectColumns = array();
4787 foreach ($this->_columns
as $tableName => $table) {
4788 if (array_key_exists('fields', $table)) {
4789 foreach ($table['fields'] as $fieldName => $field) {
4790 if (!empty($field['required']) ||
4791 !empty($this->_params
['fields'][$fieldName])
4794 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4799 return $selectColumns;
4803 * Add location tables to the query if they are used for filtering.
4805 * This is for when we are running the query separately for filtering and retrieving display fields.
4807 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4808 if ($this->isTableFiltered('civicrm_email')) {
4810 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4811 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4812 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4814 if ($this->isTableFiltered('civicrm_phone')) {
4816 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4817 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4818 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4820 if ($this->isTableFiltered('civicrm_address')) {
4822 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4823 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4824 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4829 * Set the base table for the FROM clause.
4831 * Sets up the from clause, allowing for the possibility it might be a
4832 * temp table pre-filtered by groups if a group filter is in use.
4834 * @param string $baseTable
4835 * @param string $field
4836 * @param null $tableAlias
4838 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4840 $tableAlias = $this->_aliases
[$baseTable];
4842 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4843 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4844 $this->_from
.= " {$this->_aclFrom} ";
4848 * Join the temp table contacting contacts who are members of the filtered groups.
4850 * If we are using an IN filter we use an inner join, otherwise a left join.
4852 * @param string $baseTable
4853 * @param string $field
4854 * @param string $tableAlias
4856 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4857 if ($this->groupTempTable
) {
4858 if ($this->_params
['gid_op'] == 'in') {
4859 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4860 ON group_temp_table.id = $tableAlias.{$field} ";
4864 LEFT JOIN $this->groupTempTable group_temp_table
4865 ON $tableAlias.{$field} = group_temp_table.id ";