3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 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() {
528 = CRM_Utils_Request
::retrieve(
531 CRM_Core_DAO
::$_nullObject
534 $this->_dashBoardRowCount
535 = CRM_Utils_Request
::retrieve(
538 CRM_Core_DAO
::$_nullObject
541 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
543 $this->assign('section', $this->_section
);
544 CRM_Core_Region
::instance('page-header')->add(array(
545 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
547 if (!$this->noController
) {
548 $this->setID($this->get('instanceId'));
551 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
553 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
557 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
558 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
559 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
563 $this->assign('instanceId', $this->_id
);
564 $params = array('id' => $this->_id
);
565 $this->_instanceValues
= array();
566 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
568 $this->_instanceValues
570 if (empty($this->_instanceValues
)) {
571 CRM_Core_Error
::fatal("Report could not be loaded.");
573 $this->_title
= $this->_instanceValues
['title'];
574 if (!empty($this->_instanceValues
['permission']) &&
575 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
576 CRM_Core_Permission
::check('administer Reports')
579 CRM_Utils_System
::permissionDenied();
580 CRM_Utils_System
::civiExit();
583 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
585 $this->_formValues
= unserialize($formValues);
588 $this->_formValues
= NULL;
591 $this->setOutputMode();
593 if ($this->_outputMode
== 'copy') {
594 $this->_createNew
= TRUE;
595 $this->_params
= $this->_formValues
;
596 $this->_params
['view_mode'] = 'criteria';
597 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
598 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
599 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
601 // Do not pass go. Do not collect another chance to re-run the same query.
602 CRM_Report_Form_Instance
::postProcess($this);
605 // lets always do a force if reset is found in the url.
606 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
607 // in the comment line above these 2.
608 if (!empty($_REQUEST['reset'])
609 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
614 $this->assign('mode', 'instance');
616 elseif (!$this->noController
) {
617 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
618 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
619 if (($instanceCount > 0) && $optionValueID) {
620 $this->assign('instanceUrl',
621 CRM_Utils_System
::url('civicrm/report/list',
622 "reset=1&ovid=$optionValueID"
626 if ($optionValueID) {
627 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
631 $this->assign('mode', 'template');
634 // lets display the Report Settings section
635 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
637 // Do not display Report Settings section if administer Reports permission is absent OR
638 // if report instance is reserved and administer reserved reports absent
639 if (!CRM_Core_Permission
::check('administer Reports') ||
640 ($this->_instanceValues
['is_reserved'] &&
641 !CRM_Core_Permission
::check('administer reserved reports'))
643 $this->_instanceForm
= FALSE;
646 $this->assign('criteriaForm', FALSE);
647 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
648 if (CRM_Core_Permission
::check('administer Reports') ||
649 CRM_Core_Permission
::check('access Report Criteria')
651 if (!$this->_instanceValues
['is_reserved'] ||
652 CRM_Core_Permission
::check('administer reserved reports')
654 $this->assign('criteriaForm', TRUE);
655 $this->_criteriaForm
= TRUE;
659 // Special permissions check for private instance if it's not the current contact instance
661 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
662 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
663 if (!CRM_Core_Permission
::check('access all private reports')) {
664 $this->_instanceForm
= FALSE;
665 $this->assign('criteriaForm', FALSE);
669 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
670 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
671 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
672 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
678 public function addBreadCrumb() {
682 'title' => ts('Report Templates'),
683 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
687 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
691 * Pre process function.
693 * Called prior to build form.
695 public function preProcess() {
696 $this->preProcessCommon();
699 $this->addBreadCrumb();
702 foreach ($this->_columns
as $tableName => $table) {
704 if (!isset($table['alias'])) {
705 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
709 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
712 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
714 $daoOrBaoName = NULL;
715 // higher preference to bao object
716 if (array_key_exists('bao', $table)) {
717 $daoOrBaoName = $table['bao'];
718 $expFields = $daoOrBaoName::exportableFields();
720 elseif (array_key_exists('dao', $table)) {
721 $daoOrBaoName = $table['dao'];
722 $expFields = $daoOrBaoName::export();
725 $expFields = array();
728 $doNotCopy = array('required');
730 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
731 foreach ($fieldGroups as $fieldGrp) {
732 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
733 foreach ($table[$fieldGrp] as $fieldName => $field) {
734 // $name is the field name used to reference the BAO/DAO export fields array
735 $name = isset($field['name']) ?
$field['name'] : $fieldName;
737 // Sometimes the field name key in the BAO/DAO export fields array is
738 // different from the actual database field name.
739 // Unset $field['name'] so that actual database field name can be obtained
740 // from the BAO/DAO export fields array.
741 unset($field['name']);
743 if (array_key_exists($name, $expFields)) {
744 foreach ($doNotCopy as $dnc) {
745 // unset the values we don't want to be copied.
746 unset($expFields[$name][$dnc]);
749 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
752 foreach ($expFields[$name] as $property => $val) {
753 if (!array_key_exists($property, $field)) {
754 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
761 if (!empty($field['no_repeat'])) {
762 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
764 if (!empty($field['no_display'])) {
765 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
768 // set alias = table-name, unless already set
769 $alias = isset($field['alias']) ?
$field['alias'] : (
770 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
772 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
774 // set name = fieldName, unless already set
775 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
776 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
779 // set dbAlias = alias.name, unless already set
780 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
781 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
783 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
786 // a few auto fills for filters
787 if ($fieldGrp == 'filters') {
788 // fill operator types
789 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
790 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
791 case CRM_Utils_Type
::T_MONEY
:
792 case CRM_Utils_Type
::T_FLOAT
:
793 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
796 case CRM_Utils_Type
::T_INT
:
797 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
800 case CRM_Utils_Type
::T_DATE
:
801 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
804 case CRM_Utils_Type
::T_BOOLEAN
:
805 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
806 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
807 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
818 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
820 // with multiple options operator-type is generally multi-select
821 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
822 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
824 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
835 // copy filters to a separate handy variable
836 if (array_key_exists('filters', $table)) {
837 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
840 if (array_key_exists('group_bys', $table)) {
841 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
844 if (array_key_exists('fields', $table)) {
845 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
850 $this->setDefaultValues(FALSE);
853 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
854 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
855 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
856 CRM_Report_Utils_Get
::processChart($this->_defaults
);
859 $this->_formValues
= $this->_defaults
;
860 $this->postProcess();
865 * Set default values.
867 * @param bool $freeze
871 public function setDefaultValues($freeze = TRUE) {
872 $freezeGroup = array();
874 // FIXME: generalizing form field naming conventions would reduce
875 // Lots of lines below.
876 foreach ($this->_columns
as $tableName => $table) {
877 if (array_key_exists('fields', $table)) {
878 foreach ($table['fields'] as $fieldName => $field) {
879 if (empty($field['no_display'])) {
880 if (isset($field['required'])) {
882 $this->_defaults
['fields'][$fieldName] = 1;
885 // find element object, so that we could use quickform's freeze method
886 // for required elements
887 $obj = $this->getElementFromGroup("fields", $fieldName);
889 $freezeGroup[] = $obj;
893 elseif (isset($field['default'])) {
894 $this->_defaults
['fields'][$fieldName] = $field['default'];
900 if (array_key_exists('group_bys', $table)) {
901 foreach ($table['group_bys'] as $fieldName => $field) {
902 if (isset($field['default'])) {
903 if (!empty($field['frequency'])) {
904 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
906 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
910 if (array_key_exists('filters', $table)) {
911 foreach ($table['filters'] as $fieldName => $field) {
912 if (isset($field['default'])) {
913 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
915 if (is_array($field['default'])) {
916 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
917 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
918 $this->_defaults
["{$fieldName}_relative"] = 0;
921 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
925 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
926 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
927 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
929 $this->_defaults
["{$fieldName}_value"] = $field['default'];
932 //assign default value as "in" for multiselect
933 //operator, To freeze the select element
934 if (CRM_Utils_Array
::value('operatorType', $field) ==
935 CRM_Report_Form
::OP_MULTISELECT
937 $this->_defaults
["{$fieldName}_op"] = 'in';
939 if (CRM_Utils_Array
::value('operatorType', $field) ==
940 CRM_Report_Form
::OP_ENTITYREF
942 $this->_defaults
["{$fieldName}_op"] = 'in';
944 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
945 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
947 $this->_defaults
["{$fieldName}_op"] = 'mhas';
949 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
950 $this->_defaults
["{$fieldName}_op"] = $op;
956 empty($this->_formValues
['order_bys']) &&
957 (array_key_exists('order_bys', $table) &&
958 is_array($table['order_bys']))
960 if (!array_key_exists('order_bys', $this->_defaults
)) {
961 $this->_defaults
['order_bys'] = array();
963 foreach ($table['order_bys'] as $fieldName => $field) {
964 if (!empty($field['default']) ||
!empty($field['default_order']) ||
965 CRM_Utils_Array
::value('default_is_section', $field) ||
966 !empty($field['default_weight'])
969 'column' => $fieldName,
970 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
971 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
974 if (!empty($field['default_weight'])) {
975 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
978 array_unshift($this->_defaults
['order_bys'], $order_by);
984 foreach ($this->_options
as $fieldName => $field) {
985 if (isset($field['default'])) {
986 $this->_defaults
['options'][$fieldName] = $field['default'];
991 if (!empty($this->_submitValues
)) {
992 $this->preProcessOrderBy($this->_submitValues
);
995 $this->preProcessOrderBy($this->_defaults
);
998 // lets finish freezing task here itself
999 if (!empty($freezeGroup)) {
1000 foreach ($freezeGroup as $elem) {
1005 if ($this->_formValues
) {
1006 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
1009 if ($this->_instanceValues
) {
1010 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1013 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1015 return $this->_defaults
;
1019 * Get element from group.
1021 * @param string $group
1022 * @param string $grpFieldName
1026 public function getElementFromGroup($group, $grpFieldName) {
1027 $eleObj = $this->getElement($group);
1028 foreach ($eleObj->_elements
as $index => $obj) {
1029 if ($grpFieldName == $obj->_attributes
['name']) {
1037 * Setter for $_params.
1039 * @param array $params
1041 public function setParams($params) {
1042 $this->_params
= $params;
1048 * @param int $instanceID
1050 public function setID($instanceID) {
1051 $this->_id
= $instanceID;
1055 * Setter for $_force.
1057 * @param bool $isForce
1059 public function setForce($isForce) {
1060 $this->_force
= $isForce;
1064 * Setter for $_limitValue.
1066 * @param int $_limitValue
1068 public function setLimitValue($_limitValue) {
1069 $this->_limitValue
= $_limitValue;
1073 * Setter for $_offsetValue.
1075 * @param int $_offsetValue
1077 public function setOffsetValue($_offsetValue) {
1078 $this->_offsetValue
= $_offsetValue;
1082 * Setter for $addPaging.
1084 * @param bool $value
1086 public function setAddPaging($value) {
1087 $this->addPaging
= $value;
1091 * Getter for $_defaultValues.
1095 public function getDefaultValues() {
1096 return $this->_defaults
;
1100 * Add columns to report.
1102 public function addColumns() {
1105 foreach ($this->_columns
as $tableName => $table) {
1106 if (array_key_exists('fields', $table)) {
1107 foreach ($table['fields'] as $fieldName => $field) {
1109 if (empty($field['no_display'])) {
1110 foreach (array('table', 'field') as $var) {
1111 if (!empty($
{$var}['grouping'])) {
1112 if (!is_array($
{$var}['grouping'])) {
1113 $tableName = $
{$var}['grouping'];
1116 $tableName = array_keys($
{$var}['grouping']);
1117 $tableName = $tableName[0];
1118 $groupTitle = array_values($
{$var}['grouping']);
1119 $groupTitle = $groupTitle[0];
1124 if (!$groupTitle && isset($table['group_title'])) {
1125 $groupTitle = $table['group_title'];
1126 // Having a group_title is secret code for being a custom group
1127 // which cryptically translates to needing an accordion.
1128 // here we make that explicit.
1129 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1132 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1133 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1134 $colGroups[$tableName]['group_title'] = $groupTitle;
1136 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1142 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1143 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1145 if (!empty($colGroups)) {
1146 $this->tabs
['FieldSelection'] = array(
1147 'title' => ts('Columns'),
1148 'tpl' => 'FieldSelection',
1149 'div_label' => 'col-groups',
1152 // Note this assignment is only really required in buildForm. It is being 'over-called'
1153 // to reduce risk of being missed due to overridden functions.
1154 $this->assign('tabs', $this->tabs
);
1157 $this->assign('colGroups', $colGroups);
1161 * Add filters to report.
1163 public function addFilters() {
1164 $filters = $filterGroups = array();
1167 foreach ($this->_filters
as $table => $attributes) {
1168 if (isset($this->_columns
[$table]['group_title'])) {
1169 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1170 // which magically means to 'display in an accordian'
1171 // here we make this explicit.
1172 $filterGroups[$table] = array(
1173 'group_title' => $this->_columns
[$table]['group_title'],
1174 'use_accordian_for_field_selection' => TRUE,
1178 foreach ($attributes as $fieldName => $field) {
1179 // get ready with option value pair
1180 // @ 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
1182 $operations = $this->getOperationPair(
1183 CRM_Utils_Array
::value('operatorType', $field),
1186 $filters[$table][$fieldName] = $field;
1188 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1189 case CRM_Report_Form
::OP_MONTH
:
1190 if (!array_key_exists('options', $field) ||
1191 !is_array($field['options']) ||
empty($field['options'])
1193 // If there's no option list for this filter, define one.
1194 $field['options'] = array(
1196 2 => ts('February'),
1203 9 => ts('September'),
1204 10 => ts('October'),
1205 11 => ts('November'),
1206 12 => ts('December'),
1208 // Add this option list to this column _columns. This is
1209 // required so that filter statistics show properly.
1210 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1212 case CRM_Report_Form
::OP_MULTISELECT
:
1213 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1214 // assume a multi-select field
1215 if (!empty($field['options']) ||
1216 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1218 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1219 if (count($operations) <= 1) {
1222 if ($fieldName == 'state_province_id' ||
1223 $fieldName == 'county_id'
1225 $this->addChainSelect($fieldName . '_value', array(
1232 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1233 'style' => 'min-width:250px',
1234 'class' => 'crm-select2 huge',
1236 'placeholder' => ts('- select -'),
1242 case CRM_Report_Form
::OP_SELECT
:
1243 // assume a select field
1244 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1245 if (!empty($field['options'])) {
1246 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1250 case CRM_Report_Form
::OP_ENTITYREF
:
1251 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1252 $this->setEntityRefDefaults($field, $table);
1253 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1256 case CRM_Report_Form
::OP_DATE
:
1257 // build datetime fields
1258 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1262 case CRM_Report_Form
::OP_DATETIME
:
1263 // build datetime fields
1264 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1268 case CRM_Report_Form
::OP_INT
:
1269 case CRM_Report_Form
::OP_FLOAT
:
1270 // and a min value input box
1271 $this->add('text', "{$fieldName}_min", ts('Min'));
1272 // and a max value input box
1273 $this->add('text', "{$fieldName}_max", ts('Max'));
1275 // default type is string
1276 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1277 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1279 // we need text box for value input
1280 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1285 if (!empty($filters)) {
1286 $this->tabs
['Filters'] = array(
1287 'title' => ts('Filters'),
1289 'div_label' => 'set-filters',
1292 $this->assign('filters', $filters);
1293 $this->assign('filterGroups', $filterGroups);
1297 * Function to assign the tabs to the template in the correct order.
1299 * We want the tabs to wind up in this order (if not overridden).
1307 protected function assignTabs() {
1315 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1316 $order = array_merge($order, $this->tabs
);
1317 $this->assign('tabs', $order);
1321 * The intent is to add a tab for developers to view the sql.
1323 * Currently using dpm.
1325 * @param string $sql
1327 protected function addToDeveloperTab($sql) {
1328 if (!CRM_Core_Permission
::check('view report sql')) {
1331 $this->tabs
['Developer'] = array(
1332 'title' => ts('Developer'),
1333 'tpl' => 'Developer',
1334 'div_label' => 'set-developer',
1337 $this->assignTabs();
1338 $this->sqlArray
[] = $sql;
1339 foreach ($this->sqlArray
as $sql) {
1340 foreach (array('LEFT JOIN') as $term) {
1341 $sql = str_replace($term, '<br>  ' . $term, $sql);
1343 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1344 $sql = str_replace($term, '<br><br>' . $term, $sql);
1346 $this->sqlFormattedArray
[] = $sql;
1347 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1352 * Add options defined in $this->_options to the report.
1354 public function addOptions() {
1355 if (!empty($this->_options
)) {
1356 // FIXME: For now lets build all elements as checkboxes.
1357 // Once we clear with the format we can build elements based on type
1359 foreach ($this->_options
as $fieldName => $field) {
1362 if ($field['type'] == 'select') {
1363 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1365 elseif ($field['type'] == 'checkbox') {
1366 $options[$field['title']] = $fieldName;
1367 $this->addCheckBox($fieldName, NULL,
1369 NULL, NULL, NULL, $this->_fourColumnAttribute
1374 if (!empty($this->_options
) &&
1376 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1378 $this->tabs
['ReportOptions'] = array(
1379 'title' => ts('Display Options'),
1380 'tpl' => 'ReportOptions',
1381 'div_label' => 'other-options',
1384 $this->assign('otherOptions', $this->_options
);
1388 * Add chart options to the report.
1390 public function addChartOptions() {
1391 if (!empty($this->_charts
)) {
1392 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1393 $this->assign('charts', $this->_charts
);
1394 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1399 * Add group by options to the report.
1401 public function addGroupBys() {
1402 $options = $freqElements = array();
1404 foreach ($this->_columns
as $tableName => $table) {
1405 if (array_key_exists('group_bys', $table)) {
1406 foreach ($table['group_bys'] as $fieldName => $field) {
1407 if (!empty($field)) {
1408 $options[$field['title']] = $fieldName;
1409 if (!empty($field['frequency'])) {
1410 $freqElements[$field['title']] = $fieldName;
1416 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1417 NULL, NULL, NULL, $this->_fourColumnAttribute
1419 $this->assign('groupByElements', $options);
1420 if (!empty($options)) {
1421 $this->tabs
['GroupBy'] = array(
1422 'title' => ts('Grouping'),
1424 'div_label' => 'group-by-elements',
1428 foreach ($freqElements as $name) {
1429 $this->addElement('select', "group_bys_freq[$name]",
1430 ts('Frequency'), $this->_groupByDateFreq
1436 * Add data for order by tab.
1438 public function addOrderBys() {
1440 foreach ($this->_columns
as $tableName => $table) {
1442 // Report developer may define any column to order by; include these as order-by options.
1443 if (array_key_exists('order_bys', $table)) {
1444 foreach ($table['order_bys'] as $fieldName => $field) {
1445 if (!empty($field)) {
1446 $options[$fieldName] = $field['title'];
1451 // Add searchable custom fields as order-by options, if so requested
1452 // (These are already indexed, so allowing to order on them is cheap.)
1454 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1455 array_key_exists('extends', $table) && !empty($table['extends'])
1457 foreach ($table['fields'] as $fieldName => $field) {
1458 if (empty($field['no_display'])) {
1459 $options[$fieldName] = $field['title'];
1467 $this->assign('orderByOptions', $options);
1468 if (!empty($options)) {
1469 $this->tabs
['OrderBy'] = array(
1470 'title' => ts('Sorting'),
1472 'div_label' => 'order-by-elements',
1476 if (!empty($options)) {
1478 '-' => ' - none - ',
1480 for ($i = 1; $i <= 5; $i++
) {
1481 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1482 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1483 'ASC' => ts('Ascending'),
1484 'DESC' => ts('Descending'),
1486 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1487 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1493 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1495 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1496 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1499 public function buildInstanceAndButtons() {
1500 CRM_Report_Form_Instance
::buildForm($this);
1501 $this->_actionButtonName
= $this->getButtonName('submit');
1502 $this->addTaskMenu($this->getActions($this->_id
));
1504 $this->assign('instanceForm', $this->_instanceForm
);
1506 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1507 $permission = CRM_Core_Permission
::getPermission();
1508 if ($permission == CRM_Core_Permission
::EDIT
&&
1509 $this->_add2groupSupported
1511 $this->addElement('select', 'groups', ts('Group'),
1512 array('' => ts('Add Contacts to Group')) +
1513 CRM_Core_PseudoConstant
::nestedGroup(),
1514 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1516 $this->assign('group', TRUE);
1519 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1521 $this->addChartOptions();
1522 $showResultsLabel = $this->getResultsLabel();
1523 $this->addButtons(array(
1526 'name' => $showResultsLabel,
1527 'isDefault' => TRUE,
1534 * Has this form been submitted already?
1538 public function resultsDisplayed() {
1539 $buttonName = $this->controller
->getButtonName();
1540 return ($buttonName ||
$this->_outputMode
);
1544 * Get the actions for this report instance.
1546 * @param int $instanceId
1550 protected function getActions($instanceId) {
1551 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1552 if (empty($instanceId)) {
1553 $actions['report_instance.save'] = array(
1554 'title' => ts('Create Report'),
1556 'is_confirm' => TRUE,
1557 'confirm_title' => ts('Create Report'),
1558 'confirm_refresh_fields' => json_encode(array(
1559 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1560 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1566 if (!$this->_csvSupported
) {
1567 unset($actions['report_instance.csv']);
1574 * Main build form function.
1576 public function buildQuickForm() {
1577 $this->addColumns();
1579 $this->addFilters();
1581 $this->addOptions();
1583 $this->addGroupBys();
1585 $this->addOrderBys();
1587 $this->buildInstanceAndButtons();
1589 // Add form rule for report.
1590 if (is_callable(array(
1594 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1596 $this->assignTabs();
1600 * A form rule function for custom data.
1602 * The rule ensures that fields selected in group_by if any) should only be the ones
1603 * present in display/select fields criteria;
1604 * note: works if and only if any custom field selected in group_by.
1606 * @param array $fields
1607 * @param array $ignoreFields
1611 public function customDataFormRule($fields, $ignoreFields = array()) {
1613 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1614 !empty($fields['group_bys'])
1616 foreach ($this->_columns
as $tableName => $table) {
1617 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1618 substr($tableName, 0, 12) == 'custom_value') &&
1619 !empty($this->_columns
[$tableName]['fields'])
1621 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1622 if (array_key_exists($fieldName, $fields['group_bys']) &&
1623 !array_key_exists($fieldName, $fields['fields'])
1625 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1627 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1628 foreach ($fields['fields'] as $fld => $val) {
1629 if (!array_key_exists($fld, $fields['group_bys']) &&
1630 !in_array($fld, $ignoreFields)
1632 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1644 * Get operators to display on form.
1646 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1648 * @param string $type
1649 * @param string $fieldName
1653 public function getOperationPair($type = "string", $fieldName = NULL) {
1654 // FIXME: At some point we should move these key-val pairs
1655 // to option_group and option_value table.
1657 case CRM_Report_Form
::OP_INT
:
1658 case CRM_Report_Form
::OP_FLOAT
:
1661 'lte' => ts('Is less than or equal to'),
1662 'gte' => ts('Is greater than or equal to'),
1663 'bw' => ts('Is between'),
1664 'eq' => ts('Is equal to'),
1665 'lt' => ts('Is less than'),
1666 'gt' => ts('Is greater than'),
1667 'neq' => ts('Is not equal to'),
1668 'nbw' => ts('Is not between'),
1669 'nll' => ts('Is empty (Null)'),
1670 'nnll' => ts('Is not empty (Null)'),
1674 case CRM_Report_Form
::OP_SELECT
:
1676 'eq' => ts('Is equal to'),
1680 case CRM_Report_Form
::OP_MONTH
:
1681 case CRM_Report_Form
::OP_MULTISELECT
:
1682 case CRM_Report_Form
::OP_ENTITYREF
:
1685 'in' => ts('Is one of'),
1686 'notin' => ts('Is not one of'),
1690 case CRM_Report_Form
::OP_DATE
:
1693 'nll' => ts('Is empty (Null)'),
1694 'nnll' => ts('Is not empty (Null)'),
1698 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1699 // use this operator for the values, concatenated with separator. For e.g if
1700 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1702 'mhas' => ts('Is one of'),
1703 'mnot' => ts('Is not one of'),
1710 'has' => ts('Contains'),
1711 'sw' => ts('Starts with'),
1712 'ew' => ts('Ends with'),
1713 'nhas' => ts('Does not contain'),
1714 'eq' => ts('Is equal to'),
1715 'neq' => ts('Is not equal to'),
1716 'nll' => ts('Is empty (Null)'),
1717 'nnll' => ts('Is not empty (Null)'),
1724 * Build the tag filter field to display on the filters tab.
1726 public function buildTagFilter() {
1727 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1728 if (!empty($contactTags)) {
1729 $this->_columns
['civicrm_tag'] = array(
1730 'dao' => 'CRM_Core_DAO_Tag',
1734 'title' => ts('Tag'),
1735 'type' => CRM_Utils_Type
::T_INT
,
1737 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1738 'options' => $contactTags,
1746 * Adds group filters to _columns (called from _Construct).
1748 public function buildGroupFilter() {
1749 $this->_columns
['civicrm_group']['filters'] = array(
1751 'name' => 'group_id',
1752 'title' => ts('Group'),
1753 'type' => CRM_Utils_Type
::T_INT
,
1754 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1756 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1759 if (empty($this->_columns
['civicrm_group']['dao'])) {
1760 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1762 if (empty($this->_columns
['civicrm_group']['alias'])) {
1763 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1768 * Get SQL operator from form text version.
1770 * @param string $operator
1774 public function getSQLOperator($operator = "like") {
1775 switch ($operator) {
1808 return 'IS NOT NULL';
1817 * Generate where clause.
1819 * This can be overridden in reports for special treatment of a field
1821 * @param array $field Field specifications
1822 * @param string $op Query operator (not an exact match to sql)
1823 * @param mixed $value
1827 * @return null|string
1829 public function whereClause(&$field, $op, $value, $min, $max) {
1831 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1833 // CRM-18010: Ensure type of each report filters
1835 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1842 if (($min !== NULL && strlen($min) > 0) ||
1843 ($max !== NULL && strlen($max) > 0)
1847 $min = CRM_Utils_Type
::escape($min, $type);
1849 $clauses[] = "( {$field['dbAlias']} >= $min )";
1852 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1856 $max = CRM_Utils_Type
::escape($max, $type);
1858 $clauses[] = "( {$field['dbAlias']} <= $max )";
1861 $clauses[] = "( {$field['dbAlias']} > $max )";
1865 if (!empty($clauses)) {
1867 $clause = implode(' AND ', $clauses);
1870 $clause = '(' . implode('OR', $clauses) . ')';
1878 if ($value !== NULL && strlen($value) > 0) {
1879 $value = CRM_Utils_Type
::escape($value, $type);
1880 if (strpos($value, '%') === FALSE) {
1881 $value = "'%{$value}%'";
1884 $value = "'{$value}'";
1886 $sqlOP = $this->getSQLOperator($op);
1887 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1893 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1894 $value = explode(',', $value);
1896 if ($value !== NULL && is_array($value) && count($value) > 0) {
1897 $sqlOP = $this->getSQLOperator($op);
1898 if (CRM_Utils_Array
::value('type', $field) ==
1899 CRM_Utils_Type
::T_STRING
1901 //cycle through selections and escape values
1902 foreach ($value as $key => $selection) {
1903 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1906 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1910 // for numerical values
1911 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1914 if ($op == 'notin') {
1915 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1918 $clause = "( " . $clause . " )";
1925 // multiple has or multiple not
1926 if ($value !== NULL && count($value) > 0) {
1927 $value = CRM_Utils_Type
::escapeAll($value, $type);
1928 $operator = $op == 'mnot' ?
'NOT' : '';
1929 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1930 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1936 if ($value !== NULL && strlen($value) > 0) {
1937 $value = CRM_Utils_Type
::escape($value, $type);
1938 if (strpos($value, '%') === FALSE) {
1940 $value = "'{$value}%'";
1943 $value = "'%{$value}'";
1947 $value = "'{$value}'";
1949 $sqlOP = $this->getSQLOperator($op);
1950 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1956 $sqlOP = $this->getSQLOperator($op);
1957 $clause = "( {$field['dbAlias']} $sqlOP )";
1963 //CRM-18457: some custom field passes value in array format against binary operator
1964 if (is_array($value) && count($value)) {
1969 if ($value !== NULL && $value !== '') {
1970 if (isset($field['clause'])) {
1971 // FIXME: we not doing escape here. Better solution is to use two
1972 // different types - data-type and filter-type
1973 $clause = $field['clause'];
1975 elseif (!is_array($value)) {
1976 $value = CRM_Utils_Type
::escape($value, $type);
1977 $sqlOP = $this->getSQLOperator($op);
1978 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1979 $value = "'{$value}'";
1981 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1987 if (!empty($field['group']) && $clause) {
1988 $clause = $this->whereGroupClause($field, $value, $op);
1990 elseif (!empty($field['tag']) && $clause) {
1991 // not using left join in query because if any contact
1992 // belongs to more than one tag, results duplicate
1994 $clause = $this->whereTagClause($field, $value, $op);
1996 elseif (!empty($field['membership_org']) && $clause) {
1997 $clause = $this->whereMembershipOrgClause($value, $op);
1999 elseif (!empty($field['membership_type']) && $clause) {
2000 $clause = $this->whereMembershipTypeClause($value, $op);
2006 * Get SQL where clause for a date field.
2008 * @param string $fieldName
2009 * @param string $relative
2010 * @param string $from
2012 * @param string $type
2013 * @param string $fromTime
2014 * @param string $toTime
2016 * @return null|string
2018 public function dateClause(
2020 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2023 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2024 $sqlOP = $this->getSQLOperator($relative);
2025 return "( {$fieldName} {$sqlOP} )";
2028 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2031 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2032 $clauses[] = "( {$fieldName} >= $from )";
2036 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2037 $clauses[] = "( {$fieldName} <= {$to} )";
2040 if (!empty($clauses)) {
2041 return implode(' AND ', $clauses);
2048 * Get values for from and to for date ranges.
2050 * @param bool $relative
2051 * @param string $from
2053 * @param string $fromTime
2054 * @param string $toTime
2058 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2059 if (empty($toTime)) {
2062 //FIX ME not working for relative
2064 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2065 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2066 $from = substr($dateRange['from'], 0, 8);
2067 //Take only Date Part, Sometime Time part is also present in 'to'
2068 $to = substr($dateRange['to'], 0, 8);
2070 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2071 $to = CRM_Utils_Date
::processDate($to, $toTime);
2072 return array($from, $to);
2076 * Alter display of rows.
2078 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2079 * such as rendering contacts as links.
2081 * @param array $rows
2082 * Rows generated by SQL, with an array for each row.
2084 public function alterDisplay(&$rows) {
2088 * Alter the way in which custom data fields are displayed.
2090 * @param array $rows
2092 public function alterCustomDataDisplay(&$rows) {
2093 // custom code to alter rows having custom values
2094 if (empty($this->_customGroupExtends
)) {
2098 $customFields = array();
2099 $customFieldIds = array();
2100 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2101 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2102 $customFieldIds[$fieldAlias] = $fieldId;
2105 if (empty($customFieldIds)) {
2109 // skip for type date and ContactReference since date format is already handled
2111 SELECT cg.table_name, cf.id
2112 FROM civicrm_custom_field cf
2113 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2114 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2115 cg.is_active = 1 AND
2116 cf.is_active = 1 AND
2117 cf.is_searchable = 1 AND
2118 cf.data_type NOT IN ('ContactReference', 'Date') AND
2119 cf.id IN (" . implode(",", $customFieldIds) . ")";
2121 $dao = CRM_Core_DAO
::executeQuery($query);
2122 while ($dao->fetch()) {
2123 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2127 $entryFound = FALSE;
2128 foreach ($rows as $rowNum => $row) {
2129 foreach ($row as $tableCol => $val) {
2130 if (array_key_exists($tableCol, $customFields)) {
2131 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2136 // skip looking further in rows, if first row itself doesn't
2137 // have the column we need
2145 * Remove duplicate rows.
2147 * @param array $rows
2149 public function removeDuplicates(&$rows) {
2150 if (empty($this->_noRepeats
)) {
2153 $checkList = array();
2155 foreach ($rows as $key => $list) {
2156 foreach ($list as $colName => $colVal) {
2157 if (array_key_exists($colName, $checkList) &&
2158 $checkList[$colName] == $colVal
2160 $rows[$key][$colName] = "";
2162 if (in_array($colName, $this->_noRepeats
)) {
2163 $checkList[$colName] = $colVal;
2170 * Fix subtotal display.
2173 * @param array $fields
2174 * @param bool $subtotal
2176 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2177 foreach ($row as $colName => $colVal) {
2178 if (in_array($colName, $fields)) {
2180 elseif (isset($this->_columnHeaders
[$colName])) {
2182 $row[$colName] = 'Subtotal';
2186 unset($row[$colName]);
2193 * Calculate grant total.
2195 * @param array $rows
2199 public function grandTotal(&$rows) {
2200 if (!$this->_rollup ||
count($rows) == 1) {
2204 $this->moveSummaryColumnsToTheRightHandSide();
2206 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2210 $this->rollupRow
= array_pop($rows);
2212 foreach ($this->_columnHeaders
as $fld => $val) {
2213 if (!in_array($fld, $this->_statFields
)) {
2214 if (!$this->_grandFlag
) {
2215 $this->rollupRow
[$fld] = ts('Grand Total');
2216 $this->_grandFlag
= TRUE;
2219 $this->rollupRow
[$fld] = "";
2224 $this->assign('grandStat', $this->rollupRow
);
2229 * Format display output.
2231 * @param array $rows
2232 * @param bool $pager
2234 public function formatDisplay(&$rows, $pager = TRUE) {
2235 // set pager based on if any limit was applied in the query.
2240 // allow building charts if any
2241 if (!empty($this->_params
['charts']) && !empty($rows)) {
2242 $this->buildChart($rows);
2243 $this->assign('chartEnabled', TRUE);
2244 $this->_chartId
= "{$this->_params['charts']}_" .
2245 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2247 $this->assign('chartId', $this->_chartId
);
2250 // unset columns not to be displayed.
2251 foreach ($this->_columnHeaders
as $key => $value) {
2252 if (!empty($value['no_display'])) {
2253 unset($this->_columnHeaders
[$key]);
2257 // unset columns not to be displayed.
2258 if (!empty($rows)) {
2259 foreach ($this->_noDisplay
as $noDisplayField) {
2260 foreach ($rows as $rowNum => $row) {
2261 unset($this->_columnHeaders
[$noDisplayField]);
2266 // build array of section totals
2267 $this->sectionTotals();
2269 // process grand-total row
2270 $this->grandTotal($rows);
2272 // use this method for formatting rows for display purpose.
2273 $this->alterDisplay($rows);
2274 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2276 // use this method for formatting custom rows for display purpose.
2277 $this->alterCustomDataDisplay($rows);
2283 * @param array $rows
2285 public function buildChart(&$rows) {
2286 // override this method for building charts.
2289 // select() method below has been added recently (v3.3), and many of the report templates might
2290 // still be having their own select() method. We should fix them as and when encountered and move
2291 // towards generalizing the select() method below.
2294 * Generate the SELECT clause and set class variable $_select.
2296 public function select() {
2297 $select = $this->_selectAliases
= array();
2299 foreach ($this->_columns
as $tableName => $table) {
2300 if (array_key_exists('fields', $table)) {
2301 foreach ($table['fields'] as $fieldName => $field) {
2302 if ($tableName == 'civicrm_address') {
2303 $this->_addressField
= TRUE;
2305 if ($tableName == 'civicrm_email') {
2306 $this->_emailField
= TRUE;
2308 if ($tableName == 'civicrm_phone') {
2309 $this->_phoneField
= TRUE;
2312 if (!empty($field['required']) ||
2313 !empty($this->_params
['fields'][$fieldName])
2316 // 1. In many cases we want select clause to be built in slightly different way
2317 // for a particular field of a particular type.
2318 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2320 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2321 if ($selectClause) {
2322 $select[] = $selectClause;
2326 // include statistics columns only if set
2327 if (!empty($field['statistics'])) {
2328 foreach ($field['statistics'] as $stat => $label) {
2329 $alias = "{$tableName}_{$fieldName}_{$stat}";
2330 switch (strtolower($stat)) {
2333 $select[] = "$stat({$field['dbAlias']}) as $alias";
2334 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2335 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2336 $this->_statFields
[$label] = $alias;
2337 $this->_selectAliases
[] = $alias;
2341 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2342 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2343 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2344 $this->_statFields
[$label] = $alias;
2345 $this->_selectAliases
[] = $alias;
2348 case 'count_distinct':
2349 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2350 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2351 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2352 $this->_statFields
[$label] = $alias;
2353 $this->_selectAliases
[] = $alias;
2357 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2358 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2359 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2360 $this->_statFields
[$label] = $alias;
2361 $this->_selectAliases
[] = $alias;
2367 $alias = "{$tableName}_{$fieldName}";
2368 $select[] = "{$field['dbAlias']} as $alias";
2369 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2370 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2371 $this->_selectAliases
[] = $alias;
2377 // select for group bys
2378 if (array_key_exists('group_bys', $table)) {
2379 foreach ($table['group_bys'] as $fieldName => $field) {
2381 if ($tableName == 'civicrm_address') {
2382 $this->_addressField
= TRUE;
2384 if ($tableName == 'civicrm_email') {
2385 $this->_emailField
= TRUE;
2387 if ($tableName == 'civicrm_phone') {
2388 $this->_phoneField
= TRUE;
2390 // 1. In many cases we want select clause to be built in slightly different way
2391 // for a particular field of a particular type.
2392 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2394 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2395 if ($selectClause) {
2396 $select[] = $selectClause;
2400 if (!empty($this->_params
['group_bys']) &&
2401 !empty($this->_params
['group_bys'][$fieldName]) &&
2402 !empty($this->_params
['group_bys_freq'])
2404 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2406 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2407 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2408 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2409 $field['title'] = 'Week';
2413 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2414 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2415 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2416 $field['title'] = 'Year';
2420 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2421 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2422 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2423 $field['title'] = 'Month';
2427 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2428 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2429 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2430 $field['title'] = 'Quarter';
2433 // for graphs and charts -
2434 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2435 $this->_interval
= $field['title'];
2436 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2437 = $field['title'] . ' Beginning';
2438 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2439 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2441 // just to make sure these values are transferred to rows.
2442 // since we 'll need them for calculation purpose,
2443 // e.g making subtotals look nicer or graphs
2444 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2445 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2452 $this->_selectClauses
= $select;
2453 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2457 * Build select clause for a single field.
2459 * @param string $tableName
2460 * @param string $tableKey
2461 * @param string $fieldName
2462 * @param string $field
2466 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2471 * Build where clause.
2473 public function where() {
2474 $this->storeWhereHavingClauseArray();
2476 if (empty($this->_whereClauses
)) {
2477 $this->_where
= "WHERE ( 1 ) ";
2478 $this->_having
= "";
2481 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2484 if ($this->_aclWhere
) {
2485 $this->_where
.= " AND {$this->_aclWhere} ";
2488 if (!empty($this->_havingClauses
)) {
2489 // use this clause to construct group by clause.
2490 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2495 * Store Where clauses into an array.
2497 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2498 * temp table that may not be part of the final where clause or added
2499 * in other functions
2501 public function storeWhereHavingClauseArray() {
2502 foreach ($this->_columns
as $tableName => $table) {
2503 if (array_key_exists('filters', $table)) {
2504 foreach ($table['filters'] as $fieldName => $field) {
2505 // respect pseudofield to filter spec so fields can be marked as
2506 // not to be handled here
2507 if (!empty($field['pseudofield'])) {
2511 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2512 if (CRM_Utils_Array
::value('operatorType', $field) ==
2513 CRM_Report_Form
::OP_MONTH
2515 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2516 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2517 if (is_array($value) && !empty($value)) {
2519 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2524 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2525 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2526 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2527 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2528 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2529 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2533 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2535 $clause = $this->whereClause($field,
2537 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2538 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2539 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2544 if (!empty($clause)) {
2545 if (!empty($field['having'])) {
2546 $this->_havingClauses
[] = $clause;
2549 $this->_whereClauses
[] = $clause;
2561 public function processReportMode() {
2562 $this->setOutputMode();
2565 = CRM_Utils_Request
::retrieve(
2568 CRM_Core_DAO
::$_nullObject
2571 $this->_absoluteUrl
= FALSE;
2573 $this->assign('printOnly', FALSE);
2575 if ($this->_outputMode
== 'print' ||
2576 ($this->_sendmail
&& !$this->_outputMode
)
2578 $this->assign('printOnly', TRUE);
2580 $this->addPaging
= FALSE;
2581 $this->assign('outputMode', 'print');
2582 $this->_outputMode
= 'print';
2583 if ($this->_sendmail
) {
2584 $this->_absoluteUrl
= TRUE;
2587 elseif ($this->_outputMode
== 'pdf') {
2589 $this->addPaging
= FALSE;
2590 $this->_absoluteUrl
= TRUE;
2592 elseif ($this->_outputMode
== 'csv') {
2594 $this->_absoluteUrl
= TRUE;
2595 $this->addPaging
= FALSE;
2597 elseif ($this->_outputMode
== 'group') {
2598 $this->assign('outputMode', 'group');
2600 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2601 $this->assign('outputMode', 'create_report');
2603 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2604 $this->_createNew
= TRUE;
2607 $this->assign('outputMode', $this->_outputMode
);
2608 $this->assign('printOnly', $printOnly);
2609 // Get today's date to include in printed reports
2611 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2612 $this->assign('reportDate', $reportDate);
2617 * Post Processing function for Form.
2619 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2620 * This function is not accessed when the api calls the report.
2622 public function beginPostProcess() {
2623 $this->setParams($this->controller
->exportValues($this->_name
));
2624 if (empty($this->_params
) &&
2627 $this->setParams($this->_formValues
);
2630 // hack to fix params when submitted from dashboard, CRM-8532
2631 // fields array is missing because form building etc is skipped
2632 // in dashboard mode for report
2633 //@todo - this could be done in the dashboard no we have a setter
2634 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2635 $this->setParams($this->_formValues
);
2638 $this->processReportMode();
2640 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2641 $this->_createNew
= ($this->_outputMode
== 'copy');
2642 CRM_Report_Form_Instance
::postProcess($this);
2644 if ($this->_outputMode
== 'delete') {
2645 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2648 $this->_formValues
= $this->_params
;
2650 $this->beginPostProcessCommon();
2654 * BeginPostProcess function run in both report mode and non-report mode (api).
2656 public function beginPostProcessCommon() {
2660 * Build the report query.
2662 * @param bool $applyLimit
2666 public function buildQuery($applyLimit = TRUE) {
2667 $this->buildGroupTempTable();
2670 $this->customDataFrom();
2672 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2673 $this->getPermissionedFTQuery($this);
2678 // order_by columns not selected for display need to be included in SELECT
2679 $unselectedSectionColumns = $this->unselectedSectionColumns();
2680 foreach ($unselectedSectionColumns as $alias => $section) {
2681 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2684 if ($applyLimit && empty($this->_params
['charts'])) {
2687 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2689 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2690 $this->addToDeveloperTab($sql);
2695 * Build group by clause.
2697 public function groupBy() {
2698 $groupBys = array();
2699 if (!empty($this->_params
['group_bys']) &&
2700 is_array($this->_params
['group_bys'])
2702 foreach ($this->_columns
as $tableName => $table) {
2703 if (array_key_exists('group_bys', $table)) {
2704 foreach ($table['group_bys'] as $fieldName => $field) {
2705 if (!empty($this->_params
['group_bys'][$fieldName])) {
2706 $groupBys[] = $field['dbAlias'];
2713 if (!empty($groupBys)) {
2714 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBys);
2719 * Build order by clause.
2721 public function orderBy() {
2722 $this->_orderBy
= "";
2723 $this->_sections
= array();
2724 $this->storeOrderByArray();
2725 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2726 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2728 $this->assign('sections', $this->_sections
);
2732 * Extract order by fields and store as an array.
2734 * In some cases other functions want to know which fields are selected for ordering by
2735 * Separating this into a separate function allows it to be called separately from constructing
2736 * the order by clause
2738 public function storeOrderByArray() {
2739 $orderBys = array();
2741 if (!empty($this->_params
['order_bys']) &&
2742 is_array($this->_params
['order_bys']) &&
2743 !empty($this->_params
['order_bys'])
2746 // Process order_bys in user-specified order
2747 foreach ($this->_params
['order_bys'] as $orderBy) {
2748 $orderByField = array();
2749 foreach ($this->_columns
as $tableName => $table) {
2750 if (array_key_exists('order_bys', $table)) {
2751 // For DAO columns defined in $this->_columns
2752 $fields = $table['order_bys'];
2754 elseif (array_key_exists('extends', $table)) {
2755 // For custom fields referenced in $this->_customGroupExtends
2756 $fields = CRM_Utils_Array
::value('fields', $table, array());
2761 if (!empty($fields) && is_array($fields)) {
2762 foreach ($fields as $fieldName => $field) {
2763 if ($fieldName == $orderBy['column']) {
2764 $orderByField = array_merge($field, $orderBy);
2765 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2772 if (!empty($orderByField)) {
2773 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2774 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2776 // Record any section headers for assignment to the template
2777 if (!empty($orderBy['section'])) {
2778 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2779 $this->_sections
[$orderByField['tplField']] = $orderByField;
2785 $this->_orderByArray
= $orderBys;
2787 $this->assign('sections', $this->_sections
);
2791 * Determine unselected columns.
2795 public function unselectedSectionColumns() {
2796 if (is_array($this->_sections
)) {
2797 return array_diff_key($this->_sections
, $this->getSelectColumns());
2805 * Build output rows.
2807 * @param string $sql
2808 * @param array $rows
2810 public function buildRows($sql, &$rows) {
2811 $dao = CRM_Core_DAO
::executeQuery($sql);
2812 if (!is_array($rows)) {
2816 // use this method to modify $this->_columnHeaders
2817 $this->modifyColumnHeaders();
2819 $unselectedSectionColumns = $this->unselectedSectionColumns();
2821 while ($dao->fetch()) {
2823 foreach ($this->_columnHeaders
as $key => $value) {
2824 if (property_exists($dao, $key)) {
2825 $row[$key] = $dao->$key;
2829 // section headers not selected for display need to be added to row
2830 foreach ($unselectedSectionColumns as $key => $values) {
2831 if (property_exists($dao, $key)) {
2832 $row[$key] = $dao->$key;
2841 * Calculate section totals.
2843 * When "order by" fields are marked as sections, this assigns to the template
2844 * an array of total counts for each section. This data is used by the Smarty
2845 * plugin {sectionTotal}.
2847 public function sectionTotals() {
2849 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2850 if (empty($this->_selectAliases
)) {
2854 if (!empty($this->_sections
)) {
2855 // build the query with no LIMIT clause
2856 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2857 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2859 // pull section aliases out of $this->_sections
2860 $sectionAliases = array_keys($this->_sections
);
2863 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2864 $ifnulls[] = "ifnull($alias, '') as $alias";
2866 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2867 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2869 // Group (un-limited) report by all aliases and get counts. This might
2870 // be done more efficiently when the contents of $sql are known, ie. by
2871 // overriding this method in the report class.
2873 $query = $this->_select
.
2874 ", count(*) as ct from ($sql) as subquery group by " .
2875 implode(", ", $sectionAliases);
2877 // initialize array of total counts
2879 $dao = CRM_Core_DAO
::executeQuery($query);
2880 while ($dao->fetch()) {
2882 // let $this->_alterDisplay translate any integer ids to human-readable values.
2883 $rows[0] = $dao->toArray();
2884 $this->alterDisplay($rows);
2887 // add totals for all permutations of section values
2890 $aliasCount = count($sectionAliases);
2891 foreach ($sectionAliases as $alias) {
2892 $values[] = $row[$alias];
2893 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2894 if ($i == $aliasCount) {
2895 // the last alias is the lowest-level section header; use count as-is
2896 $totals[$key] = $dao->ct
;
2899 // other aliases are higher level; roll count into their total
2900 $totals[$key] +
= $dao->ct
;
2904 $this->assign('sectionTotals', $totals);
2909 * Modify column headers.
2911 public function modifyColumnHeaders() {
2912 // use this method to modify $this->_columnHeaders
2916 * Move totals columns to the right edge of the table.
2918 * It seems like a more logical layout to have any totals columns on the far right regardless of
2919 * the location of the rest of their table.
2921 public function moveSummaryColumnsToTheRightHandSide() {
2922 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2923 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2927 * Assign rows to the template.
2929 * @param array $rows
2931 public function doTemplateAssignment(&$rows) {
2932 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2933 $this->assign_by_ref('rows', $rows);
2934 $this->assign('statistics', $this->statistics($rows));
2938 * Build report statistics.
2940 * Override this method to build your own statistics.
2942 * @param array $rows
2946 public function statistics(&$rows) {
2947 $statistics = array();
2949 $count = count($rows);
2950 // Why do we increment the count for rollup seems to artificially inflate the count.
2951 // It seems perhaps intentional to include the summary row in the count of results - although
2952 // this just seems odd.
2953 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2957 $this->countStat($statistics, $count);
2959 $this->groupByStat($statistics);
2961 $this->filterStat($statistics);
2967 * Add count statistics.
2969 * @param array $statistics
2972 public function countStat(&$statistics, $count) {
2973 $statistics['counts']['rowCount'] = array(
2974 'title' => ts('Row(s) Listed'),
2978 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2979 $statistics['counts']['rowsFound'] = array(
2980 'title' => ts('Total Row(s)'),
2981 'value' => $this->_rowsFound
,
2987 * Add group by statistics.
2989 * @param array $statistics
2991 public function groupByStat(&$statistics) {
2992 if (!empty($this->_params
['group_bys']) &&
2993 is_array($this->_params
['group_bys']) &&
2994 !empty($this->_params
['group_bys'])
2996 foreach ($this->_columns
as $tableName => $table) {
2997 if (array_key_exists('group_bys', $table)) {
2998 foreach ($table['group_bys'] as $fieldName => $field) {
2999 if (!empty($this->_params
['group_bys'][$fieldName])) {
3000 $combinations[] = $field['title'];
3005 $statistics['groups'][] = array(
3006 'title' => ts('Grouping(s)'),
3007 'value' => implode(' & ', $combinations),
3013 * Filter statistics.
3015 * @param array $statistics
3017 public function filterStat(&$statistics) {
3018 foreach ($this->_columns
as $tableName => $table) {
3019 if (array_key_exists('filters', $table)) {
3020 foreach ($table['filters'] as $fieldName => $field) {
3021 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3022 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3023 CRM_Utils_Array
::value('operatorType', $field) !=
3024 CRM_Report_Form
::OP_MONTH
3028 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3029 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3030 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3031 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3032 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3034 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3035 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3037 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3038 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3041 $statistics['filters'][] = array(
3042 'title' => $field['title'],
3043 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3046 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3047 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3049 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3050 $statistics['filters'][] = array(
3051 'title' => $field['title'],
3052 'value' => $pair[$rel],
3057 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3060 $pair = $this->getOperationPair(
3061 CRM_Utils_Array
::value('operatorType', $field),
3064 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3065 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3066 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3067 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3068 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3070 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3071 $this->setEntityRefDefaults($field, $tableName);
3072 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3073 array('id' => $val) +
3074 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3076 foreach ($result['values'] as $v) {
3077 $values[] = $v['label'];
3079 $value = "{$pair[$op]} " . implode(', ', $values);
3081 elseif ($op == 'nll' ||
$op == 'nnll') {
3082 $value = $pair[$op];
3084 elseif (is_array($val) && (!empty($val))) {
3085 $options = CRM_Utils_Array
::value('options', $field, array());
3086 foreach ($val as $key => $valIds) {
3087 if (isset($options[$valIds])) {
3088 $val[$key] = $options[$valIds];
3091 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3092 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3093 $val = implode(', ', $val);
3094 $value = "{$pair[$op]} " . $val;
3096 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3097 isset($field['options']) &&
3098 is_array($field['options']) && !empty($field['options'])
3100 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3101 CRM_Utils_Array
::value($val, $field['options'], $val);
3104 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3108 $statistics['filters'][] = array(
3109 'title' => CRM_Utils_Array
::value('title', $field),
3120 * End post processing.
3122 * @param array|null $rows
3124 public function endPostProcess(&$rows = NULL) {
3125 if ($this->_storeResultSet
) {
3126 $this->_resultSet
= $rows;
3129 if ($this->_outputMode
== 'print' ||
3130 $this->_outputMode
== 'pdf' ||
3134 $content = $this->compileContent();
3135 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3139 if ($this->_sendmail
) {
3140 $config = CRM_Core_Config
::singleton();
3141 $attachments = array();
3143 if ($this->_outputMode
== 'csv') {
3145 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3146 ": {$url}</p>" . '<p>' .
3147 ts('The report is attached as a CSV file.') . '</p>' .
3148 $this->_formValues
['report_footer'];
3150 $csvFullFilename = $config->templateCompileDir
.
3151 CRM_Utils_File
::makeFileName('CiviReport.csv');
3152 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3153 file_put_contents($csvFullFilename, $csvContent);
3154 $attachments[] = array(
3155 'fullPath' => $csvFullFilename,
3156 'mime_type' => 'text/csv',
3157 'cleanName' => 'CiviReport.csv',
3160 if ($this->_outputMode
== 'pdf') {
3161 // generate PDF content
3162 $pdfFullFilename = $config->templateCompileDir
.
3163 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3164 file_put_contents($pdfFullFilename,
3165 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3166 TRUE, array('orientation' => 'landscape')
3169 // generate Email Content
3171 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3172 ": {$url}</p>" . '<p>' .
3173 ts('The report is attached as a PDF file.') . '</p>' .
3174 $this->_formValues
['report_footer'];
3176 $attachments[] = array(
3177 'fullPath' => $pdfFullFilename,
3178 'mime_type' => 'application/pdf',
3179 'cleanName' => 'CiviReport.pdf',
3183 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3184 $this->_outputMode
, $attachments
3187 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3190 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3194 elseif ($this->_outputMode
== 'print') {
3198 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3199 $config = CRM_Core_Config
::singleton();
3200 //get chart image name
3201 $chartImg = $this->_chartId
. '.png';
3202 //get image url path
3204 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3206 $uploadUrl .= $chartImg;
3207 //get image doc path to overwrite
3209 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3210 'openFlashChart/' . $chartImg;
3212 $chart = imagecreatefrompng($uploadUrl);
3213 //convert it into formatted png
3214 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3215 //overwrite with same image
3216 imagepng($chart, $uploadImg);
3218 imagedestroy($chart);
3220 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3222 CRM_Utils_System
::civiExit();
3224 elseif ($this->_outputMode
== 'csv') {
3225 CRM_Report_Utils_Report
::export2csv($this, $rows);
3227 elseif ($this->_outputMode
== 'group') {
3228 $group = $this->_params
['groups'];
3229 $this->add2group($group);
3234 * Set store result set indicator to TRUE.
3236 * @todo explain what this does
3238 public function storeResultSet() {
3239 $this->_storeResultSet
= TRUE;
3247 public function getResultSet() {
3248 return $this->_resultSet
;
3252 * Get the sql used to generate the report.
3256 public function getReportSql() {
3257 return $this->sqlArray
;
3261 * Use the form name to create the tpl file name.
3265 public function getTemplateFileName() {
3266 $defaultTpl = parent
::getTemplateFileName();
3267 $template = CRM_Core_Smarty
::singleton();
3268 if (!$template->template_exists($defaultTpl)) {
3269 $defaultTpl = 'CRM/Report/Form.tpl';
3275 * Compile the report content.
3277 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3281 public function compileContent() {
3282 $templateFile = $this->getHookedTemplateFileName();
3283 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3284 CRM_Core_Form
::$_template->fetch($templateFile) .
3285 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3290 * Post process function.
3292 public function postProcess() {
3293 // get ready with post process params
3294 $this->beginPostProcess();
3297 $sql = $this->buildQuery();
3299 // build array of result based on column headers. This method also allows
3300 // modifying column headers before using it to build result set i.e $rows.
3302 $this->buildRows($sql, $rows);
3304 // format result set.
3305 $this->formatDisplay($rows);
3307 // assign variables to templates
3308 $this->doTemplateAssignment($rows);
3310 // do print / pdf / instance stuff if needed
3311 $this->endPostProcess($rows);
3317 * @param int $rowCount
3321 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3322 // lets do the pager if in html mode
3323 $this->_limit
= NULL;
3325 // CRM-14115, over-ride row count if rowCount is specified in URL
3326 if ($this->_dashBoardRowCount
) {
3327 $rowCount = $this->_dashBoardRowCount
;
3329 if ($this->addPaging
) {
3330 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3332 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3334 // @todo all http vars should be extracted in the preProcess
3335 // - not randomly in the class
3336 if (!$pageId && !empty($_POST)) {
3337 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3338 $pageId = max((int) $_POST['crmPID_B'], 1);
3340 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3341 $pageId = max((int) $_POST['crmPID'], 1);
3343 unset($_POST['crmPID_B'], $_POST['crmPID']);
3346 $pageId = $pageId ?
$pageId : 1;
3347 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3348 $offset = ($pageId - 1) * $rowCount;
3350 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3351 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3353 $this->_limit
= " LIMIT $offset, $rowCount";
3354 return array($offset, $rowCount);
3356 if ($this->_limitValue
) {
3357 if ($this->_offsetValue
) {
3358 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3361 $this->_limit
= " LIMIT " . $this->_limitValue
;
3369 * @param int $rowCount
3371 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3372 // CRM-14115, over-ride row count if rowCount is specified in URL
3373 if ($this->_dashBoardRowCount
) {
3374 $rowCount = $this->_dashBoardRowCount
;
3377 if ($this->_limit
&& ($this->_limit
!= '')) {
3378 if (!$this->_rowsFound
) {
3379 $sql = "SELECT FOUND_ROWS();";
3380 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3383 'total' => $this->_rowsFound
,
3384 'rowCount' => $rowCount,
3385 'status' => ts('Records') . ' %%StatusMessage%%',
3386 'buttonBottom' => 'PagerBottomButton',
3387 'buttonTop' => 'PagerTopButton',
3389 if (!empty($this->controller
)) {
3390 // This happens when being called from the api Really we want the api to be able to
3391 // pass paging parameters, but at this stage just preventing test crashes.
3392 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3395 $pager = new CRM_Utils_Pager($params);
3396 $this->assign_by_ref('pager', $pager);
3397 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3402 * Build a group filter with contempt for large data sets.
3404 * This function has been retained as it takes time to migrate the reports over
3405 * to the new method which will not crash on large datasets.
3409 * @param string $field
3410 * @param mixed $value
3415 public function legacySlowGroupFilterClause($field, $value, $op) {
3416 $smartGroupQuery = "";
3418 $group = new CRM_Contact_DAO_Group();
3419 $group->is_active
= 1;
3421 $smartGroups = array();
3422 while ($group->fetch()) {
3423 if (in_array($group->id
, $this->_params
['gid_value']) &&
3424 $group->saved_search_id
3426 $smartGroups[] = $group->id
;
3430 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3432 $smartGroupQuery = '';
3433 if (!empty($smartGroups)) {
3434 $smartGroups = implode(',', $smartGroups);
3435 $smartGroupQuery = " UNION DISTINCT
3436 SELECT DISTINCT smartgroup_contact.contact_id
3437 FROM civicrm_group_contact_cache smartgroup_contact
3438 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3441 $sqlOp = $this->getSQLOperator($op);
3442 if (!is_array($value)) {
3443 $value = array($value);
3445 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3447 $contactAlias = $this->_aliases
['civicrm_contact'];
3448 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3449 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3451 return " {$contactAlias}.id {$sqlOp} (
3452 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3453 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3454 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3455 {$smartGroupQuery} ) ";
3459 * Build where clause for groups.
3461 * @param string $field
3462 * @param mixed $value
3467 public function whereGroupClause($field, $value, $op) {
3468 if ($this->groupFilterNotOptimised
) {
3469 return $this->legacySlowGroupFilterClause($field, $value, $op);
3471 if ($op === 'notin') {
3472 return " group_temp_table.id IS NULL ";
3474 // We will have used an inner join instead.
3480 * Create a table of the contact ids included by the group filter.
3482 * This function is called by both the api (tests) and the UI.
3484 public function buildGroupTempTable() {
3485 if (!empty($this->groupTempTable
) ||
empty ($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3488 $filteredGroups = (array) $this->_params
['gid_value'];
3490 $groups = civicrm_api3('Group', 'get', array(
3492 'id' => array('IN' => $filteredGroups),
3493 'saved_search_id' => array('>' => 0),
3496 $smartGroups = array_keys($groups['values']);
3499 SELECT group_contact.contact_id as id
3500 FROM civicrm_group_contact group_contact
3501 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3502 AND group_contact.status = 'Added' ";
3504 if (!empty($smartGroups)) {
3505 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3506 $smartGroups = implode(',', $smartGroups);
3509 SELECT smartgroup_contact.contact_id as id
3510 FROM civicrm_group_contact_cache smartgroup_contact
3511 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3514 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3515 $this->executeReportQuery("
3516 CREATE TEMPORARY TABLE $this->groupTempTable
3519 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3523 * Execute query and add it to the developer tab.
3525 * @param string $query
3526 * @param array $params
3528 * @return \CRM_Core_DAO|object
3530 protected function executeReportQuery($query, $params = array()) {
3531 $this->addToDeveloperTab($query);
3532 return CRM_Core_DAO
::executeQuery($query, $params);
3536 * Build where clause for tags.
3538 * @param string $field
3539 * @param mixed $value
3544 public function whereTagClause($field, $value, $op) {
3545 // not using left join in query because if any contact
3546 // belongs to more than one tag, results duplicate
3548 $sqlOp = $this->getSQLOperator($op);
3549 if (!is_array($value)) {
3550 $value = array($value);
3552 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3553 $entity_table = $this->_tagFilterTable
;
3554 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3555 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3556 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3557 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3561 * Generate membership organization clause.
3563 * @param mixed $value
3564 * @param string $op SQL Operator
3568 public function whereMembershipOrgClause($value, $op) {
3569 $sqlOp = $this->getSQLOperator($op);
3570 if (!is_array($value)) {
3571 $value = array($value);
3574 $tmp_membership_org_sql_list = implode(', ', $value);
3575 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3576 SELECT DISTINCT mem.contact_id
3577 FROM civicrm_membership mem
3578 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3579 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3580 WHERE mt.member_of_contact_id IN (" .
3581 $tmp_membership_org_sql_list . ")
3582 AND mt.is_active = '1'
3583 AND mem_status.is_current_member = '1'
3584 AND mem_status.is_active = '1' ) ";
3588 * Generate Membership Type SQL Clause.
3590 * @param mixed $value
3596 public function whereMembershipTypeClause($value, $op) {
3597 $sqlOp = $this->getSQLOperator($op);
3598 if (!is_array($value)) {
3599 $value = array($value);
3602 $tmp_membership_sql_list = implode(', ', $value);
3603 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3604 SELECT DISTINCT mem.contact_id
3605 FROM civicrm_membership mem
3606 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3607 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3608 WHERE mem.membership_type_id IN (" .
3609 $tmp_membership_sql_list . ")
3610 AND mt.is_active = '1'
3611 AND mem_status.is_current_member = '1'
3612 AND mem_status.is_active = '1' ) ";
3616 * Build acl clauses.
3618 * @param string $tableAlias
3620 public function buildACLClause($tableAlias = 'contact_a') {
3621 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3625 * Add custom data to the columns.
3627 * @param bool $addFields
3628 * @param array $permCustomGroupIds
3630 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3631 if (empty($this->_customGroupExtends
)) {
3634 if (!is_array($this->_customGroupExtends
)) {
3635 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3637 $customGroupWhere = '';
3638 if (!empty($permCustomGroupIds)) {
3639 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3643 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3644 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3645 FROM civicrm_custom_group cg
3646 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3647 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3649 cg.is_active = 1 AND
3650 cf.is_active = 1 AND
3651 cf.is_searchable = 1
3652 ORDER BY cg.weight, cf.weight";
3653 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3656 while ($customDAO->fetch()) {
3657 if ($customDAO->table_name
!= $curTable) {
3658 $curTable = $customDAO->table_name
;
3659 $curFields = $curFilters = array();
3662 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3663 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3664 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3665 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3667 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3668 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3669 $this->_columns
[$curTable][$colKey] = array();
3673 $fieldName = 'custom_' . $customDAO->cf_id
;
3676 // this makes aliasing work in favor
3677 $curFields[$fieldName] = array(
3678 'name' => $customDAO->column_name
,
3679 'title' => $customDAO->label
,
3680 'dataType' => $customDAO->data_type
,
3681 'htmlType' => $customDAO->html_type
,
3684 if ($this->_customGroupFilters
) {
3685 // this makes aliasing work in favor
3686 $curFilters[$fieldName] = array(
3687 'name' => $customDAO->column_name
,
3688 'title' => $customDAO->label
,
3689 'dataType' => $customDAO->data_type
,
3690 'htmlType' => $customDAO->html_type
,
3694 switch ($customDAO->data_type
) {
3697 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3698 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3699 // CRM-6946, show time part for datetime date fields
3700 if ($customDAO->time_format
) {
3701 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3706 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3707 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3708 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3712 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3713 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3717 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3718 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3719 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3723 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3724 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3728 case 'StateProvince':
3730 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3732 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3733 if ($options !== FALSE) {
3734 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3735 $curFilters[$fieldName]['options'] = $options;
3739 case 'ContactReference':
3740 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3741 $curFilters[$fieldName]['name'] = 'display_name';
3742 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3744 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3745 $curFields[$fieldName]['name'] = 'display_name';
3746 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3750 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3751 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3755 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3756 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3757 if ($options !== FALSE) {
3758 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3759 $curFilters[$fieldName]['options'] = $options;
3763 if (!array_key_exists('type', $curFields[$fieldName])) {
3764 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3768 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3770 if ($this->_customGroupFilters
) {
3771 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3773 if ($this->_customGroupGroupBy
) {
3774 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3780 * Build custom data from clause.
3782 * @param bool $joinsForFiltersOnly
3783 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3785 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3786 if (empty($this->_customGroupExtends
)) {
3789 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3790 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3791 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3792 $customTables = array();
3793 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3794 while ($customTablesDAO->fetch()) {
3795 $customTables[] = $customTablesDAO->table_name
;
3798 foreach ($this->_columns
as $table => $prop) {
3799 if (in_array($table, $customTables)) {
3800 $extendsTable = $mapper[$prop['extends']];
3801 // Check field is required for rendering the report.
3802 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3805 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3807 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3809 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3810 // handle for ContactReference
3811 if (array_key_exists('fields', $prop)) {
3812 foreach ($prop['fields'] as $fieldName => $field) {
3813 if (CRM_Utils_Array
::value('dataType', $field) ==
3816 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3818 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3827 * Check if the field is selected.
3829 * @param string $prop
3833 public function isFieldSelected($prop) {
3838 if (!empty($this->_params
['fields'])) {
3839 foreach (array_keys($prop['fields']) as $fieldAlias) {
3840 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3841 if ($customFieldId) {
3842 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3846 //might be survey response field.
3847 if (!empty($this->_params
['fields']['survey_response']) &&
3848 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3856 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3857 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3858 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3859 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3866 if (!empty($this->_params
['order_bys'])) {
3867 foreach (array_keys($prop['fields']) as $fieldAlias) {
3868 foreach ($this->_params
['order_bys'] as $orderBy) {
3869 if ($fieldAlias == $orderBy['column'] &&
3870 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3877 return $this->isFieldFiltered($prop);
3882 * Check if the field is used as a filter.
3884 * @param string $prop
3888 protected function isFieldFiltered($prop) {
3889 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3890 foreach ($prop['filters'] as $fieldAlias => $val) {
3899 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3900 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3901 ||
($attach != 'relative' &&
3902 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3908 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3909 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3920 * Check for empty order_by configurations and remove them.
3922 * Also set template to hide them.
3924 * @param array $formValues
3926 public function preProcessOrderBy(&$formValues) {
3927 // Object to show/hide form elements
3928 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3930 $_showHide->addShow('optionField_1');
3932 // Cycle through order_by options; skip any empty ones, and hide them as well
3935 if (!empty($formValues['order_bys'])) {
3936 foreach ($formValues['order_bys'] as $order_by) {
3937 if ($order_by['column'] && $order_by['column'] != '-') {
3938 $_showHide->addShow('optionField_' . $n);
3939 $orderBys[$n] = $order_by;
3944 for ($i = $n; $i <= 5; $i++
) {
3946 $_showHide->addHide('optionField_' . $i);
3950 // overwrite order_by options with modified values
3951 if (!empty($orderBys)) {
3952 $formValues['order_bys'] = $orderBys;
3955 $formValues['order_bys'] = array(1 => array('column' => '-'));
3958 // assign show/hide data to template
3959 $_showHide->addToTemplate();
3963 * Check if table name has columns in SELECT clause.
3965 * @param string $tableName
3966 * Name of table (index of $this->_columns array).
3970 public function isTableSelected($tableName) {
3971 return in_array($tableName, $this->selectedTables());
3975 * Check if table name has columns in WHERE or HAVING clause.
3977 * @param string $tableName
3978 * Name of table (index of $this->_columns array).
3982 public function isTableFiltered($tableName) {
3983 // Cause the array to be generated if not previously done.
3984 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3985 $this->selectedTables();
3987 return in_array($tableName, $this->filteredTables
);
3991 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3993 * If the array is unset it will be built.
3998 public function selectedTables() {
3999 if (!$this->_selectedTables
) {
4000 $orderByColumns = array();
4001 if (array_key_exists('order_bys', $this->_params
) &&
4002 is_array($this->_params
['order_bys'])
4004 foreach ($this->_params
['order_bys'] as $orderBy) {
4005 $orderByColumns[] = $orderBy['column'];
4009 foreach ($this->_columns
as $tableName => $table) {
4010 if (array_key_exists('fields', $table)) {
4011 foreach ($table['fields'] as $fieldName => $field) {
4012 if (!empty($field['required']) ||
4013 !empty($this->_params
['fields'][$fieldName])
4015 $this->_selectedTables
[] = $tableName;
4020 if (array_key_exists('order_bys', $table)) {
4021 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4022 if (in_array($orderByName, $orderByColumns)) {
4023 $this->_selectedTables
[] = $tableName;
4028 if (array_key_exists('filters', $table)) {
4029 foreach ($table['filters'] as $filterName => $filter) {
4030 if (!empty($this->_params
["{$filterName}_value"]) ||
4031 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4033 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4036 $this->_selectedTables
[] = $tableName;
4037 $this->filteredTables
[] = $tableName;
4044 return $this->_selectedTables
;
4048 * Add address fields.
4050 * @deprecated - use getAddressColumns which is a more accurate description
4051 * and also accepts an array of options rather than a long list
4053 * adding address fields to construct function in reports
4055 * @param bool $groupBy
4056 * Add GroupBy? Not appropriate for detail report.
4057 * @param bool $orderBy
4058 * Add GroupBy? Not appropriate for detail report.
4059 * @param bool $filters
4060 * @param array $defaults
4063 * address fields for construct clause
4065 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4066 $defaultAddressFields = array(
4067 'street_address' => ts('Street Address'),
4068 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4069 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4070 'street_number' => ts('Street Number'),
4071 'street_name' => ts('Street Name'),
4072 'street_unit' => ts('Street Unit'),
4073 'city' => ts('City'),
4074 'postal_code' => ts('Postal Code'),
4075 'postal_code_suffix' => ts('Postal Code Suffix'),
4076 'country_id' => ts('Country'),
4077 'state_province_id' => ts('State/Province'),
4078 'county_id' => ts('County'),
4080 $addressFields = array(
4081 'civicrm_address' => array(
4082 'dao' => 'CRM_Core_DAO_Address',
4084 'address_name' => array(
4085 'title' => ts('Address Name'),
4086 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4090 'grouping' => 'location-fields',
4093 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4094 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4095 'title' => $fieldLabel,
4096 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4101 // Address filter depends on whether street address parsing is enabled.
4103 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4106 if ($addressOptions['street_address_parsing']) {
4107 $street_address_filters = array(
4108 'street_number' => array(
4109 'title' => ts('Street Number'),
4110 'type' => CRM_Utils_Type
::T_INT
,
4111 'name' => 'street_number',
4113 'street_name' => array(
4114 'title' => ts('Street Name'),
4115 'name' => 'street_name',
4116 'type' => CRM_Utils_Type
::T_STRING
,
4121 $street_address_filters = array(
4122 'street_address' => array(
4123 'title' => ts('Street Address'),
4124 'type' => CRM_Utils_Type
::T_STRING
,
4125 'name' => 'street_address',
4129 $general_address_filters = array(
4130 'postal_code' => array(
4131 'title' => ts('Postal Code'),
4132 'type' => CRM_Utils_Type
::T_STRING
,
4133 'name' => 'postal_code',
4136 'title' => ts('City'),
4137 'type' => CRM_Utils_Type
::T_STRING
,
4140 'country_id' => array(
4141 'name' => 'country_id',
4142 'title' => ts('Country'),
4143 'type' => CRM_Utils_Type
::T_INT
,
4144 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4145 'options' => CRM_Core_PseudoConstant
::country(),
4147 'state_province_id' => array(
4148 'name' => 'state_province_id',
4149 'title' => ts('State/Province'),
4150 'type' => CRM_Utils_Type
::T_INT
,
4151 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4152 'options' => array(),
4154 'county_id' => array(
4155 'name' => 'county_id',
4156 'title' => ts('County'),
4157 'type' => CRM_Utils_Type
::T_INT
,
4158 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4159 'options' => array(),
4163 $addressFields['civicrm_address']['filters'] = array_merge(
4164 $street_address_filters,
4165 $general_address_filters);
4168 $addressFields['civicrm_address']['order_bys'] = array(
4169 'street_name' => array('title' => ts('Street Name')),
4170 'street_number' => array('title' => ts('Odd / Even Street Number')),
4171 'street_address' => NULL,
4173 'postal_code' => NULL,
4178 $addressFields['civicrm_address']['group_bys'] = array(
4179 'street_address' => NULL,
4181 'postal_code' => NULL,
4182 'state_province_id' => array(
4183 'title' => ts('State/Province'),
4185 'country_id' => array(
4186 'title' => ts('Country'),
4188 'county_id' => array(
4189 'title' => ts('County'),
4193 return $addressFields;
4197 * Do AlterDisplay processing on Address Fields.
4200 * @param array $rows
4201 * @param int $rowNum
4202 * @param string $baseUrl
4203 * @param string $linkText
4207 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4208 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4209 $entryFound = FALSE;
4211 if (array_key_exists('civicrm_address_country_id', $row)) {
4212 if ($value = $row['civicrm_address_country_id']) {
4213 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4215 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4216 "reset=1&force=1&{$criteriaQueryParams}&" .
4217 "country_id_op=in&country_id_value={$value}",
4218 $this->_absoluteUrl
, $this->_id
4220 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4221 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4222 array(1 => $linkText)
4229 if (array_key_exists('civicrm_address_county_id', $row)) {
4230 if ($value = $row['civicrm_address_county_id']) {
4231 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4233 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4234 "reset=1&force=1&{$criteriaQueryParams}&" .
4235 "county_id_op=in&county_id_value={$value}",
4236 $this->_absoluteUrl
, $this->_id
4238 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4239 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4240 array(1 => $linkText)
4246 // handle state province
4247 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4248 if ($value = $row['civicrm_address_state_province_id']) {
4249 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4251 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4252 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4253 $this->_absoluteUrl
, $this->_id
4255 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4256 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4257 array(1 => $linkText)
4268 * Do AlterDisplay processing on Address Fields.
4271 * @param array $rows
4272 * @param int $rowNum
4273 * @param string $baseUrl
4274 * @param string $linkText
4278 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4279 $entryFound = FALSE;
4280 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4281 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4282 $addLinks = array('gender_id' => 'Gender');
4283 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4284 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4285 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4286 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4287 $rowLabels = array();
4288 foreach ($rowValues as $rowValue) {
4290 $rowLabels[] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4293 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4294 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4295 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4301 $yesNoFields = array(
4302 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4304 foreach ($yesNoFields as $fieldName) {
4305 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4306 // Since these are essentially 'negative fields' it feels like it
4307 // makes sense to only highlight the exceptions hence no 'No'.
4308 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4316 * Adjusts dates passed in to YEAR() for fiscal year.
4318 * @param string $fieldName
4322 public function fiscalYearOffset($fieldName) {
4323 $config = CRM_Core_Config
::singleton();
4324 $fy = $config->fiscalYearStart
;
4325 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4326 ($fy['d'] == 1 && $fy['M'] == 1)
4328 return "YEAR( $fieldName )";
4330 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4331 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4335 * Add Address into From Table if required.
4337 public function addAddressFromClause() {
4338 // include address field if address column is to be included
4339 if ((isset($this->_addressField
) &&
4340 $this->_addressField
4342 $this->isTableSelected('civicrm_address')
4345 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4346 ON ({$this->_aliases['civicrm_contact']}.id =
4347 {$this->_aliases['civicrm_address']}.contact_id) AND
4348 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4353 * Add Phone into From Table if required.
4355 public function addPhoneFromClause() {
4356 // include address field if address column is to be included
4357 if ($this->isTableSelected('civicrm_phone')
4360 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4361 ON ({$this->_aliases['civicrm_contact']}.id =
4362 {$this->_aliases['civicrm_phone']}.contact_id) AND
4363 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4368 * Get phone columns to add to array.
4370 * @param array $options
4371 * - prefix Prefix to add to table (in case of more than one instance of the table)
4372 * - prefix_label Label to give columns from this phone table instance
4375 * phone columns definition
4377 public function getPhoneColumns($options = array()) {
4378 $defaultOptions = array(
4380 'prefix_label' => '',
4383 $options = array_merge($defaultOptions, $options);
4386 $options['prefix'] . 'civicrm_phone' => array(
4387 'dao' => 'CRM_Core_DAO_Phone',
4389 $options['prefix'] . 'phone' => array(
4390 'title' => ts($options['prefix_label'] . 'Phone'),
4400 * Get address columns to add to array.
4402 * @param array $options
4403 * - prefix Prefix to add to table (in case of more than one instance of the table)
4404 * - prefix_label Label to give columns from this address table instance
4407 * address columns definition
4409 public function getAddressColumns($options = array()) {
4412 'prefix_label' => '',
4416 'defaults' => array(),
4418 return $this->addAddressFields(
4419 $options['group_by'],
4420 $options['order_by'],
4421 $options['filters'],
4422 $options['defaults']
4427 * Get a standard set of contact fields.
4431 public function getBasicContactFields() {
4433 'sort_name' => array(
4434 'title' => ts('Contact Name'),
4439 'no_display' => TRUE,
4442 'prefix_id' => array(
4443 'title' => ts('Contact Prefix'),
4445 'first_name' => array(
4446 'title' => ts('First Name'),
4448 'nick_name' => array(
4449 'title' => ts('Nick Name'),
4451 'middle_name' => array(
4452 'title' => ts('Middle Name'),
4454 'last_name' => array(
4455 'title' => ts('Last Name'),
4457 'suffix_id' => array(
4458 'title' => ts('Contact Suffix'),
4460 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4461 'email_greeting_display' => array('title' => ts('Email Greeting')),
4462 'addressee_display' => array('title' => ts('Addressee')),
4463 'contact_type' => array(
4464 'title' => ts('Contact Type'),
4466 'contact_sub_type' => array(
4467 'title' => ts('Contact Subtype'),
4469 'gender_id' => array(
4470 'title' => ts('Gender'),
4472 'birth_date' => array(
4473 'title' => ts('Birth Date'),
4476 'title' => ts('Age'),
4477 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4479 'job_title' => array(
4480 'title' => ts('Contact Job title'),
4482 'organization_name' => array(
4483 'title' => ts('Organization Name'),
4485 'external_identifier' => array(
4486 'title' => ts('Contact identifier from external system'),
4488 'do_not_email' => array(),
4489 'do_not_phone' => array(),
4490 'do_not_mail' => array(),
4491 'do_not_sms' => array(),
4492 'is_opt_out' => array(),
4493 'is_deceased' => array(),
4494 'preferred_language' => array(),
4499 * Get a standard set of contact filters.
4503 public function getBasicContactFilters() {
4505 'sort_name' => array(
4506 'title' => ts('Contact Name'),
4509 'title' => ts('Contact Source'),
4510 'type' => CRM_Utils_Type
::T_STRING
,
4513 'title' => ts('Contact ID'),
4514 'no_display' => TRUE,
4516 'gender_id' => array(
4517 'title' => ts('Gender'),
4518 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4519 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4521 'birth_date' => array(
4522 'title' => ts('Birth Date'),
4523 'operatorType' => CRM_Report_Form
::OP_DATE
,
4525 'contact_type' => array(
4526 'title' => ts('Contact Type'),
4528 'contact_sub_type' => array(
4529 'title' => ts('Contact Subtype'),
4531 'modified_date' => array(
4532 'title' => ts('Contact Modified'),
4533 'operatorType' => CRM_Report_Form
::OP_DATE
,
4534 'type' => CRM_Utils_Type
::T_DATE
,
4536 'is_deceased' => array(
4537 'title' => ts('Deceased'),
4538 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4541 'do_not_email' => array(
4542 'title' => ts('Do not email'),
4543 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4545 'do_not_phone' => array(
4546 'title' => ts('Do not phone'),
4547 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4549 'do_not_mail' => array(
4550 'title' => ts('Do not mail'),
4551 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4553 'do_not_sms' => array(
4554 'title' => ts('Do not SMS'),
4555 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4557 'is_opt_out' => array(
4558 'title' => ts('Do not bulk email'),
4559 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4561 'preferred_language' => array(
4562 'title' => ts('Preferred Language'),
4568 * Add contact to group.
4570 * @param int $groupID
4572 public function add2group($groupID) {
4573 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4574 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4576 // here are we are prepending / adding contact id field that could be used for adding group
4577 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4578 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select
)) {
4579 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4582 $select = str_ireplace('SELECT ', $select, $this->_select
);
4585 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4586 $sql = str_replace('WITH ROLLUP', '', $sql);
4587 $dao = CRM_Core_DAO
::executeQuery($sql);
4589 $contact_ids = array();
4590 // Add resulting contacts to group
4591 while ($dao->fetch()) {
4592 if ($dao->addtogroup_contact_id
) {
4593 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4597 if (!empty($contact_ids)) {
4598 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4599 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4602 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4608 * Show charts on print screen.
4610 public static function uploadChartImage() {
4611 // upload strictly for '.png' images
4612 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4613 if (preg_match('/\.png$/', $name)) {
4615 // Get the RAW .png from the input.
4616 $httpRawPostData = file_get_contents("php://input");
4618 // prepare the directory
4619 $config = CRM_Core_Config
::singleton();
4621 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4623 if (!file_exists($defaultPath)) {
4624 mkdir($defaultPath, 0777, TRUE);
4627 // full path to the saved image including filename
4628 $destination = $defaultPath . $name;
4631 $jfh = fopen($destination, 'w') or die("can't open file");
4632 fwrite($jfh, $httpRawPostData);
4634 CRM_Utils_System
::civiExit();
4639 * Apply common settings to entityRef fields.
4641 * @param array $field
4642 * @param string $table
4644 private function setEntityRefDefaults(&$field, $table) {
4645 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4646 $field['attributes'] +
= array(
4647 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4649 'placeholder' => ts('- select -'),
4654 * Add link fields to the row.
4656 * Function adds the _link & _hover fields to the row.
4659 * @param string $baseUrl
4660 * @param string $linkText
4661 * @param string $value
4662 * @param string $fieldName
4663 * @param string $tablePrefix
4664 * @param string $fieldLabel
4668 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4669 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4670 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4671 "reset=1&force=1&{$criteriaQueryParams}&" .
4672 $fieldName . "_op=in&{$fieldName}_value={$value}",
4673 $this->_absoluteUrl
, $this->_id
4675 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4676 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4677 array(1 => $linkText, 2 => $fieldLabel)
4682 * Generate temporary table to hold all contributions with permissioned FTs.
4684 * @param object $query
4685 * @param string $alias
4686 * @param bool $return
4688 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4689 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4692 $financialTypes = NULL;
4693 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4694 if (empty($financialTypes)) {
4696 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4699 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4701 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4703 $query->_aliases
['civicrm_line_item'] = $alias;
4706 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4708 if (empty($query->_where
)) {
4709 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4711 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4712 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4713 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4714 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4715 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4716 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4718 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4719 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4720 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4721 CRM_Core_DAO
::executeQuery($sql);
4723 $query->_aliases
['civicrm_line_item'] = $temp;
4725 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4729 $query->_from
.= $from;
4733 * Get label for show results buttons.
4737 public function getResultsLabel() {
4738 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4739 return $showResultsLabel;
4743 * Determine the output mode from the url or input.
4746 * - pdf : Render as pdf
4747 * - csv : Render as csv
4748 * - print : Render in print format
4749 * - save : save the report and display the new report
4750 * - copy : save the report as a new instance and display that.
4751 * - group : go to the add to group screen.
4753 * Potentially chart variations could also be included but the complexity
4754 * is that we might print a bar chart as a pdf.
4756 protected function setOutputMode() {
4757 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4760 CRM_Core_DAO
::$_nullObject,
4762 CRM_Utils_Array
::value('task', $this->_params
)
4764 // if contacts are added to group
4765 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4766 $this->_outputMode
= 'group';
4768 if (isset($this->_params
['task'])) {
4769 unset($this->_params
['task']);
4774 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4777 * @param $columnName
4779 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4780 // add new column with date value for the datetime field
4781 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4782 CRM_Core_DAO
::executeQuery($tempQuery);
4783 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4784 CRM_Core_DAO
::executeQuery($updateQuery);
4785 $this->_selectClauses
[] = "{$columnName}_date";
4786 $this->_select
.= ", {$columnName}_date";
4787 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4788 unset($this->_sections
["{$columnName}"]);
4789 $this->assign('sections', $this->_sections
);
4793 * Get an array of the columns that have been selected for display.
4797 public function getSelectColumns() {
4798 $selectColumns = array();
4799 foreach ($this->_columns
as $tableName => $table) {
4800 if (array_key_exists('fields', $table)) {
4801 foreach ($table['fields'] as $fieldName => $field) {
4802 if (!empty($field['required']) ||
4803 !empty($this->_params
['fields'][$fieldName])
4806 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4811 return $selectColumns;
4815 * Add location tables to the query if they are used for filtering.
4817 * This is for when we are running the query separately for filtering and retrieving display fields.
4819 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4820 if ($this->isTableFiltered('civicrm_email')) {
4822 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4823 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4824 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4826 if ($this->isTableFiltered('civicrm_phone')) {
4828 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4829 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4830 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4832 if ($this->isTableFiltered('civicrm_address')) {
4834 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4835 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4836 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4841 * Set the base table for the FROM clause.
4843 * Sets up the from clause, allowing for the possibility it might be a
4844 * temp table pre-filtered by groups if a group filter is in use.
4846 * @param string $baseTable
4847 * @param string $field
4848 * @param null $tableAlias
4850 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4852 $tableAlias = $this->_aliases
[$baseTable];
4854 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4855 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4856 $this->_from
.= " {$this->_aclFrom} ";
4860 * Join the temp table contacting contacts who are members of the filtered groups.
4862 * If we are using an IN filter we use an inner join, otherwise a left join.
4864 * @param string $baseTable
4865 * @param string $field
4866 * @param string $tableAlias
4868 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4869 if ($this->groupTempTable
) {
4870 if ($this->_params
['gid_op'] == 'in') {
4871 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4872 ON group_temp_table.id = $tableAlias.{$field} ";
4876 LEFT JOIN $this->groupTempTable group_temp_table
4877 ON $tableAlias.{$field} = group_temp_table.id ";