3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 public $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
156 * Has the report been optimised for group filtering.
158 * The functionality for group filtering has been improved but not
159 * all reports have been adjusted to take care of it.
161 * This property exists to highlight the reports which are still using the
162 * slow method & allow group filtering to still work for them until they
165 * In order to protect extensions we have to default to TRUE - but I have
166 * separately marked every class with a groupFilter in the hope that will trigger
167 * people to fix them as they touch them.
173 protected $groupFilterNotOptimised = TRUE;
180 public $_navigation = array();
182 public $_drilldownReport = array();
185 * Array of tabs to display on report.
187 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
189 * $this->tabs['OrderBy'] = array(
190 * 'title' => ts('Sorting'),
191 * 'tpl' => 'OrderBy',
192 * 'div_label' => 'order-by',
197 protected $tabs = array();
200 * Should we add paging.
204 protected $addPaging = TRUE;
207 * An attribute for checkbox/radio form field layout
211 protected $_fourColumnAttribute = array(
212 '</td><td width="25%">',
213 '</td><td width="25%">',
214 '</td><td width="25%">',
218 protected $_force = 1;
220 protected $_params = NULL;
221 protected $_formValues = NULL;
222 protected $_instanceValues = NULL;
224 protected $_instanceForm = FALSE;
225 protected $_criteriaForm = FALSE;
227 protected $_instanceButtonName = NULL;
228 protected $_createNewButtonName = NULL;
229 protected $_printButtonName = NULL;
230 protected $_pdfButtonName = NULL;
231 protected $_csvButtonName = NULL;
232 protected $_groupButtonName = NULL;
233 protected $_chartButtonName = NULL;
234 protected $_csvSupported = TRUE;
235 protected $_add2groupSupported = TRUE;
236 protected $_groups = NULL;
237 protected $_grandFlag = FALSE;
238 protected $_rowsFound = NULL;
239 protected $_selectAliases = array();
240 protected $_rollup = NULL;
243 * Table containing list of contact IDs within the group filter.
247 protected $groupTempTable = '';
252 protected $_aliases = array();
268 protected $_limit = NULL;
271 * This can be set to specify a limit to the number of rows
272 * Since it is currently envisaged as part of the api usage it is only being applied
273 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
274 * of the code (see limit() fn.
278 protected $_limitValue = NULL;
281 * This can be set to specify row offset
282 * See notes on _limitValue
285 protected $_offsetValue = NULL;
289 protected $_sections = NULL;
290 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
291 protected $_absoluteUrl = FALSE;
294 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
298 protected $_storeResultSet = FALSE;
301 * When _storeResultSet Flag is set use this var to store result set in form of array
305 protected $_resultSet = array();
308 * To what frequency group-by a date column
312 protected $_groupByDateFreq = array(
314 'YEARWEEK' => 'Week',
315 'QUARTER' => 'Quarter',
320 * Variables to hold the acl inner join and where clause
322 protected $_aclFrom = NULL;
323 protected $_aclWhere = NULL;
326 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
328 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
332 protected $_selectedTables = array();
335 * Array of DAO tables having columns included in WHERE or HAVING clause
339 protected $filteredTables;
342 * Output mode e.g 'print', 'csv', 'pdf'.
346 protected $_outputMode;
349 * Format of any chart in use.
351 * (it's unclear if this could be merged with outputMode at this stage)
357 public $_having = NULL;
358 public $_select = NULL;
359 public $_selectClauses = array();
360 public $_columnHeaders = array();
361 public $_orderBy = NULL;
362 public $_orderByFields = array();
363 public $_orderByArray = array();
365 * Array of clauses to group by.
369 protected $_groupByArray = array();
370 public $_groupBy = NULL;
371 public $_whereClauses = array();
372 public $_havingClauses = array();
375 * DashBoardRowCount Dashboard row count
378 public $_dashBoardRowCount;
381 * Is this being called without a form controller (ie. the report is being render outside the normal form
382 * - e.g the api is retrieving the rows
385 public $noController = FALSE;
388 * Variable to hold the currency alias
390 protected $_currencyColumn = NULL;
395 protected $_interval;
400 protected $_sendmail;
413 * @var string Report description.
415 public $_description;
418 * @var bool Is an address field selected.
419 * This was intended to determine if the address table should be joined in
420 * The isTableSelected function is now preferred for this purpose
422 protected $_addressField;
425 * @var bool Is an email field selected.
426 * This was intended to determine if the email table should be joined in
427 * The isTableSelected function is now preferred for this purpose
429 protected $_emailField;
432 * @var bool Is a phone field selected.
433 * This was intended to determine if the phone table should be joined in
434 * The isTableSelected function is now preferred for this purpose
436 protected $_phoneField;
439 * @var bool Create new report instance? (or update existing) on save.
441 protected $_createNew;
444 * When a grand total row has calculated the status we pop it off to here.
446 * This allows us to access it from the stats function and avoid recalculating.
448 protected $rollupRow = array();
451 * @var string Database attributes - character set and collation
453 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
456 * SQL being run in this report.
458 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
466 * SQL being run in this report as an array.
468 * The sql in the report is stored in this variable in order to be returned to api & test calls.
477 public function __construct() {
478 parent
::__construct();
480 $this->addClass('crm-report-form');
482 if ($this->_tagFilter
) {
483 $this->buildTagFilter();
485 if ($this->_exposeContactID
) {
486 if (array_key_exists('civicrm_contact', $this->_columns
)) {
487 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
489 'title' => ts('Contact ID'),
495 if ($this->_groupFilter
) {
496 $this->buildGroupFilter();
499 // Get all custom groups
500 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
502 // Get the custom groupIds for which the user has VIEW permission
503 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
504 // and addCustomDataToColumns() will allow access to all custom groups.
505 $permCustomGroupIds = array();
506 if (!CRM_Core_Permission
::check('access all custom data')) {
507 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
508 // do not allow custom data for reports if user doesn't have
509 // permission to access custom data.
510 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
511 $this->_customGroupExtends
= array();
515 // merge custom data columns to _columns list, if any
516 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
518 // add / modify display columns, filters ..etc
519 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
521 //assign currencyColumn variable to tpl
522 $this->assign('currencyColumn', $this->_currencyColumn
);
526 * Shared pre-process function.
528 * If overriding preProcess function this should still be called.
532 public function preProcessCommon() {
533 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean');
535 $this->_dashBoardRowCount
= CRM_Utils_Request
::retrieve('rowCount', 'Integer');
537 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer');
539 $this->assign('section', $this->_section
);
540 CRM_Core_Region
::instance('page-header')->add(array(
541 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
543 if (!$this->noController
) {
544 $this->setID($this->get('instanceId'));
547 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
549 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
553 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
554 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
555 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
559 $this->assign('instanceId', $this->_id
);
560 $params = array('id' => $this->_id
);
561 $this->_instanceValues
= array();
562 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
564 $this->_instanceValues
566 if (empty($this->_instanceValues
)) {
567 CRM_Core_Error
::fatal("Report could not be loaded.");
569 $this->_title
= $this->_instanceValues
['title'];
570 if (!empty($this->_instanceValues
['permission']) &&
571 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
572 CRM_Core_Permission
::check('administer Reports')
575 CRM_Utils_System
::permissionDenied();
576 CRM_Utils_System
::civiExit();
579 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
581 $this->_formValues
= unserialize($formValues);
584 $this->_formValues
= NULL;
587 $this->setOutputMode();
589 if ($this->_outputMode
== 'copy') {
590 $this->_createNew
= TRUE;
591 $this->_params
= $this->_formValues
;
592 $this->_params
['view_mode'] = 'criteria';
593 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
594 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
595 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
597 // Do not pass go. Do not collect another chance to re-run the same query.
598 CRM_Report_Form_Instance
::postProcess($this);
601 // lets always do a force if reset is found in the url.
602 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
603 // in the comment line above these 2.
604 if (!empty($_REQUEST['reset'])
605 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
610 $this->assign('mode', 'instance');
612 elseif (!$this->noController
) {
613 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
614 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
615 if (($instanceCount > 0) && $optionValueID) {
616 $this->assign('instanceUrl',
617 CRM_Utils_System
::url('civicrm/report/list',
618 "reset=1&ovid=$optionValueID"
622 if ($optionValueID) {
623 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
627 $this->assign('mode', 'template');
630 // lets display the Report Settings section
631 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
633 // Do not display Report Settings section if administer Reports permission is absent OR
634 // if report instance is reserved and administer reserved reports absent
635 if (!CRM_Core_Permission
::check('administer Reports') ||
636 ($this->_instanceValues
['is_reserved'] &&
637 !CRM_Core_Permission
::check('administer reserved reports'))
639 $this->_instanceForm
= FALSE;
642 $this->assign('criteriaForm', FALSE);
643 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
644 if (CRM_Core_Permission
::check('administer Reports') ||
645 CRM_Core_Permission
::check('access Report Criteria')
647 if (!$this->_instanceValues
['is_reserved'] ||
648 CRM_Core_Permission
::check('administer reserved reports')
650 $this->assign('criteriaForm', TRUE);
651 $this->_criteriaForm
= TRUE;
655 // Special permissions check for private instance if it's not the current contact instance
657 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
658 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
659 if (!CRM_Core_Permission
::check('access all private reports')) {
660 $this->_instanceForm
= FALSE;
661 $this->assign('criteriaForm', FALSE);
665 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
666 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
667 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
668 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
674 public function addBreadCrumb() {
678 'title' => ts('Report Templates'),
679 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
683 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
687 * Pre process function.
689 * Called prior to build form.
691 public function preProcess() {
692 $this->preProcessCommon();
695 $this->addBreadCrumb();
698 foreach ($this->_columns
as $tableName => $table) {
699 $this->setTableAlias($table, $tableName);
701 $expFields = array();
702 // higher preference to bao object
703 $daoOrBaoName = CRM_Utils_Array
::value('bao', $table, CRM_Utils_Array
::value('dao', $table));
706 if (method_exists($daoOrBaoName, 'exportableFields')) {
707 $expFields = $daoOrBaoName::exportableFields();
710 $expFields = $daoOrBaoName::export();
714 $doNotCopy = array('required', 'default');
716 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
717 foreach ($fieldGroups as $fieldGrp) {
718 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
719 foreach ($table[$fieldGrp] as $fieldName => $field) {
720 // $name is the field name used to reference the BAO/DAO export fields array
721 $name = isset($field['name']) ?
$field['name'] : $fieldName;
723 // Sometimes the field name key in the BAO/DAO export fields array is
724 // different from the actual database field name.
725 // Unset $field['name'] so that actual database field name can be obtained
726 // from the BAO/DAO export fields array.
727 unset($field['name']);
729 if (array_key_exists($name, $expFields)) {
730 foreach ($doNotCopy as $dnc) {
731 // unset the values we don't want to be copied.
732 unset($expFields[$name][$dnc]);
735 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
738 foreach ($expFields[$name] as $property => $val) {
739 if (!array_key_exists($property, $field)) {
740 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
747 if (!empty($field['no_repeat'])) {
748 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
750 if (!empty($field['no_display'])) {
751 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
754 // set alias = table-name, unless already set
755 $alias = isset($field['alias']) ?
$field['alias'] : (
756 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
758 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
760 // set name = fieldName, unless already set
761 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
762 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
765 // set dbAlias = alias.name, unless already set
766 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
767 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
769 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
772 // a few auto fills for filters
773 if ($fieldGrp == 'filters') {
774 // fill operator types
775 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
776 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
777 case CRM_Utils_Type
::T_MONEY
:
778 case CRM_Utils_Type
::T_FLOAT
:
779 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
782 case CRM_Utils_Type
::T_INT
:
783 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
786 case CRM_Utils_Type
::T_DATE
:
787 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
790 case CRM_Utils_Type
::T_BOOLEAN
:
791 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
792 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
793 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
804 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
806 // with multiple options operator-type is generally multi-select
807 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
808 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
810 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
821 // copy filters to a separate handy variable
822 if (array_key_exists('filters', $table)) {
823 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
826 if (array_key_exists('group_bys', $table)) {
827 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
830 if (array_key_exists('fields', $table)) {
831 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
836 $this->setDefaultValues(FALSE);
839 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
840 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
841 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
842 CRM_Report_Utils_Get
::processChart($this->_defaults
);
845 $this->_formValues
= $this->_defaults
;
846 $this->postProcess();
851 * Set default values.
853 * @param bool $freeze
857 public function setDefaultValues($freeze = TRUE) {
858 $freezeGroup = array();
860 // FIXME: generalizing form field naming conventions would reduce
861 // Lots of lines below.
862 foreach ($this->_columns
as $tableName => $table) {
863 if (array_key_exists('fields', $table)) {
864 foreach ($table['fields'] as $fieldName => $field) {
865 if (empty($field['no_display'])) {
866 if (isset($field['required'])) {
868 $this->_defaults
['fields'][$fieldName] = 1;
871 // find element object, so that we could use quickform's freeze method
872 // for required elements
873 $obj = $this->getElementFromGroup("fields", $fieldName);
875 $freezeGroup[] = $obj;
879 elseif (isset($field['default'])) {
880 $this->_defaults
['fields'][$fieldName] = $field['default'];
886 if (array_key_exists('group_bys', $table)) {
887 foreach ($table['group_bys'] as $fieldName => $field) {
888 if (isset($field['default'])) {
889 if (!empty($field['frequency'])) {
890 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
892 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
896 if (array_key_exists('filters', $table)) {
897 foreach ($table['filters'] as $fieldName => $field) {
898 if (isset($field['default'])) {
899 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
901 if (is_array($field['default'])) {
902 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
903 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
904 $this->_defaults
["{$fieldName}_relative"] = 0;
907 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
911 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
912 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
913 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
915 $this->_defaults
["{$fieldName}_value"] = $field['default'];
918 //assign default value as "in" for multiselect
919 //operator, To freeze the select element
920 if (CRM_Utils_Array
::value('operatorType', $field) ==
921 CRM_Report_Form
::OP_MULTISELECT
923 $this->_defaults
["{$fieldName}_op"] = 'in';
925 if (CRM_Utils_Array
::value('operatorType', $field) ==
926 CRM_Report_Form
::OP_ENTITYREF
928 $this->_defaults
["{$fieldName}_op"] = 'in';
930 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
931 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
933 $this->_defaults
["{$fieldName}_op"] = 'mhas';
935 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
936 $this->_defaults
["{$fieldName}_op"] = $op;
942 empty($this->_formValues
['order_bys']) &&
943 (array_key_exists('order_bys', $table) &&
944 is_array($table['order_bys']))
946 if (!array_key_exists('order_bys', $this->_defaults
)) {
947 $this->_defaults
['order_bys'] = array();
949 foreach ($table['order_bys'] as $fieldName => $field) {
950 if (!empty($field['default']) ||
!empty($field['default_order']) ||
951 CRM_Utils_Array
::value('default_is_section', $field) ||
952 !empty($field['default_weight'])
955 'column' => $fieldName,
956 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
957 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
960 if (!empty($field['default_weight'])) {
961 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
964 array_unshift($this->_defaults
['order_bys'], $order_by);
970 foreach ($this->_options
as $fieldName => $field) {
971 if (isset($field['default'])) {
972 $this->_defaults
['options'][$fieldName] = $field['default'];
977 if (!empty($this->_submitValues
)) {
978 $this->preProcessOrderBy($this->_submitValues
);
981 $this->preProcessOrderBy($this->_defaults
);
984 // lets finish freezing task here itself
985 if (!empty($freezeGroup)) {
986 foreach ($freezeGroup as $elem) {
991 if ($this->_formValues
) {
992 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
995 if ($this->_instanceValues
) {
996 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
999 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1001 return $this->_defaults
;
1005 * Get element from group.
1007 * @param string $group
1008 * @param string $grpFieldName
1012 public function getElementFromGroup($group, $grpFieldName) {
1013 $eleObj = $this->getElement($group);
1014 foreach ($eleObj->_elements
as $index => $obj) {
1015 if ($grpFieldName == $obj->_attributes
['name']) {
1023 * Setter for $_params.
1025 * @param array $params
1027 public function setParams($params) {
1028 $this->_params
= $params;
1034 * @param int $instanceID
1036 public function setID($instanceID) {
1037 $this->_id
= $instanceID;
1041 * Setter for $_force.
1043 * @param bool $isForce
1045 public function setForce($isForce) {
1046 $this->_force
= $isForce;
1050 * Setter for $_limitValue.
1052 * @param int $_limitValue
1054 public function setLimitValue($_limitValue) {
1055 $this->_limitValue
= $_limitValue;
1059 * Setter for $_offsetValue.
1061 * @param int $_offsetValue
1063 public function setOffsetValue($_offsetValue) {
1064 $this->_offsetValue
= $_offsetValue;
1068 * Setter for $addPaging.
1070 * @param bool $value
1072 public function setAddPaging($value) {
1073 $this->addPaging
= $value;
1077 * Getter for $_defaultValues.
1081 public function getDefaultValues() {
1082 return $this->_defaults
;
1086 * Add columns to report.
1088 public function addColumns() {
1091 foreach ($this->_columns
as $tableName => $table) {
1092 if (array_key_exists('fields', $table)) {
1093 foreach ($table['fields'] as $fieldName => $field) {
1095 if (empty($field['no_display'])) {
1096 foreach (array('table', 'field') as $var) {
1097 if (!empty($
{$var}['grouping'])) {
1098 if (!is_array($
{$var}['grouping'])) {
1099 $tableName = $
{$var}['grouping'];
1102 $tableName = array_keys($
{$var}['grouping']);
1103 $tableName = $tableName[0];
1104 $groupTitle = array_values($
{$var}['grouping']);
1105 $groupTitle = $groupTitle[0];
1110 if (!$groupTitle && isset($table['group_title'])) {
1111 $groupTitle = $table['group_title'];
1112 // Having a group_title is secret code for being a custom group
1113 // which cryptically translates to needing an accordion.
1114 // here we make that explicit.
1115 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1118 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1119 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1120 $colGroups[$tableName]['group_title'] = $groupTitle;
1122 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1128 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1129 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1131 if (!empty($colGroups)) {
1132 $this->tabs
['FieldSelection'] = array(
1133 'title' => ts('Columns'),
1134 'tpl' => 'FieldSelection',
1135 'div_label' => 'col-groups',
1138 // Note this assignment is only really required in buildForm. It is being 'over-called'
1139 // to reduce risk of being missed due to overridden functions.
1140 $this->assign('tabs', $this->tabs
);
1143 $this->assign('colGroups', $colGroups);
1147 * Add filters to report.
1149 public function addFilters() {
1150 $filters = $filterGroups = array();
1153 foreach ($this->_filters
as $table => $attributes) {
1154 if (isset($this->_columns
[$table]['group_title'])) {
1155 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1156 // which magically means to 'display in an accordian'
1157 // here we make this explicit.
1158 $filterGroups[$table] = array(
1159 'group_title' => $this->_columns
[$table]['group_title'],
1160 'use_accordian_for_field_selection' => TRUE,
1164 foreach ($attributes as $fieldName => $field) {
1165 // get ready with option value pair
1166 // @ 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
1168 $operations = $this->getOperationPair(
1169 CRM_Utils_Array
::value('operatorType', $field),
1172 $filters[$table][$fieldName] = $field;
1174 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1175 case CRM_Report_Form
::OP_MONTH
:
1176 if (!array_key_exists('options', $field) ||
1177 !is_array($field['options']) ||
empty($field['options'])
1179 // If there's no option list for this filter, define one.
1180 $field['options'] = array(
1182 2 => ts('February'),
1189 9 => ts('September'),
1190 10 => ts('October'),
1191 11 => ts('November'),
1192 12 => ts('December'),
1194 // Add this option list to this column _columns. This is
1195 // required so that filter statistics show properly.
1196 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1198 case CRM_Report_Form
::OP_MULTISELECT
:
1199 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1200 // assume a multi-select field
1201 if (!empty($field['options']) ||
1202 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1204 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1205 if (count($operations) <= 1) {
1208 if ($fieldName == 'state_province_id' ||
1209 $fieldName == 'county_id'
1211 $this->addChainSelect($fieldName . '_value', array(
1218 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1219 'style' => 'min-width:250px',
1220 'class' => 'crm-select2 huge',
1222 'placeholder' => ts('- select -'),
1228 case CRM_Report_Form
::OP_SELECT
:
1229 // assume a select field
1230 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1231 if (!empty($field['options'])) {
1232 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1236 case CRM_Report_Form
::OP_ENTITYREF
:
1237 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1238 $this->setEntityRefDefaults($field, $table);
1239 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1242 case CRM_Report_Form
::OP_DATE
:
1243 // build datetime fields
1244 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1248 case CRM_Report_Form
::OP_DATETIME
:
1249 // build datetime fields
1250 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1254 case CRM_Report_Form
::OP_INT
:
1255 case CRM_Report_Form
::OP_FLOAT
:
1256 // and a min value input box
1257 $this->add('text', "{$fieldName}_min", ts('Min'));
1258 // and a max value input box
1259 $this->add('text', "{$fieldName}_max", ts('Max'));
1261 // default type is string
1262 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1263 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1265 // we need text box for value input
1266 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1271 if (!empty($filters)) {
1272 $this->tabs
['Filters'] = array(
1273 'title' => ts('Filters'),
1275 'div_label' => 'set-filters',
1278 $this->assign('filters', $filters);
1279 $this->assign('filterGroups', $filterGroups);
1283 * Function to assign the tabs to the template in the correct order.
1285 * We want the tabs to wind up in this order (if not overridden).
1293 protected function assignTabs() {
1301 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1302 $order = array_merge($order, $this->tabs
);
1303 $this->assign('tabs', $order);
1307 * The intent is to add a tab for developers to view the sql.
1309 * Currently using dpm.
1311 * @param string $sql
1313 protected function addToDeveloperTab($sql) {
1314 if (!CRM_Core_Permission
::check('view report sql')) {
1317 $this->tabs
['Developer'] = array(
1318 'title' => ts('Developer'),
1319 'tpl' => 'Developer',
1320 'div_label' => 'set-developer',
1323 $this->assignTabs();
1324 $this->sqlArray
[] = $sql;
1325 foreach ($this->sqlArray
as $sql) {
1326 foreach (array('LEFT JOIN') as $term) {
1327 $sql = str_replace($term, '<br>  ' . $term, $sql);
1329 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1330 $sql = str_replace($term, '<br><br>' . $term, $sql);
1332 $this->sqlFormattedArray
[] = $sql;
1333 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1338 * Add options defined in $this->_options to the report.
1340 public function addOptions() {
1341 if (!empty($this->_options
)) {
1342 // FIXME: For now lets build all elements as checkboxes.
1343 // Once we clear with the format we can build elements based on type
1345 foreach ($this->_options
as $fieldName => $field) {
1348 if ($field['type'] == 'select') {
1349 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1351 elseif ($field['type'] == 'checkbox') {
1352 $options[$field['title']] = $fieldName;
1353 $this->addCheckBox($fieldName, NULL,
1355 NULL, NULL, NULL, $this->_fourColumnAttribute
1360 if (!empty($this->_options
) &&
1362 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1364 $this->tabs
['ReportOptions'] = array(
1365 'title' => ts('Display Options'),
1366 'tpl' => 'ReportOptions',
1367 'div_label' => 'other-options',
1370 $this->assign('otherOptions', $this->_options
);
1374 * Add chart options to the report.
1376 public function addChartOptions() {
1377 if (!empty($this->_charts
)) {
1378 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1379 $this->assign('charts', $this->_charts
);
1380 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1385 * Add group by options to the report.
1387 public function addGroupBys() {
1388 $options = $freqElements = array();
1390 foreach ($this->_columns
as $tableName => $table) {
1391 if (array_key_exists('group_bys', $table)) {
1392 foreach ($table['group_bys'] as $fieldName => $field) {
1393 if (!empty($field)) {
1394 $options[$field['title']] = $fieldName;
1395 if (!empty($field['frequency'])) {
1396 $freqElements[$field['title']] = $fieldName;
1402 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1403 NULL, NULL, NULL, $this->_fourColumnAttribute
1405 $this->assign('groupByElements', $options);
1406 if (!empty($options)) {
1407 $this->tabs
['GroupBy'] = array(
1408 'title' => ts('Grouping'),
1410 'div_label' => 'group-by-elements',
1414 foreach ($freqElements as $name) {
1415 $this->addElement('select', "group_bys_freq[$name]",
1416 ts('Frequency'), $this->_groupByDateFreq
1422 * Add data for order by tab.
1424 public function addOrderBys() {
1426 foreach ($this->_columns
as $tableName => $table) {
1428 // Report developer may define any column to order by; include these as order-by options.
1429 if (array_key_exists('order_bys', $table)) {
1430 foreach ($table['order_bys'] as $fieldName => $field) {
1431 if (!empty($field)) {
1432 $options[$fieldName] = $field['title'];
1437 // Add searchable custom fields as order-by options, if so requested
1438 // (These are already indexed, so allowing to order on them is cheap.)
1440 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1441 array_key_exists('extends', $table) && !empty($table['extends'])
1443 foreach ($table['fields'] as $fieldName => $field) {
1444 if (empty($field['no_display'])) {
1445 $options[$fieldName] = $field['title'];
1453 $this->assign('orderByOptions', $options);
1454 if (!empty($options)) {
1455 $this->tabs
['OrderBy'] = array(
1456 'title' => ts('Sorting'),
1458 'div_label' => 'order-by-elements',
1462 if (!empty($options)) {
1464 '-' => ' - none - ',
1466 for ($i = 1; $i <= 5; $i++
) {
1467 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1468 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1469 'ASC' => ts('Ascending'),
1470 'DESC' => ts('Descending'),
1472 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1473 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1479 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1481 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1482 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1485 public function buildInstanceAndButtons() {
1486 CRM_Report_Form_Instance
::buildForm($this);
1487 $this->_actionButtonName
= $this->getButtonName('submit');
1488 $this->addTaskMenu($this->getActions($this->_id
));
1490 $this->assign('instanceForm', $this->_instanceForm
);
1492 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1493 $permission = CRM_Core_Permission
::getPermission();
1494 if ($permission == CRM_Core_Permission
::EDIT
&&
1495 $this->_add2groupSupported
1497 $this->addElement('select', 'groups', ts('Group'),
1498 array('' => ts('Add Contacts to Group')) +
1499 CRM_Core_PseudoConstant
::nestedGroup(),
1500 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1502 $this->assign('group', TRUE);
1505 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1507 $this->addChartOptions();
1508 $showResultsLabel = $this->getResultsLabel();
1509 $this->addButtons(array(
1512 'name' => $showResultsLabel,
1513 'isDefault' => TRUE,
1520 * Has this form been submitted already?
1524 public function resultsDisplayed() {
1525 $buttonName = $this->controller
->getButtonName();
1526 return ($buttonName ||
$this->_outputMode
);
1530 * Get the actions for this report instance.
1532 * @param int $instanceId
1536 protected function getActions($instanceId) {
1537 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1538 if (empty($instanceId)) {
1539 $actions['report_instance.save'] = array(
1540 'title' => ts('Create Report'),
1542 'is_confirm' => TRUE,
1543 'confirm_title' => ts('Create Report'),
1544 'confirm_refresh_fields' => json_encode(array(
1545 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1546 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1552 if (!$this->_csvSupported
) {
1553 unset($actions['report_instance.csv']);
1560 * Main build form function.
1562 public function buildQuickForm() {
1563 $this->addColumns();
1565 $this->addFilters();
1567 $this->addOptions();
1569 $this->addGroupBys();
1571 $this->addOrderBys();
1573 $this->buildInstanceAndButtons();
1575 // Add form rule for report.
1576 if (is_callable(array(
1580 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1582 $this->assignTabs();
1586 * A form rule function for custom data.
1588 * The rule ensures that fields selected in group_by if any) should only be the ones
1589 * present in display/select fields criteria;
1590 * note: works if and only if any custom field selected in group_by.
1592 * @param array $fields
1593 * @param array $ignoreFields
1597 public function customDataFormRule($fields, $ignoreFields = array()) {
1599 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1600 !empty($fields['group_bys'])
1602 foreach ($this->_columns
as $tableName => $table) {
1603 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1604 substr($tableName, 0, 12) == 'custom_value') &&
1605 !empty($this->_columns
[$tableName]['fields'])
1607 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1608 if (array_key_exists($fieldName, $fields['group_bys']) &&
1609 !array_key_exists($fieldName, $fields['fields'])
1611 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1613 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1614 foreach ($fields['fields'] as $fld => $val) {
1615 if (!array_key_exists($fld, $fields['group_bys']) &&
1616 !in_array($fld, $ignoreFields)
1618 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1630 * Get operators to display on form.
1632 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1634 * @param string $type
1635 * @param string $fieldName
1639 public function getOperationPair($type = "string", $fieldName = NULL) {
1640 // FIXME: At some point we should move these key-val pairs
1641 // to option_group and option_value table.
1643 case CRM_Report_Form
::OP_INT
:
1644 case CRM_Report_Form
::OP_FLOAT
:
1647 'lte' => ts('Is less than or equal to'),
1648 'gte' => ts('Is greater than or equal to'),
1649 'bw' => ts('Is between'),
1650 'eq' => ts('Is equal to'),
1651 'lt' => ts('Is less than'),
1652 'gt' => ts('Is greater than'),
1653 'neq' => ts('Is not equal to'),
1654 'nbw' => ts('Is not between'),
1655 'nll' => ts('Is empty (Null)'),
1656 'nnll' => ts('Is not empty (Null)'),
1660 case CRM_Report_Form
::OP_SELECT
:
1662 'eq' => ts('Is equal to'),
1666 case CRM_Report_Form
::OP_MONTH
:
1667 case CRM_Report_Form
::OP_MULTISELECT
:
1668 case CRM_Report_Form
::OP_ENTITYREF
:
1671 'in' => ts('Is one of'),
1672 'notin' => ts('Is not one of'),
1676 case CRM_Report_Form
::OP_DATE
:
1679 'nll' => ts('Is empty (Null)'),
1680 'nnll' => ts('Is not empty (Null)'),
1684 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1685 // use this operator for the values, concatenated with separator. For e.g if
1686 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1688 'mhas' => ts('Is one of'),
1689 'mnot' => ts('Is not one of'),
1696 'has' => ts('Contains'),
1697 'sw' => ts('Starts with'),
1698 'ew' => ts('Ends with'),
1699 'nhas' => ts('Does not contain'),
1700 'eq' => ts('Is equal to'),
1701 'neq' => ts('Is not equal to'),
1702 'nll' => ts('Is empty (Null)'),
1703 'nnll' => ts('Is not empty (Null)'),
1710 * Build the tag filter field to display on the filters tab.
1712 public function buildTagFilter() {
1713 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1714 if (!empty($contactTags)) {
1715 $this->_columns
['civicrm_tag'] = array(
1716 'dao' => 'CRM_Core_DAO_Tag',
1720 'title' => ts('Tag'),
1721 'type' => CRM_Utils_Type
::T_INT
,
1723 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1724 'options' => $contactTags,
1732 * Adds group filters to _columns (called from _Construct).
1734 public function buildGroupFilter() {
1735 $this->_columns
['civicrm_group']['filters'] = array(
1737 'name' => 'group_id',
1738 'title' => ts('Group'),
1739 'type' => CRM_Utils_Type
::T_INT
,
1740 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1742 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1745 if (empty($this->_columns
['civicrm_group']['dao'])) {
1746 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1748 if (empty($this->_columns
['civicrm_group']['alias'])) {
1749 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1754 * Get SQL operator from form text version.
1756 * @param string $operator
1760 public function getSQLOperator($operator = "like") {
1761 switch ($operator) {
1794 return 'IS NOT NULL';
1803 * Generate where clause.
1805 * This can be overridden in reports for special treatment of a field
1807 * @param array $field Field specifications
1808 * @param string $op Query operator (not an exact match to sql)
1809 * @param mixed $value
1813 * @return null|string
1815 public function whereClause(&$field, $op, $value, $min, $max) {
1817 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1819 // CRM-18010: Ensure type of each report filters
1821 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1828 if (($min !== NULL && strlen($min) > 0) ||
1829 ($max !== NULL && strlen($max) > 0)
1833 $min = CRM_Utils_Type
::escape($min, $type);
1835 $clauses[] = "( {$field['dbAlias']} >= $min )";
1838 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1842 $max = CRM_Utils_Type
::escape($max, $type);
1844 $clauses[] = "( {$field['dbAlias']} <= $max )";
1847 $clauses[] = "( {$field['dbAlias']} > $max )";
1851 if (!empty($clauses)) {
1853 $clause = implode(' AND ', $clauses);
1856 $clause = '(' . implode('OR', $clauses) . ')';
1864 if ($value !== NULL && strlen($value) > 0) {
1865 $value = CRM_Utils_Type
::escape($value, $type);
1866 if (strpos($value, '%') === FALSE) {
1867 $value = "'%{$value}%'";
1870 $value = "'{$value}'";
1872 $sqlOP = $this->getSQLOperator($op);
1873 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1879 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1880 $value = explode(',', $value);
1882 if ($value !== NULL && is_array($value) && count($value) > 0) {
1883 $sqlOP = $this->getSQLOperator($op);
1884 if (CRM_Utils_Array
::value('type', $field) ==
1885 CRM_Utils_Type
::T_STRING
1887 //cycle through selections and escape values
1888 foreach ($value as $key => $selection) {
1889 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1892 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1896 // for numerical values
1897 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1900 if ($op == 'notin') {
1901 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1904 $clause = "( " . $clause . " )";
1911 // multiple has or multiple not
1912 if ($value !== NULL && count($value) > 0) {
1913 $value = CRM_Utils_Type
::escapeAll($value, $type);
1914 $operator = $op == 'mnot' ?
'NOT' : '';
1915 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1916 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1922 if ($value !== NULL && strlen($value) > 0) {
1923 $value = CRM_Utils_Type
::escape($value, $type);
1924 if (strpos($value, '%') === FALSE) {
1926 $value = "'{$value}%'";
1929 $value = "'%{$value}'";
1933 $value = "'{$value}'";
1935 $sqlOP = $this->getSQLOperator($op);
1936 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1942 $sqlOP = $this->getSQLOperator($op);
1943 $clause = "( {$field['dbAlias']} $sqlOP )";
1949 //CRM-18457: some custom field passes value in array format against binary operator
1950 if (is_array($value) && count($value)) {
1955 if ($value !== NULL && $value !== '') {
1956 if (isset($field['clause'])) {
1957 // FIXME: we not doing escape here. Better solution is to use two
1958 // different types - data-type and filter-type
1959 $clause = $field['clause'];
1961 elseif (!is_array($value)) {
1962 $value = CRM_Utils_Type
::escape($value, $type);
1963 $sqlOP = $this->getSQLOperator($op);
1964 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1965 $value = "'{$value}'";
1967 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1973 if (!empty($field['group']) && $clause) {
1974 $clause = $this->whereGroupClause($field, $value, $op);
1976 elseif (!empty($field['tag']) && $clause) {
1977 // not using left join in query because if any contact
1978 // belongs to more than one tag, results duplicate
1980 $clause = $this->whereTagClause($field, $value, $op);
1982 elseif (!empty($field['membership_org']) && $clause) {
1983 $clause = $this->whereMembershipOrgClause($value, $op);
1985 elseif (!empty($field['membership_type']) && $clause) {
1986 $clause = $this->whereMembershipTypeClause($value, $op);
1992 * Get SQL where clause for a date field.
1994 * @param string $fieldName
1995 * @param string $relative
1996 * @param string $from
1998 * @param string $type
1999 * @param string $fromTime
2000 * @param string $toTime
2002 * @return null|string
2004 public function dateClause(
2006 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2009 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2010 $sqlOP = $this->getSQLOperator($relative);
2011 return "( {$fieldName} {$sqlOP} )";
2014 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2017 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2018 $clauses[] = "( {$fieldName} >= $from )";
2022 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2023 $clauses[] = "( {$fieldName} <= {$to} )";
2026 if (!empty($clauses)) {
2027 return implode(' AND ', $clauses);
2034 * Get values for from and to for date ranges.
2036 * @param bool $relative
2037 * @param string $from
2039 * @param string $fromTime
2040 * @param string $toTime
2044 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2045 if (empty($toTime)) {
2048 //FIX ME not working for relative
2050 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2051 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2052 $from = substr($dateRange['from'], 0, 8);
2053 //Take only Date Part, Sometime Time part is also present in 'to'
2054 $to = substr($dateRange['to'], 0, 8);
2056 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2057 $to = CRM_Utils_Date
::processDate($to, $toTime);
2058 return array($from, $to);
2062 * Alter display of rows.
2064 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2065 * such as rendering contacts as links.
2067 * @param array $rows
2068 * Rows generated by SQL, with an array for each row.
2070 public function alterDisplay(&$rows) {
2074 * Alter the way in which custom data fields are displayed.
2076 * @param array $rows
2078 public function alterCustomDataDisplay(&$rows) {
2079 // custom code to alter rows having custom values
2080 if (empty($this->_customGroupExtends
)) {
2084 $customFields = array();
2085 $customFieldIds = array();
2086 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2087 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2088 $customFieldIds[$fieldAlias] = $fieldId;
2091 if (empty($customFieldIds)) {
2095 // skip for type date and ContactReference since date format is already handled
2097 SELECT cg.table_name, cf.id
2098 FROM civicrm_custom_field cf
2099 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2100 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2101 cg.is_active = 1 AND
2102 cf.is_active = 1 AND
2103 cf.is_searchable = 1 AND
2104 cf.data_type NOT IN ('ContactReference', 'Date') AND
2105 cf.id IN (" . implode(",", $customFieldIds) . ")";
2107 $dao = CRM_Core_DAO
::executeQuery($query);
2108 while ($dao->fetch()) {
2109 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2113 $entryFound = FALSE;
2114 foreach ($rows as $rowNum => $row) {
2115 foreach ($row as $tableCol => $val) {
2116 if (array_key_exists($tableCol, $customFields)) {
2117 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2122 // skip looking further in rows, if first row itself doesn't
2123 // have the column we need
2131 * Remove duplicate rows.
2133 * @param array $rows
2135 public function removeDuplicates(&$rows) {
2136 if (empty($this->_noRepeats
)) {
2139 $checkList = array();
2141 foreach ($rows as $key => $list) {
2142 foreach ($list as $colName => $colVal) {
2143 if (array_key_exists($colName, $checkList) &&
2144 $checkList[$colName] == $colVal
2146 $rows[$key][$colName] = "";
2148 if (in_array($colName, $this->_noRepeats
)) {
2149 $checkList[$colName] = $colVal;
2156 * Fix subtotal display.
2159 * @param array $fields
2160 * @param bool $subtotal
2162 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2163 foreach ($row as $colName => $colVal) {
2164 if (in_array($colName, $fields)) {
2166 elseif (isset($this->_columnHeaders
[$colName])) {
2168 $row[$colName] = 'Subtotal';
2172 unset($row[$colName]);
2179 * Calculate grant total.
2181 * @param array $rows
2185 public function grandTotal(&$rows) {
2186 if (!$this->_rollup ||
count($rows) == 1) {
2190 $this->moveSummaryColumnsToTheRightHandSide();
2192 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2196 $this->rollupRow
= array_pop($rows);
2198 foreach ($this->_columnHeaders
as $fld => $val) {
2199 if (!in_array($fld, $this->_statFields
)) {
2200 if (!$this->_grandFlag
) {
2201 $this->rollupRow
[$fld] = ts('Grand Total');
2202 $this->_grandFlag
= TRUE;
2205 $this->rollupRow
[$fld] = "";
2210 $this->assign('grandStat', $this->rollupRow
);
2215 * Format display output.
2217 * @param array $rows
2218 * @param bool $pager
2220 public function formatDisplay(&$rows, $pager = TRUE) {
2221 // set pager based on if any limit was applied in the query.
2226 // allow building charts if any
2227 if (!empty($this->_params
['charts']) && !empty($rows)) {
2228 $this->buildChart($rows);
2229 $this->assign('chartEnabled', TRUE);
2230 $this->_chartId
= "{$this->_params['charts']}_" .
2231 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2233 $this->assign('chartId', $this->_chartId
);
2236 // unset columns not to be displayed.
2237 foreach ($this->_columnHeaders
as $key => $value) {
2238 if (!empty($value['no_display'])) {
2239 unset($this->_columnHeaders
[$key]);
2243 // unset columns not to be displayed.
2244 if (!empty($rows)) {
2245 foreach ($this->_noDisplay
as $noDisplayField) {
2246 foreach ($rows as $rowNum => $row) {
2247 unset($this->_columnHeaders
[$noDisplayField]);
2252 // build array of section totals
2253 $this->sectionTotals();
2255 // process grand-total row
2256 $this->grandTotal($rows);
2258 // use this method for formatting rows for display purpose.
2259 $this->alterDisplay($rows);
2260 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2262 // use this method for formatting custom rows for display purpose.
2263 $this->alterCustomDataDisplay($rows);
2269 * @param array $rows
2271 public function buildChart(&$rows) {
2272 // override this method for building charts.
2275 // select() method below has been added recently (v3.3), and many of the report templates might
2276 // still be having their own select() method. We should fix them as and when encountered and move
2277 // towards generalizing the select() method below.
2280 * Generate the SELECT clause and set class variable $_select.
2282 public function select() {
2283 $select = $this->_selectAliases
= array();
2285 foreach ($this->_columns
as $tableName => $table) {
2286 if (array_key_exists('fields', $table)) {
2287 foreach ($table['fields'] as $fieldName => $field) {
2288 if ($tableName == 'civicrm_address') {
2289 // deprecated, use $this->isTableSelected.
2290 $this->_addressField
= TRUE;
2292 if ($tableName == 'civicrm_email') {
2293 $this->_emailField
= TRUE;
2295 if ($tableName == 'civicrm_phone') {
2296 $this->_phoneField
= TRUE;
2299 if (!empty($field['required']) ||
2300 !empty($this->_params
['fields'][$fieldName])
2303 // 1. In many cases we want select clause to be built in slightly different way
2304 // for a particular field of a particular type.
2305 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2307 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2308 if ($selectClause) {
2309 $select[] = $selectClause;
2313 // include statistics columns only if set
2314 if (!empty($field['statistics'])) {
2315 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2318 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2324 // select for group bys
2325 if (array_key_exists('group_bys', $table)) {
2326 foreach ($table['group_bys'] as $fieldName => $field) {
2328 if ($tableName == 'civicrm_address') {
2329 $this->_addressField
= TRUE;
2331 if ($tableName == 'civicrm_email') {
2332 $this->_emailField
= TRUE;
2334 if ($tableName == 'civicrm_phone') {
2335 $this->_phoneField
= TRUE;
2337 // 1. In many cases we want select clause to be built in slightly different way
2338 // for a particular field of a particular type.
2339 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2341 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2342 if ($selectClause) {
2343 $select[] = $selectClause;
2347 if (!empty($this->_params
['group_bys']) &&
2348 !empty($this->_params
['group_bys'][$fieldName]) &&
2349 !empty($this->_params
['group_bys_freq'])
2351 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2353 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2354 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2355 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2356 $field['title'] = 'Week';
2360 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2361 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2362 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2363 $field['title'] = 'Year';
2367 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2368 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2369 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2370 $field['title'] = 'Month';
2374 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2375 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2376 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2377 $field['title'] = 'Quarter';
2380 // for graphs and charts -
2381 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2382 $this->_interval
= $field['title'];
2383 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2384 = $field['title'] . ' Beginning';
2385 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2386 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2388 // just to make sure these values are transferred to rows.
2389 // since we 'll need them for calculation purpose,
2390 // e.g making subtotals look nicer or graphs
2391 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2392 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2399 $this->_selectClauses
= $select;
2400 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2404 * Build select clause for a single field.
2406 * @param string $tableName
2407 * @param string $tableKey
2408 * @param string $fieldName
2409 * @param string $field
2413 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2418 * Build where clause.
2420 public function where() {
2421 $this->storeWhereHavingClauseArray();
2423 if (empty($this->_whereClauses
)) {
2424 $this->_where
= "WHERE ( 1 ) ";
2425 $this->_having
= "";
2428 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2431 if ($this->_aclWhere
) {
2432 $this->_where
.= " AND {$this->_aclWhere} ";
2435 if (!empty($this->_havingClauses
)) {
2436 // use this clause to construct group by clause.
2437 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2442 * Store Where clauses into an array.
2444 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2445 * temp table that may not be part of the final where clause or added
2446 * in other functions
2448 public function storeWhereHavingClauseArray() {
2449 foreach ($this->_columns
as $tableName => $table) {
2450 if (array_key_exists('filters', $table)) {
2451 foreach ($table['filters'] as $fieldName => $field) {
2452 // respect pseudofield to filter spec so fields can be marked as
2453 // not to be handled here
2454 if (!empty($field['pseudofield'])) {
2458 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2459 if (CRM_Utils_Array
::value('operatorType', $field) ==
2460 CRM_Report_Form
::OP_MONTH
2462 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2463 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2464 if (is_array($value) && !empty($value)) {
2466 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2471 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2472 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2473 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2474 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2475 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2476 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2480 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2482 $clause = $this->whereClause($field,
2484 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2485 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2486 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2491 if (!empty($clause)) {
2492 if (!empty($field['having'])) {
2493 $this->_havingClauses
[] = $clause;
2496 $this->_whereClauses
[] = $clause;
2508 public function processReportMode() {
2509 $this->setOutputMode();
2512 = CRM_Utils_Request
::retrieve(
2515 CRM_Core_DAO
::$_nullObject
2518 $this->_absoluteUrl
= FALSE;
2520 $this->assign('printOnly', FALSE);
2522 if ($this->_outputMode
== 'print' ||
2523 ($this->_sendmail
&& !$this->_outputMode
)
2525 $this->assign('printOnly', TRUE);
2527 $this->addPaging
= FALSE;
2528 $this->assign('outputMode', 'print');
2529 $this->_outputMode
= 'print';
2530 if ($this->_sendmail
) {
2531 $this->_absoluteUrl
= TRUE;
2534 elseif ($this->_outputMode
== 'pdf') {
2536 $this->addPaging
= FALSE;
2537 $this->_absoluteUrl
= TRUE;
2539 elseif ($this->_outputMode
== 'csv') {
2541 $this->_absoluteUrl
= TRUE;
2542 $this->addPaging
= FALSE;
2544 elseif ($this->_outputMode
== 'group') {
2545 $this->assign('outputMode', 'group');
2547 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2548 $this->assign('outputMode', 'create_report');
2550 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2551 $this->_createNew
= TRUE;
2554 $this->assign('outputMode', $this->_outputMode
);
2555 $this->assign('printOnly', $printOnly);
2556 // Get today's date to include in printed reports
2558 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2559 $this->assign('reportDate', $reportDate);
2564 * Post Processing function for Form.
2566 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2567 * This function is not accessed when the api calls the report.
2569 public function beginPostProcess() {
2570 $this->setParams($this->controller
->exportValues($this->_name
));
2571 if (empty($this->_params
) &&
2574 $this->setParams($this->_formValues
);
2577 // hack to fix params when submitted from dashboard, CRM-8532
2578 // fields array is missing because form building etc is skipped
2579 // in dashboard mode for report
2580 //@todo - this could be done in the dashboard no we have a setter
2581 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2582 $this->setParams($this->_formValues
);
2585 $this->processReportMode();
2587 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2588 $this->_createNew
= ($this->_outputMode
== 'copy');
2589 CRM_Report_Form_Instance
::postProcess($this);
2591 if ($this->_outputMode
== 'delete') {
2592 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2595 $this->_formValues
= $this->_params
;
2597 $this->beginPostProcessCommon();
2601 * BeginPostProcess function run in both report mode and non-report mode (api).
2603 public function beginPostProcessCommon() {
2607 * Build the report query.
2609 * @param bool $applyLimit
2613 public function buildQuery($applyLimit = TRUE) {
2614 $this->buildGroupTempTable();
2617 $this->customDataFrom();
2618 $this->buildPermissionClause();
2623 // order_by columns not selected for display need to be included in SELECT
2624 $unselectedSectionColumns = $this->unselectedSectionColumns();
2625 foreach ($unselectedSectionColumns as $alias => $section) {
2626 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2629 if ($applyLimit && empty($this->_params
['charts'])) {
2632 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2634 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2635 $this->addToDeveloperTab($sql);
2640 * Build group by clause.
2642 public function groupBy() {
2643 if (!empty($this->_params
['group_bys']) &&
2644 is_array($this->_params
['group_bys'])
2646 foreach ($this->_columns
as $tableName => $table) {
2647 if (array_key_exists('group_bys', $table)) {
2648 foreach ($table['group_bys'] as $fieldName => $field) {
2649 if (!empty($this->_params
['group_bys'][$fieldName])) {
2650 $this->_groupByArray
[] = $field['dbAlias'];
2657 if (!empty($this->_groupByArray
)) {
2658 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2663 * Build order by clause.
2665 public function orderBy() {
2666 $this->_orderBy
= "";
2667 $this->_sections
= array();
2668 $this->storeOrderByArray();
2669 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2670 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2672 $this->assign('sections', $this->_sections
);
2676 * Extract order by fields and store as an array.
2678 * In some cases other functions want to know which fields are selected for ordering by
2679 * Separating this into a separate function allows it to be called separately from constructing
2680 * the order by clause
2682 public function storeOrderByArray() {
2683 $orderBys = array();
2685 if (!empty($this->_params
['order_bys']) &&
2686 is_array($this->_params
['order_bys']) &&
2687 !empty($this->_params
['order_bys'])
2690 // Process order_bys in user-specified order
2691 foreach ($this->_params
['order_bys'] as $orderBy) {
2692 $orderByField = array();
2693 foreach ($this->_columns
as $tableName => $table) {
2694 if (array_key_exists('order_bys', $table)) {
2695 // For DAO columns defined in $this->_columns
2696 $fields = $table['order_bys'];
2698 elseif (array_key_exists('extends', $table)) {
2699 // For custom fields referenced in $this->_customGroupExtends
2700 $fields = CRM_Utils_Array
::value('fields', $table, array());
2705 if (!empty($fields) && is_array($fields)) {
2706 foreach ($fields as $fieldName => $field) {
2707 if ($fieldName == $orderBy['column']) {
2708 $orderByField = array_merge($field, $orderBy);
2709 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2716 if (!empty($orderByField)) {
2717 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2718 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2720 // Record any section headers for assignment to the template
2721 if (!empty($orderBy['section'])) {
2722 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2723 $this->_sections
[$orderByField['tplField']] = $orderByField;
2729 $this->_orderByArray
= $orderBys;
2731 $this->assign('sections', $this->_sections
);
2735 * Determine unselected columns.
2739 public function unselectedSectionColumns() {
2740 if (is_array($this->_sections
)) {
2741 return array_diff_key($this->_sections
, $this->getSelectColumns());
2749 * Build output rows.
2751 * @param string $sql
2752 * @param array $rows
2754 public function buildRows($sql, &$rows) {
2755 $dao = CRM_Core_DAO
::executeQuery($sql);
2756 if (!is_array($rows)) {
2760 // use this method to modify $this->_columnHeaders
2761 $this->modifyColumnHeaders();
2763 $unselectedSectionColumns = $this->unselectedSectionColumns();
2765 while ($dao->fetch()) {
2767 foreach ($this->_columnHeaders
as $key => $value) {
2768 if (property_exists($dao, $key)) {
2769 $row[$key] = $dao->$key;
2773 // section headers not selected for display need to be added to row
2774 foreach ($unselectedSectionColumns as $key => $values) {
2775 if (property_exists($dao, $key)) {
2776 $row[$key] = $dao->$key;
2785 * Calculate section totals.
2787 * When "order by" fields are marked as sections, this assigns to the template
2788 * an array of total counts for each section. This data is used by the Smarty
2789 * plugin {sectionTotal}.
2791 public function sectionTotals() {
2793 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2794 if (empty($this->_selectAliases
)) {
2798 if (!empty($this->_sections
)) {
2799 // build the query with no LIMIT clause
2800 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2801 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2803 // pull section aliases out of $this->_sections
2804 $sectionAliases = array_keys($this->_sections
);
2807 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2808 $ifnulls[] = "ifnull($alias, '') as $alias";
2810 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2811 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2813 // Group (un-limited) report by all aliases and get counts. This might
2814 // be done more efficiently when the contents of $sql are known, ie. by
2815 // overriding this method in the report class.
2817 $query = $this->_select
.
2818 ", count(*) as ct from ($sql) as subquery group by " .
2819 implode(", ", $sectionAliases);
2821 // initialize array of total counts
2823 $dao = CRM_Core_DAO
::executeQuery($query);
2824 while ($dao->fetch()) {
2826 // let $this->_alterDisplay translate any integer ids to human-readable values.
2827 $rows[0] = $dao->toArray();
2828 $this->alterDisplay($rows);
2831 // add totals for all permutations of section values
2834 $aliasCount = count($sectionAliases);
2835 foreach ($sectionAliases as $alias) {
2836 $values[] = $row[$alias];
2837 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2838 if ($i == $aliasCount) {
2839 // the last alias is the lowest-level section header; use count as-is
2840 $totals[$key] = $dao->ct
;
2843 // other aliases are higher level; roll count into their total
2844 $totals[$key] +
= $dao->ct
;
2848 $this->assign('sectionTotals', $totals);
2853 * Modify column headers.
2855 public function modifyColumnHeaders() {
2856 // use this method to modify $this->_columnHeaders
2860 * Move totals columns to the right edge of the table.
2862 * It seems like a more logical layout to have any totals columns on the far right regardless of
2863 * the location of the rest of their table.
2865 public function moveSummaryColumnsToTheRightHandSide() {
2866 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2867 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2871 * Assign rows to the template.
2873 * @param array $rows
2875 public function doTemplateAssignment(&$rows) {
2876 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2877 $this->assign_by_ref('rows', $rows);
2878 $this->assign('statistics', $this->statistics($rows));
2882 * Build report statistics.
2884 * Override this method to build your own statistics.
2886 * @param array $rows
2890 public function statistics(&$rows) {
2891 $statistics = array();
2893 $count = count($rows);
2894 // Why do we increment the count for rollup seems to artificially inflate the count.
2895 // It seems perhaps intentional to include the summary row in the count of results - although
2896 // this just seems odd.
2897 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2901 $this->countStat($statistics, $count);
2903 $this->groupByStat($statistics);
2905 $this->filterStat($statistics);
2911 * Add count statistics.
2913 * @param array $statistics
2916 public function countStat(&$statistics, $count) {
2917 $statistics['counts']['rowCount'] = array(
2918 'title' => ts('Row(s) Listed'),
2922 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2923 $statistics['counts']['rowsFound'] = array(
2924 'title' => ts('Total Row(s)'),
2925 'value' => $this->_rowsFound
,
2931 * Add group by statistics.
2933 * @param array $statistics
2935 public function groupByStat(&$statistics) {
2936 if (!empty($this->_params
['group_bys']) &&
2937 is_array($this->_params
['group_bys']) &&
2938 !empty($this->_params
['group_bys'])
2940 foreach ($this->_columns
as $tableName => $table) {
2941 if (array_key_exists('group_bys', $table)) {
2942 foreach ($table['group_bys'] as $fieldName => $field) {
2943 if (!empty($this->_params
['group_bys'][$fieldName])) {
2944 $combinations[] = $field['title'];
2949 $statistics['groups'][] = array(
2950 'title' => ts('Grouping(s)'),
2951 'value' => implode(' & ', $combinations),
2957 * Filter statistics.
2959 * @param array $statistics
2961 public function filterStat(&$statistics) {
2962 foreach ($this->_columns
as $tableName => $table) {
2963 if (array_key_exists('filters', $table)) {
2964 foreach ($table['filters'] as $fieldName => $field) {
2965 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2966 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2967 CRM_Utils_Array
::value('operatorType', $field) !=
2968 CRM_Report_Form
::OP_MONTH
2972 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2973 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2974 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2975 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2976 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2978 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2979 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2981 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2982 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2985 $statistics['filters'][] = array(
2986 'title' => $field['title'],
2987 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2990 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2991 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2993 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2994 $statistics['filters'][] = array(
2995 'title' => $field['title'],
2996 'value' => $pair[$rel],
3001 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3004 $pair = $this->getOperationPair(
3005 CRM_Utils_Array
::value('operatorType', $field),
3008 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3009 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3010 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3011 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3012 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3014 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3015 $this->setEntityRefDefaults($field, $tableName);
3016 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3017 array('id' => $val) +
3018 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3020 foreach ($result['values'] as $v) {
3021 $values[] = $v['label'];
3023 $value = "{$pair[$op]} " . implode(', ', $values);
3025 elseif ($op == 'nll' ||
$op == 'nnll') {
3026 $value = $pair[$op];
3028 elseif (is_array($val) && (!empty($val))) {
3029 $options = CRM_Utils_Array
::value('options', $field, array());
3030 foreach ($val as $key => $valIds) {
3031 if (isset($options[$valIds])) {
3032 $val[$key] = $options[$valIds];
3035 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3036 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3037 $val = implode(', ', $val);
3038 $value = "{$pair[$op]} " . $val;
3040 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3041 isset($field['options']) &&
3042 is_array($field['options']) && !empty($field['options'])
3044 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3045 CRM_Utils_Array
::value($val, $field['options'], $val);
3048 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3051 if ($value && empty($field['no_display'])) {
3052 $statistics['filters'][] = array(
3053 'title' => CRM_Utils_Array
::value('title', $field),
3064 * End post processing.
3066 * @param array|null $rows
3068 public function endPostProcess(&$rows = NULL) {
3069 $this->assign('report_class', get_class($this));
3070 if ($this->_storeResultSet
) {
3071 $this->_resultSet
= $rows;
3074 if ($this->_outputMode
== 'print' ||
3075 $this->_outputMode
== 'pdf' ||
3079 $content = $this->compileContent();
3080 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3084 if ($this->_sendmail
) {
3085 $config = CRM_Core_Config
::singleton();
3086 $attachments = array();
3088 if ($this->_outputMode
== 'csv') {
3090 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3091 ": {$url}</p>" . '<p>' .
3092 ts('The report is attached as a CSV file.') . '</p>' .
3093 $this->_formValues
['report_footer'];
3095 $csvFullFilename = $config->templateCompileDir
.
3096 CRM_Utils_File
::makeFileName('CiviReport.csv');
3097 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3098 file_put_contents($csvFullFilename, $csvContent);
3099 $attachments[] = array(
3100 'fullPath' => $csvFullFilename,
3101 'mime_type' => 'text/csv',
3102 'cleanName' => 'CiviReport.csv',
3105 if ($this->_outputMode
== 'pdf') {
3106 // generate PDF content
3107 $pdfFullFilename = $config->templateCompileDir
.
3108 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3109 file_put_contents($pdfFullFilename,
3110 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3111 TRUE, array('orientation' => 'landscape')
3114 // generate Email Content
3116 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3117 ": {$url}</p>" . '<p>' .
3118 ts('The report is attached as a PDF file.') . '</p>' .
3119 $this->_formValues
['report_footer'];
3121 $attachments[] = array(
3122 'fullPath' => $pdfFullFilename,
3123 'mime_type' => 'application/pdf',
3124 'cleanName' => 'CiviReport.pdf',
3128 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3129 $this->_outputMode
, $attachments
3132 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3135 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3139 elseif ($this->_outputMode
== 'print') {
3143 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3144 $config = CRM_Core_Config
::singleton();
3145 //get chart image name
3146 $chartImg = $this->_chartId
. '.png';
3147 //get image url path
3149 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3151 $uploadUrl .= $chartImg;
3152 //get image doc path to overwrite
3154 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3155 'openFlashChart/' . $chartImg;
3157 $chart = imagecreatefrompng($uploadUrl);
3158 //convert it into formatted png
3159 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3160 //overwrite with same image
3161 imagepng($chart, $uploadImg);
3163 imagedestroy($chart);
3165 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3167 CRM_Utils_System
::civiExit();
3169 elseif ($this->_outputMode
== 'csv') {
3170 CRM_Report_Utils_Report
::export2csv($this, $rows);
3172 elseif ($this->_outputMode
== 'group') {
3173 $group = $this->_params
['groups'];
3174 $this->add2group($group);
3179 * Set store result set indicator to TRUE.
3181 * @todo explain what this does
3183 public function storeResultSet() {
3184 $this->_storeResultSet
= TRUE;
3192 public function getResultSet() {
3193 return $this->_resultSet
;
3197 * Get the sql used to generate the report.
3201 public function getReportSql() {
3202 return $this->sqlArray
;
3206 * Use the form name to create the tpl file name.
3210 public function getTemplateFileName() {
3211 $defaultTpl = parent
::getTemplateFileName();
3212 $template = CRM_Core_Smarty
::singleton();
3213 if (!$template->template_exists($defaultTpl)) {
3214 $defaultTpl = 'CRM/Report/Form.tpl';
3220 * Compile the report content.
3222 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3226 public function compileContent() {
3227 $templateFile = $this->getHookedTemplateFileName();
3228 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3229 CRM_Core_Form
::$_template->fetch($templateFile) .
3230 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3235 * Post process function.
3237 public function postProcess() {
3238 // get ready with post process params
3239 $this->beginPostProcess();
3242 $sql = $this->buildQuery();
3244 // build array of result based on column headers. This method also allows
3245 // modifying column headers before using it to build result set i.e $rows.
3247 $this->buildRows($sql, $rows);
3249 // format result set.
3250 $this->formatDisplay($rows);
3252 // assign variables to templates
3253 $this->doTemplateAssignment($rows);
3255 // do print / pdf / instance stuff if needed
3256 $this->endPostProcess($rows);
3262 * @param int $rowCount
3266 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3267 // lets do the pager if in html mode
3268 $this->_limit
= NULL;
3270 // CRM-14115, over-ride row count if rowCount is specified in URL
3271 if ($this->_dashBoardRowCount
) {
3272 $rowCount = $this->_dashBoardRowCount
;
3274 if ($this->addPaging
) {
3275 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3277 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3279 // @todo all http vars should be extracted in the preProcess
3280 // - not randomly in the class
3281 if (!$pageId && !empty($_POST)) {
3282 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3283 $pageId = max((int) $_POST['crmPID_B'], 1);
3285 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3286 $pageId = max((int) $_POST['crmPID'], 1);
3288 unset($_POST['crmPID_B'], $_POST['crmPID']);
3291 $pageId = $pageId ?
$pageId : 1;
3292 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3293 $offset = ($pageId - 1) * $rowCount;
3295 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3296 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3298 $this->_limit
= " LIMIT $offset, $rowCount";
3299 return array($offset, $rowCount);
3301 if ($this->_limitValue
) {
3302 if ($this->_offsetValue
) {
3303 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3306 $this->_limit
= " LIMIT " . $this->_limitValue
;
3314 * @param int $rowCount
3316 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3317 // CRM-14115, over-ride row count if rowCount is specified in URL
3318 if ($this->_dashBoardRowCount
) {
3319 $rowCount = $this->_dashBoardRowCount
;
3322 if ($this->_limit
&& ($this->_limit
!= '')) {
3323 if (!$this->_rowsFound
) {
3324 $sql = "SELECT FOUND_ROWS();";
3325 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3328 'total' => $this->_rowsFound
,
3329 'rowCount' => $rowCount,
3330 'status' => ts('Records') . ' %%StatusMessage%%',
3331 'buttonBottom' => 'PagerBottomButton',
3332 'buttonTop' => 'PagerTopButton',
3334 if (!empty($this->controller
)) {
3335 // This happens when being called from the api Really we want the api to be able to
3336 // pass paging parameters, but at this stage just preventing test crashes.
3337 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3340 $pager = new CRM_Utils_Pager($params);
3341 $this->assign_by_ref('pager', $pager);
3342 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3347 * Build a group filter with contempt for large data sets.
3349 * This function has been retained as it takes time to migrate the reports over
3350 * to the new method which will not crash on large datasets.
3354 * @param string $field
3355 * @param mixed $value
3360 public function legacySlowGroupFilterClause($field, $value, $op) {
3361 $smartGroupQuery = "";
3363 $group = new CRM_Contact_DAO_Group();
3364 $group->is_active
= 1;
3366 $smartGroups = array();
3367 while ($group->fetch()) {
3368 if (in_array($group->id
, $this->_params
['gid_value']) &&
3369 $group->saved_search_id
3371 $smartGroups[] = $group->id
;
3375 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3377 $smartGroupQuery = '';
3378 if (!empty($smartGroups)) {
3379 $smartGroups = implode(',', $smartGroups);
3380 $smartGroupQuery = " UNION DISTINCT
3381 SELECT DISTINCT smartgroup_contact.contact_id
3382 FROM civicrm_group_contact_cache smartgroup_contact
3383 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3386 $sqlOp = $this->getSQLOperator($op);
3387 if (!is_array($value)) {
3388 $value = array($value);
3390 //include child groups if any
3391 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3393 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3395 $contactAlias = $this->_aliases
['civicrm_contact'];
3396 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3397 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3399 return " {$contactAlias}.id {$sqlOp} (
3400 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3401 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3402 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3403 {$smartGroupQuery} ) ";
3407 * Build where clause for groups.
3409 * @param string $field
3410 * @param mixed $value
3415 public function whereGroupClause($field, $value, $op) {
3416 if ($this->groupFilterNotOptimised
) {
3417 return $this->legacySlowGroupFilterClause($field, $value, $op);
3419 if ($op === 'notin') {
3420 return " group_temp_table.id IS NULL ";
3422 // We will have used an inner join instead.
3428 * Create a table of the contact ids included by the group filter.
3430 * This function is called by both the api (tests) and the UI.
3432 public function buildGroupTempTable() {
3433 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3436 $filteredGroups = (array) $this->_params
['gid_value'];
3438 $groups = civicrm_api3('Group', 'get', array(
3440 'id' => array('IN' => $filteredGroups),
3441 'saved_search_id' => array('>' => 0),
3444 $smartGroups = array_keys($groups['values']);
3447 SELECT DISTINCT group_contact.contact_id as id
3448 FROM civicrm_group_contact group_contact
3449 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3450 AND group_contact.status = 'Added' ";
3452 if (!empty($smartGroups)) {
3453 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3454 $smartGroups = implode(',', $smartGroups);
3457 SELECT smartgroup_contact.contact_id as id
3458 FROM civicrm_group_contact_cache smartgroup_contact
3459 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3462 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3463 $this->executeReportQuery("
3464 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3467 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3471 * Execute query and add it to the developer tab.
3473 * @param string $query
3474 * @param array $params
3476 * @return \CRM_Core_DAO|object
3478 protected function executeReportQuery($query, $params = array()) {
3479 $this->addToDeveloperTab($query);
3480 return CRM_Core_DAO
::executeQuery($query, $params);
3484 * Build where clause for tags.
3486 * @param string $field
3487 * @param mixed $value
3492 public function whereTagClause($field, $value, $op) {
3493 // not using left join in query because if any contact
3494 // belongs to more than one tag, results duplicate
3496 $sqlOp = $this->getSQLOperator($op);
3497 if (!is_array($value)) {
3498 $value = array($value);
3500 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3501 $entity_table = $this->_tagFilterTable
;
3502 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3503 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3504 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3505 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3509 * Generate membership organization clause.
3511 * @param mixed $value
3512 * @param string $op SQL Operator
3516 public function whereMembershipOrgClause($value, $op) {
3517 $sqlOp = $this->getSQLOperator($op);
3518 if (!is_array($value)) {
3519 $value = array($value);
3522 $tmp_membership_org_sql_list = implode(', ', $value);
3523 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3524 SELECT DISTINCT mem.contact_id
3525 FROM civicrm_membership mem
3526 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3527 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3528 WHERE mt.member_of_contact_id IN (" .
3529 $tmp_membership_org_sql_list . ")
3530 AND mt.is_active = '1'
3531 AND mem_status.is_current_member = '1'
3532 AND mem_status.is_active = '1' ) ";
3536 * Generate Membership Type SQL Clause.
3538 * @param mixed $value
3544 public function whereMembershipTypeClause($value, $op) {
3545 $sqlOp = $this->getSQLOperator($op);
3546 if (!is_array($value)) {
3547 $value = array($value);
3550 $tmp_membership_sql_list = implode(', ', $value);
3551 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3552 SELECT DISTINCT mem.contact_id
3553 FROM civicrm_membership mem
3554 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3555 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3556 WHERE mem.membership_type_id IN (" .
3557 $tmp_membership_sql_list . ")
3558 AND mt.is_active = '1'
3559 AND mem_status.is_current_member = '1'
3560 AND mem_status.is_active = '1' ) ";
3564 * Buld contact acl clause
3565 * @deprecated in favor of buildPermissionClause
3567 * @param string $tableAlias
3569 public function buildACLClause($tableAlias = 'contact_a') {
3570 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3574 * Build the permision clause for all entities in this report
3576 public function buildPermissionClause() {
3578 foreach ($this->selectedTables() as $tableName) {
3579 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3580 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3581 $tableAlias = $this->_columns
[$tableName]['alias'];
3582 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3583 foreach ($clauses as $field => $clause) {
3584 // Skip contact_id field if redundant
3585 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3586 $ret["$tableName.$field"] = $clause;
3591 // Override output from buildACLClause
3592 $this->_aclFrom
= NULL;
3593 $this->_aclWhere
= implode(' AND ', $ret);
3597 * Add custom data to the columns.
3599 * @param bool $addFields
3600 * @param array $permCustomGroupIds
3602 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3603 if (empty($this->_customGroupExtends
)) {
3606 if (!is_array($this->_customGroupExtends
)) {
3607 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3609 $customGroupWhere = '';
3610 if (!empty($permCustomGroupIds)) {
3611 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3615 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3616 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3617 FROM civicrm_custom_group cg
3618 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3619 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3621 cg.is_active = 1 AND
3622 cf.is_active = 1 AND
3623 cf.is_searchable = 1
3624 ORDER BY cg.weight, cf.weight";
3625 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3628 while ($customDAO->fetch()) {
3629 if ($customDAO->table_name
!= $curTable) {
3630 $curTable = $customDAO->table_name
;
3631 $curFields = $curFilters = array();
3634 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3635 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3636 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3637 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3639 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3640 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3641 $this->_columns
[$curTable][$colKey] = array();
3645 $fieldName = 'custom_' . $customDAO->cf_id
;
3648 // this makes aliasing work in favor
3649 $curFields[$fieldName] = array(
3650 'name' => $customDAO->column_name
,
3651 'title' => $customDAO->label
,
3652 'dataType' => $customDAO->data_type
,
3653 'htmlType' => $customDAO->html_type
,
3656 if ($this->_customGroupFilters
) {
3657 // this makes aliasing work in favor
3658 $curFilters[$fieldName] = array(
3659 'name' => $customDAO->column_name
,
3660 'title' => $customDAO->label
,
3661 'dataType' => $customDAO->data_type
,
3662 'htmlType' => $customDAO->html_type
,
3666 switch ($customDAO->data_type
) {
3669 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3670 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3671 // CRM-6946, show time part for datetime date fields
3672 if ($customDAO->time_format
) {
3673 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3678 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3679 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3680 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3684 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3685 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3689 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3690 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3691 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3695 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3696 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3700 case 'StateProvince':
3702 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3704 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3705 if ($options !== FALSE) {
3706 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3707 $curFilters[$fieldName]['options'] = $options;
3711 case 'ContactReference':
3712 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3713 $curFilters[$fieldName]['name'] = 'display_name';
3714 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3716 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3717 $curFields[$fieldName]['name'] = 'display_name';
3718 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3722 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3723 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3727 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3728 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3729 if ($options !== FALSE) {
3730 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3731 $curFilters[$fieldName]['options'] = $options;
3735 if (!array_key_exists('type', $curFields[$fieldName])) {
3736 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3740 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3742 if ($this->_customGroupFilters
) {
3743 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3745 if ($this->_customGroupGroupBy
) {
3746 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3752 * Build custom data from clause.
3754 * @param bool $joinsForFiltersOnly
3755 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3757 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3758 if (empty($this->_customGroupExtends
)) {
3761 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3762 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3763 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3764 $customTables = array();
3765 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3766 while ($customTablesDAO->fetch()) {
3767 $customTables[] = $customTablesDAO->table_name
;
3770 foreach ($this->_columns
as $table => $prop) {
3771 if (in_array($table, $customTables)) {
3772 $extendsTable = $mapper[$prop['extends']];
3773 // Check field is required for rendering the report.
3774 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3777 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3779 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3781 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3782 // handle for ContactReference
3783 if (array_key_exists('fields', $prop)) {
3784 foreach ($prop['fields'] as $fieldName => $field) {
3785 if (CRM_Utils_Array
::value('dataType', $field) ==
3788 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3790 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3799 * Check if the field is selected.
3801 * @param string $prop
3805 public function isFieldSelected($prop) {
3810 if (!empty($this->_params
['fields'])) {
3811 foreach (array_keys($prop['fields']) as $fieldAlias) {
3812 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3813 if ($customFieldId) {
3814 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3818 //might be survey response field.
3819 if (!empty($this->_params
['fields']['survey_response']) &&
3820 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3828 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3829 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3830 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3831 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3838 if (!empty($this->_params
['order_bys'])) {
3839 foreach (array_keys($prop['fields']) as $fieldAlias) {
3840 foreach ($this->_params
['order_bys'] as $orderBy) {
3841 if ($fieldAlias == $orderBy['column'] &&
3842 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3849 return $this->isFieldFiltered($prop);
3854 * Check if the field is used as a filter.
3856 * @param string $prop
3860 protected function isFieldFiltered($prop) {
3861 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3862 foreach ($prop['filters'] as $fieldAlias => $val) {
3871 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3872 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3873 ||
($attach != 'relative' &&
3874 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3880 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3881 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3892 * Check for empty order_by configurations and remove them.
3894 * Also set template to hide them.
3896 * @param array $formValues
3898 public function preProcessOrderBy(&$formValues) {
3899 // Object to show/hide form elements
3900 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3902 $_showHide->addShow('optionField_1');
3904 // Cycle through order_by options; skip any empty ones, and hide them as well
3907 if (!empty($formValues['order_bys'])) {
3908 foreach ($formValues['order_bys'] as $order_by) {
3909 if ($order_by['column'] && $order_by['column'] != '-') {
3910 $_showHide->addShow('optionField_' . $n);
3911 $orderBys[$n] = $order_by;
3916 for ($i = $n; $i <= 5; $i++
) {
3918 $_showHide->addHide('optionField_' . $i);
3922 // overwrite order_by options with modified values
3923 if (!empty($orderBys)) {
3924 $formValues['order_bys'] = $orderBys;
3927 $formValues['order_bys'] = array(1 => array('column' => '-'));
3930 // assign show/hide data to template
3931 $_showHide->addToTemplate();
3935 * Check if table name has columns in SELECT clause.
3937 * @param string $tableName
3938 * Name of table (index of $this->_columns array).
3942 public function isTableSelected($tableName) {
3943 return in_array($tableName, $this->selectedTables());
3947 * Check if table name has columns in WHERE or HAVING clause.
3949 * @param string $tableName
3950 * Name of table (index of $this->_columns array).
3954 public function isTableFiltered($tableName) {
3955 // Cause the array to be generated if not previously done.
3956 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3957 $this->selectedTables();
3959 return in_array($tableName, $this->filteredTables
);
3963 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3965 * If the array is unset it will be built.
3970 public function selectedTables() {
3971 if (!$this->_selectedTables
) {
3972 $orderByColumns = array();
3973 if (array_key_exists('order_bys', $this->_params
) &&
3974 is_array($this->_params
['order_bys'])
3976 foreach ($this->_params
['order_bys'] as $orderBy) {
3977 $orderByColumns[] = $orderBy['column'];
3981 foreach ($this->_columns
as $tableName => $table) {
3982 if (array_key_exists('fields', $table)) {
3983 foreach ($table['fields'] as $fieldName => $field) {
3984 if (!empty($field['required']) ||
3985 !empty($this->_params
['fields'][$fieldName])
3987 $this->_selectedTables
[] = $tableName;
3992 if (array_key_exists('order_bys', $table)) {
3993 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3994 if (in_array($orderByName, $orderByColumns)) {
3995 $this->_selectedTables
[] = $tableName;
4000 if (array_key_exists('filters', $table)) {
4001 foreach ($table['filters'] as $filterName => $filter) {
4002 if (!empty($this->_params
["{$filterName}_value"]) ||
4003 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4005 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4008 $this->_selectedTables
[] = $tableName;
4009 $this->filteredTables
[] = $tableName;
4016 return $this->_selectedTables
;
4020 * Add address fields.
4022 * @deprecated - use getAddressColumns which is a more accurate description
4023 * and also accepts an array of options rather than a long list
4025 * adding address fields to construct function in reports
4027 * @param bool $groupBy
4028 * Add GroupBy? Not appropriate for detail report.
4029 * @param bool $orderBy
4030 * Add GroupBy? Not appropriate for detail report.
4031 * @param bool $filters
4032 * @param array $defaults
4035 * address fields for construct clause
4037 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4038 $defaultAddressFields = array(
4039 'street_address' => ts('Street Address'),
4040 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4041 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4042 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4043 'street_number' => ts('Street Number'),
4044 'street_name' => ts('Street Name'),
4045 'street_unit' => ts('Street Unit'),
4046 'city' => ts('City'),
4047 'postal_code' => ts('Postal Code'),
4048 'postal_code_suffix' => ts('Postal Code Suffix'),
4049 'country_id' => ts('Country'),
4050 'state_province_id' => ts('State/Province'),
4051 'county_id' => ts('County'),
4053 $addressFields = array(
4054 'civicrm_address' => array(
4055 'dao' => 'CRM_Core_DAO_Address',
4057 'address_name' => array(
4058 'title' => ts('Address Name'),
4059 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4063 'grouping' => 'location-fields',
4066 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4067 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4068 'title' => $fieldLabel,
4069 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4073 $street_address_filters = $general_address_filters = array();
4075 // Address filter depends on whether street address parsing is enabled.
4077 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4080 if ($addressOptions['street_address_parsing']) {
4081 $street_address_filters = array(
4082 'street_number' => array(
4083 'title' => ts('Street Number'),
4084 'type' => CRM_Utils_Type
::T_INT
,
4085 'name' => 'street_number',
4087 'street_name' => array(
4088 'title' => ts('Street Name'),
4089 'name' => 'street_name',
4090 'type' => CRM_Utils_Type
::T_STRING
,
4095 $street_address_filters = array(
4096 'street_address' => array(
4097 'title' => ts('Street Address'),
4098 'type' => CRM_Utils_Type
::T_STRING
,
4099 'name' => 'street_address',
4103 $general_address_filters = array(
4104 'postal_code' => array(
4105 'title' => ts('Postal Code'),
4106 'type' => CRM_Utils_Type
::T_STRING
,
4107 'name' => 'postal_code',
4110 'title' => ts('City'),
4111 'type' => CRM_Utils_Type
::T_STRING
,
4114 'country_id' => array(
4115 'name' => 'country_id',
4116 'title' => ts('Country'),
4117 'type' => CRM_Utils_Type
::T_INT
,
4118 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4119 'options' => CRM_Core_PseudoConstant
::country(),
4121 'state_province_id' => array(
4122 'name' => 'state_province_id',
4123 'title' => ts('State/Province'),
4124 'type' => CRM_Utils_Type
::T_INT
,
4125 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4126 'options' => array(),
4128 'county_id' => array(
4129 'name' => 'county_id',
4130 'title' => ts('County'),
4131 'type' => CRM_Utils_Type
::T_INT
,
4132 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4133 'options' => array(),
4137 $addressFields['civicrm_address']['filters'] = array_merge(
4138 $street_address_filters,
4139 $general_address_filters);
4142 $addressFields['civicrm_address']['order_bys'] = array(
4143 'street_name' => array('title' => ts('Street Name')),
4144 'street_number' => array('title' => ts('Odd / Even Street Number')),
4145 'street_address' => NULL,
4147 'postal_code' => NULL,
4152 $addressFields['civicrm_address']['group_bys'] = array(
4153 'street_address' => NULL,
4155 'postal_code' => NULL,
4156 'state_province_id' => array(
4157 'title' => ts('State/Province'),
4159 'country_id' => array(
4160 'title' => ts('Country'),
4162 'county_id' => array(
4163 'title' => ts('County'),
4167 return $addressFields;
4171 * Do AlterDisplay processing on Address Fields.
4174 * @param array $rows
4175 * @param int $rowNum
4176 * @param string $baseUrl
4177 * @param string $linkText
4181 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4182 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4183 $entryFound = FALSE;
4185 if (array_key_exists('civicrm_address_country_id', $row)) {
4186 if ($value = $row['civicrm_address_country_id']) {
4187 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4189 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4190 "reset=1&force=1&{$criteriaQueryParams}&" .
4191 "country_id_op=in&country_id_value={$value}",
4192 $this->_absoluteUrl
, $this->_id
4194 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4195 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4196 array(1 => $linkText)
4203 if (array_key_exists('civicrm_address_county_id', $row)) {
4204 if ($value = $row['civicrm_address_county_id']) {
4205 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4207 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4208 "reset=1&force=1&{$criteriaQueryParams}&" .
4209 "county_id_op=in&county_id_value={$value}",
4210 $this->_absoluteUrl
, $this->_id
4212 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4213 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4214 array(1 => $linkText)
4220 // handle state province
4221 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4222 if ($value = $row['civicrm_address_state_province_id']) {
4223 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4225 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4226 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4227 $this->_absoluteUrl
, $this->_id
4229 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4230 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4231 array(1 => $linkText)
4242 * Do AlterDisplay processing on Address Fields.
4245 * @param array $rows
4246 * @param int $rowNum
4247 * @param string $baseUrl
4248 * @param string $linkText
4252 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4253 $entryFound = FALSE;
4254 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4255 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4256 $addLinks = array('gender_id' => 'Gender');
4257 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4258 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4259 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4260 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4261 $rowLabels = array();
4262 foreach ($rowValues as $rowValue) {
4264 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4267 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4268 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4269 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4275 $yesNoFields = array(
4276 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4278 foreach ($yesNoFields as $fieldName) {
4279 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4280 // Since these are essentially 'negative fields' it feels like it
4281 // makes sense to only highlight the exceptions hence no 'No'.
4282 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4290 * Adjusts dates passed in to YEAR() for fiscal year.
4292 * @param string $fieldName
4296 public function fiscalYearOffset($fieldName) {
4297 $config = CRM_Core_Config
::singleton();
4298 $fy = $config->fiscalYearStart
;
4299 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4300 ($fy['d'] == 1 && $fy['M'] == 1)
4302 return "YEAR( $fieldName )";
4304 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4305 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4309 * Add Address into From Table if required.
4311 public function addAddressFromClause() {
4312 // include address field if address column is to be included
4313 if ((isset($this->_addressField
) &&
4314 $this->_addressField
4316 $this->isTableSelected('civicrm_address')
4319 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4320 ON ({$this->_aliases['civicrm_contact']}.id =
4321 {$this->_aliases['civicrm_address']}.contact_id) AND
4322 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4327 * Add Phone into From Table if required.
4329 public function addPhoneFromClause() {
4330 // include address field if address column is to be included
4331 if ($this->isTableSelected('civicrm_phone')) {
4333 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4334 ON ({$this->_aliases['civicrm_contact']}.id =
4335 {$this->_aliases['civicrm_phone']}.contact_id) AND
4336 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4341 * Add Financial Transaction into From Table if required.
4343 public function addFinancialTrxnFromClause() {
4344 if ($this->isTableSelected('civicrm_financial_trxn')) {
4346 LEFT JOIN civicrm_entity_financial_trxn eftcc
4347 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4348 eftcc.entity_table = 'civicrm_contribution')
4349 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4350 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4355 * Get phone columns to add to array.
4357 * @param array $options
4358 * - prefix Prefix to add to table (in case of more than one instance of the table)
4359 * - prefix_label Label to give columns from this phone table instance
4362 * phone columns definition
4364 public function getPhoneColumns($options = array()) {
4365 $defaultOptions = array(
4367 'prefix_label' => '',
4370 $options = array_merge($defaultOptions, $options);
4373 $options['prefix'] . 'civicrm_phone' => array(
4374 'dao' => 'CRM_Core_DAO_Phone',
4376 $options['prefix'] . 'phone' => array(
4377 'title' => ts($options['prefix_label'] . 'Phone'),
4387 * Get address columns to add to array.
4389 * @param array $options
4390 * - prefix Prefix to add to table (in case of more than one instance of the table)
4391 * - prefix_label Label to give columns from this address table instance
4394 * address columns definition
4396 public function getAddressColumns($options = array()) {
4399 'prefix_label' => '',
4403 'defaults' => array(),
4405 return $this->addAddressFields(
4406 $options['group_by'],
4407 $options['order_by'],
4408 $options['filters'],
4409 $options['defaults']
4414 * Get a standard set of contact fields.
4418 public function getBasicContactFields() {
4420 'sort_name' => array(
4421 'title' => ts('Contact Name'),
4426 'no_display' => TRUE,
4429 'prefix_id' => array(
4430 'title' => ts('Contact Prefix'),
4432 'first_name' => array(
4433 'title' => ts('First Name'),
4435 'nick_name' => array(
4436 'title' => ts('Nick Name'),
4438 'middle_name' => array(
4439 'title' => ts('Middle Name'),
4441 'last_name' => array(
4442 'title' => ts('Last Name'),
4444 'suffix_id' => array(
4445 'title' => ts('Contact Suffix'),
4447 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4448 'email_greeting_display' => array('title' => ts('Email Greeting')),
4449 'addressee_display' => array('title' => ts('Addressee')),
4450 'contact_type' => array(
4451 'title' => ts('Contact Type'),
4453 'contact_sub_type' => array(
4454 'title' => ts('Contact Subtype'),
4456 'gender_id' => array(
4457 'title' => ts('Gender'),
4459 'birth_date' => array(
4460 'title' => ts('Birth Date'),
4463 'title' => ts('Age'),
4464 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4466 'job_title' => array(
4467 'title' => ts('Contact Job title'),
4469 'organization_name' => array(
4470 'title' => ts('Organization Name'),
4472 'external_identifier' => array(
4473 'title' => ts('Contact identifier from external system'),
4475 'do_not_email' => array(),
4476 'do_not_phone' => array(),
4477 'do_not_mail' => array(),
4478 'do_not_sms' => array(),
4479 'is_opt_out' => array(),
4480 'is_deceased' => array(),
4481 'preferred_language' => array(),
4486 * Get a standard set of contact filters.
4490 public function getBasicContactFilters() {
4492 'sort_name' => array(
4493 'title' => ts('Contact Name'),
4496 'title' => ts('Contact Source'),
4497 'type' => CRM_Utils_Type
::T_STRING
,
4500 'title' => ts('Contact ID'),
4501 'no_display' => TRUE,
4503 'gender_id' => array(
4504 'title' => ts('Gender'),
4505 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4506 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4508 'birth_date' => array(
4509 'title' => ts('Birth Date'),
4510 'operatorType' => CRM_Report_Form
::OP_DATE
,
4512 'contact_type' => array(
4513 'title' => ts('Contact Type'),
4515 'contact_sub_type' => array(
4516 'title' => ts('Contact Subtype'),
4518 'modified_date' => array(
4519 'title' => ts('Contact Modified'),
4520 'operatorType' => CRM_Report_Form
::OP_DATE
,
4521 'type' => CRM_Utils_Type
::T_DATE
,
4523 'is_deceased' => array(
4524 'title' => ts('Deceased'),
4525 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4528 'do_not_email' => array(
4529 'title' => ts('Do not email'),
4530 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4532 'do_not_phone' => array(
4533 'title' => ts('Do not phone'),
4534 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4536 'do_not_mail' => array(
4537 'title' => ts('Do not mail'),
4538 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4540 'do_not_sms' => array(
4541 'title' => ts('Do not SMS'),
4542 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4544 'is_opt_out' => array(
4545 'title' => ts('Do not bulk email'),
4546 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4548 'preferred_language' => array(
4549 'title' => ts('Preferred Language'),
4551 'is_deleted' => array(
4552 'no_display' => TRUE,
4554 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4560 * Add contact to group.
4562 * @param int $groupID
4564 public function add2group($groupID) {
4565 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4566 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4567 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4568 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4569 $sql = str_replace('WITH ROLLUP', '', $sql);
4570 $dao = CRM_Core_DAO
::executeQuery($sql);
4572 $contact_ids = array();
4573 // Add resulting contacts to group
4574 while ($dao->fetch()) {
4575 if ($dao->addtogroup_contact_id
) {
4576 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4580 if (!empty($contact_ids)) {
4581 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4582 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4585 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4591 * Show charts on print screen.
4593 public static function uploadChartImage() {
4594 // upload strictly for '.png' images
4595 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4596 if (preg_match('/\.png$/', $name)) {
4598 // Get the RAW .png from the input.
4599 $httpRawPostData = file_get_contents("php://input");
4601 // prepare the directory
4602 $config = CRM_Core_Config
::singleton();
4604 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4606 if (!file_exists($defaultPath)) {
4607 mkdir($defaultPath, 0777, TRUE);
4610 // full path to the saved image including filename
4611 $destination = $defaultPath . $name;
4614 $jfh = fopen($destination, 'w') or die("can't open file");
4615 fwrite($jfh, $httpRawPostData);
4617 CRM_Utils_System
::civiExit();
4622 * Apply common settings to entityRef fields.
4624 * @param array $field
4625 * @param string $table
4627 private function setEntityRefDefaults(&$field, $table) {
4628 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4629 $field['attributes'] +
= array(
4630 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4632 'placeholder' => ts('- select -'),
4637 * Add link fields to the row.
4639 * Function adds the _link & _hover fields to the row.
4642 * @param string $baseUrl
4643 * @param string $linkText
4644 * @param string $value
4645 * @param string $fieldName
4646 * @param string $tablePrefix
4647 * @param string $fieldLabel
4651 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4652 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4653 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4654 "reset=1&force=1&{$criteriaQueryParams}&" .
4655 $fieldName . "_op=in&{$fieldName}_value={$value}",
4656 $this->_absoluteUrl
, $this->_id
4658 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4659 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4660 array(1 => $linkText, 2 => $fieldLabel)
4665 * Get label for show results buttons.
4669 public function getResultsLabel() {
4670 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4671 return $showResultsLabel;
4675 * Determine the output mode from the url or input.
4678 * - pdf : Render as pdf
4679 * - csv : Render as csv
4680 * - print : Render in print format
4681 * - save : save the report and display the new report
4682 * - copy : save the report as a new instance and display that.
4683 * - group : go to the add to group screen.
4685 * Potentially chart variations could also be included but the complexity
4686 * is that we might print a bar chart as a pdf.
4688 protected function setOutputMode() {
4689 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4692 CRM_Core_DAO
::$_nullObject,
4694 CRM_Utils_Array
::value('task', $this->_params
)
4696 // if contacts are added to group
4697 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4698 $this->_outputMode
= 'group';
4700 if (isset($this->_params
['task'])) {
4701 unset($this->_params
['task']);
4706 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4709 * @param $columnName
4711 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4712 // add new column with date value for the datetime field
4713 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4714 CRM_Core_DAO
::executeQuery($tempQuery);
4715 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4716 CRM_Core_DAO
::executeQuery($updateQuery);
4717 $this->_selectClauses
[] = "{$columnName}_date";
4718 $this->_select
.= ", {$columnName}_date";
4719 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4720 unset($this->_sections
["{$columnName}"]);
4721 $this->assign('sections', $this->_sections
);
4725 * Get an array of the columns that have been selected for display.
4729 public function getSelectColumns() {
4730 $selectColumns = array();
4731 foreach ($this->_columns
as $tableName => $table) {
4732 if (array_key_exists('fields', $table)) {
4733 foreach ($table['fields'] as $fieldName => $field) {
4734 if (!empty($field['required']) ||
4735 !empty($this->_params
['fields'][$fieldName])
4738 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4743 return $selectColumns;
4747 * Add location tables to the query if they are used for filtering.
4749 * This is for when we are running the query separately for filtering and retrieving display fields.
4751 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4752 if ($this->isTableFiltered('civicrm_email')) {
4754 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4755 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4756 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4758 if ($this->isTableFiltered('civicrm_phone')) {
4760 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4761 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4762 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4764 if ($this->isTableFiltered('civicrm_address')) {
4766 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4767 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4768 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4773 * Set the base table for the FROM clause.
4775 * Sets up the from clause, allowing for the possibility it might be a
4776 * temp table pre-filtered by groups if a group filter is in use.
4778 * @param string $baseTable
4779 * @param string $field
4780 * @param null $tableAlias
4782 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4784 $tableAlias = $this->_aliases
[$baseTable];
4786 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4787 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4788 $this->_from
.= " {$this->_aclFrom} ";
4792 * Join the temp table contacting contacts who are members of the filtered groups.
4794 * If we are using an IN filter we use an inner join, otherwise a left join.
4796 * @param string $baseTable
4797 * @param string $field
4798 * @param string $tableAlias
4800 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4801 if ($this->groupTempTable
) {
4802 if ($this->_params
['gid_op'] == 'in') {
4803 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4804 ON group_temp_table.id = $tableAlias.{$field} ";
4808 LEFT JOIN $this->groupTempTable group_temp_table
4809 ON $tableAlias.{$field} = group_temp_table.id ";
4815 * Get all labels for fields that are used in a group concat.
4817 * @param string $options
4818 * comma separated option values.
4819 * @param string $baoName
4820 * The BAO name for the field.
4821 * @param string $fieldName
4822 * The name of the field for which labels should be retrieved.
4826 public function getLabels($options, $baoName, $fieldName) {
4827 $types = explode(',', $options);
4829 foreach ($types as $value) {
4830 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
4832 return implode(', ', array_filter($labels));
4836 * Add statistics columns.
4838 * If a group by is in play then add columns for the statistics fields.
4840 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
4841 * column header field.
4843 * @param array $field
4844 * @param string $tableName
4845 * @param string $fieldName
4846 * @param array $select
4850 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
4851 foreach ($field['statistics'] as $stat => $label) {
4852 $alias = "{$tableName}_{$fieldName}_{$stat}";
4853 switch (strtolower($stat)) {
4856 $select[] = "$stat({$field['dbAlias']}) as $alias";
4857 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4858 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4859 $this->_statFields
[$label] = $alias;
4860 $this->_selectAliases
[] = $alias;
4864 $select[] = "COUNT({$field['dbAlias']}) as $alias";
4865 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4866 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4867 $this->_statFields
[$label] = $alias;
4868 $this->_selectAliases
[] = $alias;
4871 case 'count_distinct':
4872 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
4873 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4874 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4875 $this->_statFields
[$label] = $alias;
4876 $this->_selectAliases
[] = $alias;
4880 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
4881 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4882 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4883 $this->_statFields
[$label] = $alias;
4884 $this->_selectAliases
[] = $alias;
4892 * Add a basic field to the select clause.
4894 * @param string $tableName
4895 * @param string $fieldName
4896 * @param array $field
4897 * @param string $select
4900 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
4901 $alias = "{$tableName}_{$fieldName}";
4902 $select[] = "{$field['dbAlias']} as $alias";
4903 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
4904 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
4905 $this->_selectAliases
[] = $alias;
4912 * @param array $table
4913 * @param string $tableName
4918 protected function setTableAlias($table, $tableName) {
4919 if (!isset($table['alias'])) {
4920 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
4924 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
4927 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
4928 return $this->_aliases
[$tableName];