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);
817 if (!isset($this->_columns
[$tableName]['metadata'][$fieldName])) {
818 $this->_columns
[$tableName]['metadata'][$fieldName] = $this->_columns
[$tableName][$fieldGrp][$fieldName];
824 // copy filters to a separate handy variable
825 if (array_key_exists('filters', $table)) {
826 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
829 if (array_key_exists('group_bys', $table)) {
830 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
833 if (array_key_exists('fields', $table)) {
834 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
839 $this->setDefaultValues(FALSE);
842 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
843 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
844 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
845 CRM_Report_Utils_Get
::processChart($this->_defaults
);
848 $this->_formValues
= $this->_defaults
;
849 $this->postProcess();
854 * Set default values.
856 * @param bool $freeze
860 public function setDefaultValues($freeze = TRUE) {
861 $freezeGroup = array();
863 // FIXME: generalizing form field naming conventions would reduce
864 // Lots of lines below.
865 foreach ($this->_columns
as $tableName => $table) {
866 if (array_key_exists('fields', $table)) {
867 foreach ($table['fields'] as $fieldName => $field) {
868 if (empty($field['no_display'])) {
869 if (isset($field['required'])) {
871 $this->_defaults
['fields'][$fieldName] = 1;
874 // find element object, so that we could use quickform's freeze method
875 // for required elements
876 $obj = $this->getElementFromGroup("fields", $fieldName);
878 $freezeGroup[] = $obj;
882 elseif (isset($field['default'])) {
883 $this->_defaults
['fields'][$fieldName] = $field['default'];
889 if (array_key_exists('group_bys', $table)) {
890 foreach ($table['group_bys'] as $fieldName => $field) {
891 if (isset($field['default'])) {
892 if (!empty($field['frequency'])) {
893 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
895 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
899 if (array_key_exists('filters', $table)) {
900 foreach ($table['filters'] as $fieldName => $field) {
901 if (isset($field['default'])) {
902 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
904 if (is_array($field['default'])) {
905 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
906 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
907 $this->_defaults
["{$fieldName}_relative"] = 0;
910 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
914 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
915 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
916 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
918 $this->_defaults
["{$fieldName}_value"] = $field['default'];
921 //assign default value as "in" for multiselect
922 //operator, To freeze the select element
923 if (CRM_Utils_Array
::value('operatorType', $field) ==
924 CRM_Report_Form
::OP_MULTISELECT
926 $this->_defaults
["{$fieldName}_op"] = 'in';
928 if (CRM_Utils_Array
::value('operatorType', $field) ==
929 CRM_Report_Form
::OP_ENTITYREF
931 $this->_defaults
["{$fieldName}_op"] = 'in';
933 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
934 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
936 $this->_defaults
["{$fieldName}_op"] = 'mhas';
938 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
939 $this->_defaults
["{$fieldName}_op"] = $op;
945 empty($this->_formValues
['order_bys']) &&
946 (array_key_exists('order_bys', $table) &&
947 is_array($table['order_bys']))
949 if (!array_key_exists('order_bys', $this->_defaults
)) {
950 $this->_defaults
['order_bys'] = array();
952 foreach ($table['order_bys'] as $fieldName => $field) {
953 if (!empty($field['default']) ||
!empty($field['default_order']) ||
954 CRM_Utils_Array
::value('default_is_section', $field) ||
955 !empty($field['default_weight'])
958 'column' => $fieldName,
959 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
960 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
963 if (!empty($field['default_weight'])) {
964 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
967 array_unshift($this->_defaults
['order_bys'], $order_by);
973 foreach ($this->_options
as $fieldName => $field) {
974 if (isset($field['default'])) {
975 $this->_defaults
['options'][$fieldName] = $field['default'];
980 if (!empty($this->_submitValues
)) {
981 $this->preProcessOrderBy($this->_submitValues
);
984 $this->preProcessOrderBy($this->_defaults
);
987 // lets finish freezing task here itself
988 if (!empty($freezeGroup)) {
989 foreach ($freezeGroup as $elem) {
994 if ($this->_formValues
) {
995 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
998 if ($this->_instanceValues
) {
999 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
1002 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
1004 return $this->_defaults
;
1008 * Get element from group.
1010 * @param string $group
1011 * @param string $grpFieldName
1015 public function getElementFromGroup($group, $grpFieldName) {
1016 $eleObj = $this->getElement($group);
1017 foreach ($eleObj->_elements
as $index => $obj) {
1018 if ($grpFieldName == $obj->_attributes
['name']) {
1026 * Setter for $_params.
1028 * @param array $params
1030 public function setParams($params) {
1031 $this->_params
= $params;
1037 * @param int $instanceID
1039 public function setID($instanceID) {
1040 $this->_id
= $instanceID;
1044 * Setter for $_force.
1046 * @param bool $isForce
1048 public function setForce($isForce) {
1049 $this->_force
= $isForce;
1053 * Setter for $_limitValue.
1055 * @param int $_limitValue
1057 public function setLimitValue($_limitValue) {
1058 $this->_limitValue
= $_limitValue;
1062 * Setter for $_offsetValue.
1064 * @param int $_offsetValue
1066 public function setOffsetValue($_offsetValue) {
1067 $this->_offsetValue
= $_offsetValue;
1071 * Setter for $addPaging.
1073 * @param bool $value
1075 public function setAddPaging($value) {
1076 $this->addPaging
= $value;
1080 * Getter for $_defaultValues.
1084 public function getDefaultValues() {
1085 return $this->_defaults
;
1089 * Add columns to report.
1091 public function addColumns() {
1094 foreach ($this->_columns
as $tableName => $table) {
1095 if (array_key_exists('fields', $table)) {
1096 foreach ($table['fields'] as $fieldName => $field) {
1098 if (empty($field['no_display'])) {
1099 foreach (array('table', 'field') as $var) {
1100 if (!empty($
{$var}['grouping'])) {
1101 if (!is_array($
{$var}['grouping'])) {
1102 $tableName = $
{$var}['grouping'];
1105 $tableName = array_keys($
{$var}['grouping']);
1106 $tableName = $tableName[0];
1107 $groupTitle = array_values($
{$var}['grouping']);
1108 $groupTitle = $groupTitle[0];
1113 if (!$groupTitle && isset($table['group_title'])) {
1114 $groupTitle = $table['group_title'];
1115 // Having a group_title is secret code for being a custom group
1116 // which cryptically translates to needing an accordion.
1117 // here we make that explicit.
1118 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1121 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1122 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1123 $colGroups[$tableName]['group_title'] = $groupTitle;
1125 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1131 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1132 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1134 if (!empty($colGroups)) {
1135 $this->tabs
['FieldSelection'] = array(
1136 'title' => ts('Columns'),
1137 'tpl' => 'FieldSelection',
1138 'div_label' => 'col-groups',
1141 // Note this assignment is only really required in buildForm. It is being 'over-called'
1142 // to reduce risk of being missed due to overridden functions.
1143 $this->assign('tabs', $this->tabs
);
1146 $this->assign('colGroups', $colGroups);
1150 * Add filters to report.
1152 public function addFilters() {
1153 $filters = $filterGroups = array();
1156 foreach ($this->_filters
as $table => $attributes) {
1157 if (isset($this->_columns
[$table]['group_title'])) {
1158 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1159 // which magically means to 'display in an accordian'
1160 // here we make this explicit.
1161 $filterGroups[$table] = array(
1162 'group_title' => $this->_columns
[$table]['group_title'],
1163 'use_accordian_for_field_selection' => TRUE,
1167 foreach ($attributes as $fieldName => $field) {
1168 // get ready with option value pair
1169 // @ 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
1171 $operations = $this->getOperationPair(
1172 CRM_Utils_Array
::value('operatorType', $field),
1175 $filters[$table][$fieldName] = $field;
1177 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1178 case CRM_Report_Form
::OP_MONTH
:
1179 if (!array_key_exists('options', $field) ||
1180 !is_array($field['options']) ||
empty($field['options'])
1182 // If there's no option list for this filter, define one.
1183 $field['options'] = array(
1185 2 => ts('February'),
1192 9 => ts('September'),
1193 10 => ts('October'),
1194 11 => ts('November'),
1195 12 => ts('December'),
1197 // Add this option list to this column _columns. This is
1198 // required so that filter statistics show properly.
1199 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1201 case CRM_Report_Form
::OP_MULTISELECT
:
1202 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1203 // assume a multi-select field
1204 if (!empty($field['options']) ||
1205 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1207 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1208 if (count($operations) <= 1) {
1211 if ($fieldName == 'state_province_id' ||
1212 $fieldName == 'county_id'
1214 $this->addChainSelect($fieldName . '_value', array(
1221 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1222 'style' => 'min-width:250px',
1223 'class' => 'crm-select2 huge',
1225 'placeholder' => ts('- select -'),
1231 case CRM_Report_Form
::OP_SELECT
:
1232 // assume a select field
1233 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1234 if (!empty($field['options'])) {
1235 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1239 case CRM_Report_Form
::OP_ENTITYREF
:
1240 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1241 $this->setEntityRefDefaults($field, $table);
1242 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1245 case CRM_Report_Form
::OP_DATE
:
1246 // build datetime fields
1247 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1251 case CRM_Report_Form
::OP_DATETIME
:
1252 // build datetime fields
1253 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1257 case CRM_Report_Form
::OP_INT
:
1258 case CRM_Report_Form
::OP_FLOAT
:
1259 // and a min value input box
1260 $this->add('text', "{$fieldName}_min", ts('Min'));
1261 // and a max value input box
1262 $this->add('text', "{$fieldName}_max", ts('Max'));
1264 // default type is string
1265 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1266 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1268 // we need text box for value input
1269 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1274 if (!empty($filters)) {
1275 $this->tabs
['Filters'] = array(
1276 'title' => ts('Filters'),
1278 'div_label' => 'set-filters',
1281 $this->assign('filters', $filters);
1282 $this->assign('filterGroups', $filterGroups);
1286 * Function to assign the tabs to the template in the correct order.
1288 * We want the tabs to wind up in this order (if not overridden).
1296 protected function assignTabs() {
1304 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1305 $order = array_merge($order, $this->tabs
);
1306 $this->assign('tabs', $order);
1310 * The intent is to add a tab for developers to view the sql.
1312 * Currently using dpm.
1314 * @param string $sql
1316 protected function addToDeveloperTab($sql) {
1317 if (!CRM_Core_Permission
::check('view report sql')) {
1320 $this->tabs
['Developer'] = array(
1321 'title' => ts('Developer'),
1322 'tpl' => 'Developer',
1323 'div_label' => 'set-developer',
1326 $this->assignTabs();
1327 $this->sqlArray
[] = $sql;
1328 foreach ($this->sqlArray
as $sql) {
1329 foreach (array('LEFT JOIN') as $term) {
1330 $sql = str_replace($term, '<br>  ' . $term, $sql);
1332 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1333 $sql = str_replace($term, '<br><br>' . $term, $sql);
1335 $this->sqlFormattedArray
[] = $sql;
1336 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray
));
1341 * Add options defined in $this->_options to the report.
1343 public function addOptions() {
1344 if (!empty($this->_options
)) {
1345 // FIXME: For now lets build all elements as checkboxes.
1346 // Once we clear with the format we can build elements based on type
1348 foreach ($this->_options
as $fieldName => $field) {
1351 if ($field['type'] == 'select') {
1352 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1354 elseif ($field['type'] == 'checkbox') {
1355 $options[$field['title']] = $fieldName;
1356 $this->addCheckBox($fieldName, NULL,
1358 NULL, NULL, NULL, $this->_fourColumnAttribute
1363 if (!empty($this->_options
) &&
1365 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1367 $this->tabs
['ReportOptions'] = array(
1368 'title' => ts('Display Options'),
1369 'tpl' => 'ReportOptions',
1370 'div_label' => 'other-options',
1373 $this->assign('otherOptions', $this->_options
);
1377 * Add chart options to the report.
1379 public function addChartOptions() {
1380 if (!empty($this->_charts
)) {
1381 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1382 $this->assign('charts', $this->_charts
);
1383 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1388 * Add group by options to the report.
1390 public function addGroupBys() {
1391 $options = $freqElements = array();
1393 foreach ($this->_columns
as $tableName => $table) {
1394 if (array_key_exists('group_bys', $table)) {
1395 foreach ($table['group_bys'] as $fieldName => $field) {
1396 if (!empty($field)) {
1397 $options[$field['title']] = $fieldName;
1398 if (!empty($field['frequency'])) {
1399 $freqElements[$field['title']] = $fieldName;
1405 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1406 NULL, NULL, NULL, $this->_fourColumnAttribute
1408 $this->assign('groupByElements', $options);
1409 if (!empty($options)) {
1410 $this->tabs
['GroupBy'] = array(
1411 'title' => ts('Grouping'),
1413 'div_label' => 'group-by-elements',
1417 foreach ($freqElements as $name) {
1418 $this->addElement('select', "group_bys_freq[$name]",
1419 ts('Frequency'), $this->_groupByDateFreq
1425 * Add data for order by tab.
1427 public function addOrderBys() {
1429 foreach ($this->_columns
as $tableName => $table) {
1431 // Report developer may define any column to order by; include these as order-by options.
1432 if (array_key_exists('order_bys', $table)) {
1433 foreach ($table['order_bys'] as $fieldName => $field) {
1434 if (!empty($field)) {
1435 $options[$fieldName] = $field['title'];
1440 // Add searchable custom fields as order-by options, if so requested
1441 // (These are already indexed, so allowing to order on them is cheap.)
1443 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1444 array_key_exists('extends', $table) && !empty($table['extends'])
1446 foreach ($table['fields'] as $fieldName => $field) {
1447 if (empty($field['no_display'])) {
1448 $options[$fieldName] = $field['title'];
1456 $this->assign('orderByOptions', $options);
1457 if (!empty($options)) {
1458 $this->tabs
['OrderBy'] = array(
1459 'title' => ts('Sorting'),
1461 'div_label' => 'order-by-elements',
1465 if (!empty($options)) {
1467 '-' => ' - none - ',
1469 for ($i = 1; $i <= 5; $i++
) {
1470 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1471 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1472 'ASC' => ts('Ascending'),
1473 'DESC' => ts('Descending'),
1475 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1476 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1482 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1484 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1485 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1488 public function buildInstanceAndButtons() {
1489 CRM_Report_Form_Instance
::buildForm($this);
1490 $this->_actionButtonName
= $this->getButtonName('submit');
1491 $this->addTaskMenu($this->getActions($this->_id
));
1493 $this->assign('instanceForm', $this->_instanceForm
);
1495 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1496 $permission = CRM_Core_Permission
::getPermission();
1497 if ($permission == CRM_Core_Permission
::EDIT
&&
1498 $this->_add2groupSupported
1500 $this->addElement('select', 'groups', ts('Group'),
1501 array('' => ts('Add Contacts to Group')) +
1502 CRM_Core_PseudoConstant
::nestedGroup(),
1503 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1505 $this->assign('group', TRUE);
1508 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1510 $this->addChartOptions();
1511 $showResultsLabel = $this->getResultsLabel();
1512 $this->addButtons(array(
1515 'name' => $showResultsLabel,
1516 'isDefault' => TRUE,
1523 * Has this form been submitted already?
1527 public function resultsDisplayed() {
1528 $buttonName = $this->controller
->getButtonName();
1529 return ($buttonName ||
$this->_outputMode
);
1533 * Get the actions for this report instance.
1535 * @param int $instanceId
1539 protected function getActions($instanceId) {
1540 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1541 if (empty($instanceId)) {
1542 $actions['report_instance.save'] = array(
1543 'title' => ts('Create Report'),
1545 'is_confirm' => TRUE,
1546 'confirm_title' => ts('Create Report'),
1547 'confirm_refresh_fields' => json_encode(array(
1548 'title' => array('selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''),
1549 'description' => array('selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''),
1555 if (!$this->_csvSupported
) {
1556 unset($actions['report_instance.csv']);
1563 * Main build form function.
1565 public function buildQuickForm() {
1566 $this->addColumns();
1568 $this->addFilters();
1570 $this->addOptions();
1572 $this->addGroupBys();
1574 $this->addOrderBys();
1576 $this->buildInstanceAndButtons();
1578 // Add form rule for report.
1579 if (is_callable(array(
1583 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1585 $this->assignTabs();
1589 * A form rule function for custom data.
1591 * The rule ensures that fields selected in group_by if any) should only be the ones
1592 * present in display/select fields criteria;
1593 * note: works if and only if any custom field selected in group_by.
1595 * @param array $fields
1596 * @param array $ignoreFields
1600 public function customDataFormRule($fields, $ignoreFields = array()) {
1602 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1603 !empty($fields['group_bys'])
1605 foreach ($this->_columns
as $tableName => $table) {
1606 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1607 substr($tableName, 0, 12) == 'custom_value') &&
1608 !empty($this->_columns
[$tableName]['fields'])
1610 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1611 if (array_key_exists($fieldName, $fields['group_bys']) &&
1612 !array_key_exists($fieldName, $fields['fields'])
1614 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1616 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1617 foreach ($fields['fields'] as $fld => $val) {
1618 if (!array_key_exists($fld, $fields['group_bys']) &&
1619 !in_array($fld, $ignoreFields)
1621 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1633 * Get operators to display on form.
1635 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1637 * @param string $type
1638 * @param string $fieldName
1642 public function getOperationPair($type = "string", $fieldName = NULL) {
1643 // FIXME: At some point we should move these key-val pairs
1644 // to option_group and option_value table.
1646 case CRM_Report_Form
::OP_INT
:
1647 case CRM_Report_Form
::OP_FLOAT
:
1650 'lte' => ts('Is less than or equal to'),
1651 'gte' => ts('Is greater than or equal to'),
1652 'bw' => ts('Is between'),
1653 'eq' => ts('Is equal to'),
1654 'lt' => ts('Is less than'),
1655 'gt' => ts('Is greater than'),
1656 'neq' => ts('Is not equal to'),
1657 'nbw' => ts('Is not between'),
1658 'nll' => ts('Is empty (Null)'),
1659 'nnll' => ts('Is not empty (Null)'),
1663 case CRM_Report_Form
::OP_SELECT
:
1665 'eq' => ts('Is equal to'),
1669 case CRM_Report_Form
::OP_MONTH
:
1670 case CRM_Report_Form
::OP_MULTISELECT
:
1671 case CRM_Report_Form
::OP_ENTITYREF
:
1674 'in' => ts('Is one of'),
1675 'notin' => ts('Is not one of'),
1679 case CRM_Report_Form
::OP_DATE
:
1682 'nll' => ts('Is empty (Null)'),
1683 'nnll' => ts('Is not empty (Null)'),
1687 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1688 // use this operator for the values, concatenated with separator. For e.g if
1689 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1691 'mhas' => ts('Is one of'),
1692 'mnot' => ts('Is not one of'),
1699 'has' => ts('Contains'),
1700 'sw' => ts('Starts with'),
1701 'ew' => ts('Ends with'),
1702 'nhas' => ts('Does not contain'),
1703 'eq' => ts('Is equal to'),
1704 'neq' => ts('Is not equal to'),
1705 'nll' => ts('Is empty (Null)'),
1706 'nnll' => ts('Is not empty (Null)'),
1713 * Build the tag filter field to display on the filters tab.
1715 public function buildTagFilter() {
1716 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1717 if (!empty($contactTags)) {
1718 $this->_columns
['civicrm_tag'] = array(
1719 'dao' => 'CRM_Core_DAO_Tag',
1723 'title' => ts('Tag'),
1724 'type' => CRM_Utils_Type
::T_INT
,
1726 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1727 'options' => $contactTags,
1735 * Adds group filters to _columns (called from _Construct).
1737 public function buildGroupFilter() {
1738 $this->_columns
['civicrm_group']['filters'] = array(
1740 'name' => 'group_id',
1741 'title' => ts('Group'),
1742 'type' => CRM_Utils_Type
::T_INT
,
1743 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1745 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1748 if (empty($this->_columns
['civicrm_group']['dao'])) {
1749 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1751 if (empty($this->_columns
['civicrm_group']['alias'])) {
1752 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1757 * Get SQL operator from form text version.
1759 * @param string $operator
1763 public function getSQLOperator($operator = "like") {
1764 switch ($operator) {
1797 return 'IS NOT NULL';
1806 * Generate where clause.
1808 * This can be overridden in reports for special treatment of a field
1810 * @param array $field Field specifications
1811 * @param string $op Query operator (not an exact match to sql)
1812 * @param mixed $value
1816 * @return null|string
1818 public function whereClause(&$field, $op, $value, $min, $max) {
1820 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1822 // CRM-18010: Ensure type of each report filters
1824 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1831 if (($min !== NULL && strlen($min) > 0) ||
1832 ($max !== NULL && strlen($max) > 0)
1836 $min = CRM_Utils_Type
::escape($min, $type);
1838 $clauses[] = "( {$field['dbAlias']} >= $min )";
1841 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1845 $max = CRM_Utils_Type
::escape($max, $type);
1847 $clauses[] = "( {$field['dbAlias']} <= $max )";
1850 $clauses[] = "( {$field['dbAlias']} > $max )";
1854 if (!empty($clauses)) {
1856 $clause = implode(' AND ', $clauses);
1859 $clause = '(' . implode('OR', $clauses) . ')';
1867 if ($value !== NULL && strlen($value) > 0) {
1868 $value = CRM_Utils_Type
::escape($value, $type);
1869 if (strpos($value, '%') === FALSE) {
1870 $value = "'%{$value}%'";
1873 $value = "'{$value}'";
1875 $sqlOP = $this->getSQLOperator($op);
1876 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1882 if ((is_string($value) ||
is_numeric($value)) && strlen($value)) {
1883 $value = explode(',', $value);
1885 if ($value !== NULL && is_array($value) && count($value) > 0) {
1886 $sqlOP = $this->getSQLOperator($op);
1887 if (CRM_Utils_Array
::value('type', $field) ==
1888 CRM_Utils_Type
::T_STRING
1890 //cycle through selections and escape values
1891 foreach ($value as $key => $selection) {
1892 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1895 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1899 // for numerical values
1900 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1903 if ($op == 'notin') {
1904 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1907 $clause = "( " . $clause . " )";
1914 // multiple has or multiple not
1915 if ($value !== NULL && count($value) > 0) {
1916 $value = CRM_Utils_Type
::escapeAll($value, $type);
1917 $operator = $op == 'mnot' ?
'NOT' : '';
1918 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1919 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1925 if ($value !== NULL && strlen($value) > 0) {
1926 $value = CRM_Utils_Type
::escape($value, $type);
1927 if (strpos($value, '%') === FALSE) {
1929 $value = "'{$value}%'";
1932 $value = "'%{$value}'";
1936 $value = "'{$value}'";
1938 $sqlOP = $this->getSQLOperator($op);
1939 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1945 $sqlOP = $this->getSQLOperator($op);
1946 $clause = "( {$field['dbAlias']} $sqlOP )";
1952 //CRM-18457: some custom field passes value in array format against binary operator
1953 if (is_array($value) && count($value)) {
1958 if ($value !== NULL && $value !== '') {
1959 if (isset($field['clause'])) {
1960 // FIXME: we not doing escape here. Better solution is to use two
1961 // different types - data-type and filter-type
1962 $clause = $field['clause'];
1964 elseif (!is_array($value)) {
1965 $value = CRM_Utils_Type
::escape($value, $type);
1966 $sqlOP = $this->getSQLOperator($op);
1967 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1968 $value = "'{$value}'";
1970 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1976 if (!empty($field['group']) && $clause) {
1977 $clause = $this->whereGroupClause($field, $value, $op);
1979 elseif (!empty($field['tag']) && $clause) {
1980 // not using left join in query because if any contact
1981 // belongs to more than one tag, results duplicate
1983 $clause = $this->whereTagClause($field, $value, $op);
1985 elseif (!empty($field['membership_org']) && $clause) {
1986 $clause = $this->whereMembershipOrgClause($value, $op);
1988 elseif (!empty($field['membership_type']) && $clause) {
1989 $clause = $this->whereMembershipTypeClause($value, $op);
1995 * Get SQL where clause for a date field.
1997 * @param string $fieldName
1998 * @param string $relative
1999 * @param string $from
2001 * @param string $type
2002 * @param string $fromTime
2003 * @param string $toTime
2005 * @return null|string
2007 public function dateClause(
2009 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2012 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
2013 $sqlOP = $this->getSQLOperator($relative);
2014 return "( {$fieldName} {$sqlOP} )";
2017 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2020 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
2021 $clauses[] = "( {$fieldName} >= $from )";
2025 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
2026 $clauses[] = "( {$fieldName} <= {$to} )";
2029 if (!empty($clauses)) {
2030 return implode(' AND ', $clauses);
2037 * Get values for from and to for date ranges.
2039 * @param bool $relative
2040 * @param string $from
2042 * @param string $fromTime
2043 * @param string $toTime
2047 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2048 if (empty($toTime)) {
2051 //FIX ME not working for relative
2053 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2054 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2055 $from = substr($dateRange['from'], 0, 8);
2056 //Take only Date Part, Sometime Time part is also present in 'to'
2057 $to = substr($dateRange['to'], 0, 8);
2059 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2060 $to = CRM_Utils_Date
::processDate($to, $toTime);
2061 return array($from, $to);
2065 * Alter display of rows.
2067 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2068 * such as rendering contacts as links.
2070 * @param array $rows
2071 * Rows generated by SQL, with an array for each row.
2073 public function alterDisplay(&$rows) {
2077 * Alter the way in which custom data fields are displayed.
2079 * @param array $rows
2081 public function alterCustomDataDisplay(&$rows) {
2082 // custom code to alter rows having custom values
2083 if (empty($this->_customGroupExtends
)) {
2087 $customFields = array();
2088 $customFieldIds = array();
2089 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2090 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2091 $customFieldIds[$fieldAlias] = $fieldId;
2094 if (empty($customFieldIds)) {
2098 // skip for type date and ContactReference since date format is already handled
2100 SELECT cg.table_name, cf.id
2101 FROM civicrm_custom_field cf
2102 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2103 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2104 cg.is_active = 1 AND
2105 cf.is_active = 1 AND
2106 cf.is_searchable = 1 AND
2107 cf.data_type NOT IN ('ContactReference', 'Date') AND
2108 cf.id IN (" . implode(",", $customFieldIds) . ")";
2110 $dao = CRM_Core_DAO
::executeQuery($query);
2111 while ($dao->fetch()) {
2112 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2116 $entryFound = FALSE;
2117 foreach ($rows as $rowNum => $row) {
2118 foreach ($row as $tableCol => $val) {
2119 if (array_key_exists($tableCol, $customFields)) {
2120 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2125 // skip looking further in rows, if first row itself doesn't
2126 // have the column we need
2134 * Remove duplicate rows.
2136 * @param array $rows
2138 public function removeDuplicates(&$rows) {
2139 if (empty($this->_noRepeats
)) {
2142 $checkList = array();
2144 foreach ($rows as $key => $list) {
2145 foreach ($list as $colName => $colVal) {
2146 if (array_key_exists($colName, $checkList) &&
2147 $checkList[$colName] == $colVal
2149 $rows[$key][$colName] = "";
2151 if (in_array($colName, $this->_noRepeats
)) {
2152 $checkList[$colName] = $colVal;
2159 * Fix subtotal display.
2162 * @param array $fields
2163 * @param bool $subtotal
2165 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2166 foreach ($row as $colName => $colVal) {
2167 if (in_array($colName, $fields)) {
2169 elseif (isset($this->_columnHeaders
[$colName])) {
2171 $row[$colName] = 'Subtotal';
2175 unset($row[$colName]);
2182 * Calculate grant total.
2184 * @param array $rows
2188 public function grandTotal(&$rows) {
2189 if (!$this->_rollup ||
count($rows) == 1) {
2193 $this->moveSummaryColumnsToTheRightHandSide();
2195 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2199 $this->rollupRow
= array_pop($rows);
2201 foreach ($this->_columnHeaders
as $fld => $val) {
2202 if (!in_array($fld, $this->_statFields
)) {
2203 if (!$this->_grandFlag
) {
2204 $this->rollupRow
[$fld] = ts('Grand Total');
2205 $this->_grandFlag
= TRUE;
2208 $this->rollupRow
[$fld] = "";
2213 $this->assign('grandStat', $this->rollupRow
);
2218 * Format display output.
2220 * @param array $rows
2221 * @param bool $pager
2223 public function formatDisplay(&$rows, $pager = TRUE) {
2224 // set pager based on if any limit was applied in the query.
2229 // allow building charts if any
2230 if (!empty($this->_params
['charts']) && !empty($rows)) {
2231 $this->buildChart($rows);
2232 $this->assign('chartEnabled', TRUE);
2233 $this->_chartId
= "{$this->_params['charts']}_" .
2234 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2236 $this->assign('chartId', $this->_chartId
);
2239 // unset columns not to be displayed.
2240 foreach ($this->_columnHeaders
as $key => $value) {
2241 if (!empty($value['no_display'])) {
2242 unset($this->_columnHeaders
[$key]);
2246 // unset columns not to be displayed.
2247 if (!empty($rows)) {
2248 foreach ($this->_noDisplay
as $noDisplayField) {
2249 foreach ($rows as $rowNum => $row) {
2250 unset($this->_columnHeaders
[$noDisplayField]);
2255 // build array of section totals
2256 $this->sectionTotals();
2258 // process grand-total row
2259 $this->grandTotal($rows);
2261 // use this method for formatting rows for display purpose.
2262 $this->alterDisplay($rows);
2263 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2265 // use this method for formatting custom rows for display purpose.
2266 $this->alterCustomDataDisplay($rows);
2272 * @param array $rows
2274 public function buildChart(&$rows) {
2275 // override this method for building charts.
2278 // select() method below has been added recently (v3.3), and many of the report templates might
2279 // still be having their own select() method. We should fix them as and when encountered and move
2280 // towards generalizing the select() method below.
2283 * Generate the SELECT clause and set class variable $_select.
2285 public function select() {
2286 $select = $this->_selectAliases
= array();
2287 $this->storeGroupByArray();
2289 foreach ($this->_columns
as $tableName => $table) {
2290 if (array_key_exists('fields', $table)) {
2291 foreach ($table['fields'] as $fieldName => $field) {
2292 if ($tableName == 'civicrm_address') {
2293 // deprecated, use $this->isTableSelected.
2294 $this->_addressField
= TRUE;
2296 if ($tableName == 'civicrm_email') {
2297 $this->_emailField
= TRUE;
2299 if ($tableName == 'civicrm_phone') {
2300 $this->_phoneField
= TRUE;
2303 if (!empty($field['required']) ||
2304 !empty($this->_params
['fields'][$fieldName])
2307 // 1. In many cases we want select clause to be built in slightly different way
2308 // for a particular field of a particular type.
2309 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2311 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2312 if ($selectClause) {
2313 $select[] = $selectClause;
2317 // include statistics columns only if set
2318 if (!empty($field['statistics']) && !empty($this->_groupByArray
)) {
2319 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2322 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2328 // select for group bys
2329 if (array_key_exists('group_bys', $table)) {
2330 foreach ($table['group_bys'] as $fieldName => $field) {
2332 if ($tableName == 'civicrm_address') {
2333 $this->_addressField
= TRUE;
2335 if ($tableName == 'civicrm_email') {
2336 $this->_emailField
= TRUE;
2338 if ($tableName == 'civicrm_phone') {
2339 $this->_phoneField
= TRUE;
2341 // 1. In many cases we want select clause to be built in slightly different way
2342 // for a particular field of a particular type.
2343 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2345 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2346 if ($selectClause) {
2347 $select[] = $selectClause;
2351 if (!empty($this->_params
['group_bys']) &&
2352 !empty($this->_params
['group_bys'][$fieldName]) &&
2353 !empty($this->_params
['group_bys_freq'])
2355 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2357 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2358 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2359 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2360 $field['title'] = 'Week';
2364 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2365 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2366 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2367 $field['title'] = 'Year';
2371 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2372 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2373 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2374 $field['title'] = 'Month';
2378 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2379 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2380 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2381 $field['title'] = 'Quarter';
2384 // for graphs and charts -
2385 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2386 $this->_interval
= $field['title'];
2387 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2388 = $field['title'] . ' Beginning';
2389 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2390 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2392 // just to make sure these values are transferred to rows.
2393 // since we 'll need them for calculation purpose,
2394 // e.g making subtotals look nicer or graphs
2395 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2396 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2403 if (empty($select)) {
2404 // CRM-21412 Do not give fatal error on report when no fields selected
2408 $this->_selectClauses
= $select;
2409 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2413 * Build select clause for a single field.
2415 * @param string $tableName
2416 * @param string $tableKey
2417 * @param string $fieldName
2418 * @param string $field
2422 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2427 * Build where clause.
2429 public function where() {
2430 $this->storeWhereHavingClauseArray();
2432 if (empty($this->_whereClauses
)) {
2433 $this->_where
= "WHERE ( 1 ) ";
2434 $this->_having
= "";
2437 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2440 if ($this->_aclWhere
) {
2441 $this->_where
.= " AND {$this->_aclWhere} ";
2444 if (!empty($this->_havingClauses
)) {
2445 // use this clause to construct group by clause.
2446 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2451 * Store Where clauses into an array.
2453 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2454 * temp table that may not be part of the final where clause or added
2455 * in other functions
2457 public function storeWhereHavingClauseArray() {
2458 foreach ($this->_columns
as $tableName => $table) {
2459 if (array_key_exists('filters', $table)) {
2460 foreach ($table['filters'] as $fieldName => $field) {
2461 // respect pseudofield to filter spec so fields can be marked as
2462 // not to be handled here
2463 if (!empty($field['pseudofield'])) {
2467 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2468 if (CRM_Utils_Array
::value('operatorType', $field) ==
2469 CRM_Report_Form
::OP_MONTH
2471 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2472 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2473 if (is_array($value) && !empty($value)) {
2475 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2480 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2481 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2482 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2483 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2484 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2485 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2489 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2491 $clause = $this->whereClause($field,
2493 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2494 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2495 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2500 if (!empty($clause)) {
2501 if (!empty($field['having'])) {
2502 $this->_havingClauses
[] = $clause;
2505 $this->_whereClauses
[] = $clause;
2517 public function processReportMode() {
2518 $this->setOutputMode();
2521 = CRM_Utils_Request
::retrieve(
2524 CRM_Core_DAO
::$_nullObject
2527 $this->_absoluteUrl
= FALSE;
2529 $this->assign('printOnly', FALSE);
2531 if ($this->_outputMode
== 'print' ||
2532 ($this->_sendmail
&& !$this->_outputMode
)
2534 $this->assign('printOnly', TRUE);
2536 $this->addPaging
= FALSE;
2537 $this->assign('outputMode', 'print');
2538 $this->_outputMode
= 'print';
2539 if ($this->_sendmail
) {
2540 $this->_absoluteUrl
= TRUE;
2543 elseif ($this->_outputMode
== 'pdf') {
2545 $this->addPaging
= FALSE;
2546 $this->_absoluteUrl
= TRUE;
2548 elseif ($this->_outputMode
== 'csv') {
2550 $this->_absoluteUrl
= TRUE;
2551 $this->addPaging
= FALSE;
2553 elseif ($this->_outputMode
== 'group') {
2554 $this->assign('outputMode', 'group');
2556 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2557 $this->assign('outputMode', 'create_report');
2559 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2560 $this->_createNew
= TRUE;
2563 $this->assign('outputMode', $this->_outputMode
);
2564 $this->assign('printOnly', $printOnly);
2565 // Get today's date to include in printed reports
2567 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2568 $this->assign('reportDate', $reportDate);
2573 * Post Processing function for Form.
2575 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2576 * This function is not accessed when the api calls the report.
2578 public function beginPostProcess() {
2579 $this->setParams($this->controller
->exportValues($this->_name
));
2580 if (empty($this->_params
) &&
2583 $this->setParams($this->_formValues
);
2586 // hack to fix params when submitted from dashboard, CRM-8532
2587 // fields array is missing because form building etc is skipped
2588 // in dashboard mode for report
2589 //@todo - this could be done in the dashboard no we have a setter
2590 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2591 $this->setParams($this->_formValues
);
2594 $this->processReportMode();
2596 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2597 $this->_createNew
= ($this->_outputMode
== 'copy');
2598 CRM_Report_Form_Instance
::postProcess($this);
2600 if ($this->_outputMode
== 'delete') {
2601 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2604 $this->_formValues
= $this->_params
;
2606 $this->beginPostProcessCommon();
2610 * BeginPostProcess function run in both report mode and non-report mode (api).
2612 public function beginPostProcessCommon() {
2616 * Build the report query.
2618 * @param bool $applyLimit
2622 public function buildQuery($applyLimit = TRUE) {
2623 $this->buildGroupTempTable();
2626 $this->customDataFrom();
2627 $this->buildPermissionClause();
2632 // order_by columns not selected for display need to be included in SELECT
2633 $unselectedSectionColumns = $this->unselectedSectionColumns();
2634 foreach ($unselectedSectionColumns as $alias => $section) {
2635 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2638 if ($applyLimit && empty($this->_params
['charts'])) {
2641 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2643 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2644 $this->addToDeveloperTab($sql);
2649 * Build group by clause.
2651 public function groupBy() {
2652 $this->storeGroupByArray();
2654 if (!empty($this->_groupByArray
)) {
2655 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $this->_groupByArray
);
2660 * Build order by clause.
2662 public function orderBy() {
2663 $this->_orderBy
= "";
2664 $this->_sections
= array();
2665 $this->storeOrderByArray();
2666 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2667 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2669 $this->assign('sections', $this->_sections
);
2673 * Extract order by fields and store as an array.
2675 * In some cases other functions want to know which fields are selected for ordering by
2676 * Separating this into a separate function allows it to be called separately from constructing
2677 * the order by clause
2679 public function storeOrderByArray() {
2680 $orderBys = array();
2682 if (!empty($this->_params
['order_bys']) &&
2683 is_array($this->_params
['order_bys']) &&
2684 !empty($this->_params
['order_bys'])
2687 // Process order_bys in user-specified order
2688 foreach ($this->_params
['order_bys'] as $orderBy) {
2689 $orderByField = array();
2690 foreach ($this->_columns
as $tableName => $table) {
2691 if (array_key_exists('order_bys', $table)) {
2692 // For DAO columns defined in $this->_columns
2693 $fields = $table['order_bys'];
2695 elseif (array_key_exists('extends', $table)) {
2696 // For custom fields referenced in $this->_customGroupExtends
2697 $fields = CRM_Utils_Array
::value('fields', $table, array());
2702 if (!empty($fields) && is_array($fields)) {
2703 foreach ($fields as $fieldName => $field) {
2704 if ($fieldName == $orderBy['column']) {
2705 $orderByField = array_merge($field, $orderBy);
2706 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2713 if (!empty($orderByField)) {
2714 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2715 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2717 // Record any section headers for assignment to the template
2718 if (!empty($orderBy['section'])) {
2719 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2720 $this->_sections
[$orderByField['tplField']] = $orderByField;
2726 $this->_orderByArray
= $orderBys;
2728 $this->assign('sections', $this->_sections
);
2732 * Determine unselected columns.
2736 public function unselectedSectionColumns() {
2737 if (is_array($this->_sections
)) {
2738 return array_diff_key($this->_sections
, $this->getSelectColumns());
2746 * Build output rows.
2748 * @param string $sql
2749 * @param array $rows
2751 public function buildRows($sql, &$rows) {
2752 $dao = CRM_Core_DAO
::executeQuery($sql);
2753 if (!is_array($rows)) {
2757 // use this method to modify $this->_columnHeaders
2758 $this->modifyColumnHeaders();
2760 $unselectedSectionColumns = $this->unselectedSectionColumns();
2762 while ($dao->fetch()) {
2764 foreach ($this->_columnHeaders
as $key => $value) {
2765 if (property_exists($dao, $key)) {
2766 $row[$key] = $dao->$key;
2770 // section headers not selected for display need to be added to row
2771 foreach ($unselectedSectionColumns as $key => $values) {
2772 if (property_exists($dao, $key)) {
2773 $row[$key] = $dao->$key;
2782 * Calculate section totals.
2784 * When "order by" fields are marked as sections, this assigns to the template
2785 * an array of total counts for each section. This data is used by the Smarty
2786 * plugin {sectionTotal}.
2788 public function sectionTotals() {
2790 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2791 if (empty($this->_selectAliases
)) {
2795 if (!empty($this->_sections
)) {
2796 // build the query with no LIMIT clause
2797 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2798 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2800 // pull section aliases out of $this->_sections
2801 $sectionAliases = array_keys($this->_sections
);
2804 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2805 $ifnulls[] = "ifnull($alias, '') as $alias";
2807 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2808 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2810 // Group (un-limited) report by all aliases and get counts. This might
2811 // be done more efficiently when the contents of $sql are known, ie. by
2812 // overriding this method in the report class.
2814 $query = $this->_select
.
2815 ", count(*) as ct from ($sql) as subquery group by " .
2816 implode(", ", $sectionAliases);
2818 // initialize array of total counts
2820 $dao = CRM_Core_DAO
::executeQuery($query);
2821 while ($dao->fetch()) {
2823 // let $this->_alterDisplay translate any integer ids to human-readable values.
2824 $rows[0] = $dao->toArray();
2825 $this->alterDisplay($rows);
2828 // add totals for all permutations of section values
2831 $aliasCount = count($sectionAliases);
2832 foreach ($sectionAliases as $alias) {
2833 $values[] = $row[$alias];
2834 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2835 if ($i == $aliasCount) {
2836 // the last alias is the lowest-level section header; use count as-is
2837 $totals[$key] = $dao->ct
;
2840 // other aliases are higher level; roll count into their total
2841 $totals[$key] +
= $dao->ct
;
2845 $this->assign('sectionTotals', $totals);
2850 * Modify column headers.
2852 public function modifyColumnHeaders() {
2853 // use this method to modify $this->_columnHeaders
2857 * Move totals columns to the right edge of the table.
2859 * It seems like a more logical layout to have any totals columns on the far right regardless of
2860 * the location of the rest of their table.
2862 public function moveSummaryColumnsToTheRightHandSide() {
2863 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2864 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2868 * Assign rows to the template.
2870 * @param array $rows
2872 public function doTemplateAssignment(&$rows) {
2873 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2874 $this->assign_by_ref('rows', $rows);
2875 $this->assign('statistics', $this->statistics($rows));
2879 * Build report statistics.
2881 * Override this method to build your own statistics.
2883 * @param array $rows
2887 public function statistics(&$rows) {
2888 $statistics = array();
2890 $count = count($rows);
2891 // Why do we increment the count for rollup seems to artificially inflate the count.
2892 // It seems perhaps intentional to include the summary row in the count of results - although
2893 // this just seems odd.
2894 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2898 $this->countStat($statistics, $count);
2900 $this->groupByStat($statistics);
2902 $this->filterStat($statistics);
2908 * Add count statistics.
2910 * @param array $statistics
2913 public function countStat(&$statistics, $count) {
2914 $statistics['counts']['rowCount'] = array(
2915 'title' => ts('Row(s) Listed'),
2919 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2920 $statistics['counts']['rowsFound'] = array(
2921 'title' => ts('Total Row(s)'),
2922 'value' => $this->_rowsFound
,
2928 * Add group by statistics.
2930 * @param array $statistics
2932 public function groupByStat(&$statistics) {
2933 if (!empty($this->_params
['group_bys']) &&
2934 is_array($this->_params
['group_bys']) &&
2935 !empty($this->_params
['group_bys'])
2937 foreach ($this->_columns
as $tableName => $table) {
2938 if (array_key_exists('group_bys', $table)) {
2939 foreach ($table['group_bys'] as $fieldName => $field) {
2940 if (!empty($this->_params
['group_bys'][$fieldName])) {
2941 $combinations[] = $field['title'];
2946 $statistics['groups'][] = array(
2947 'title' => ts('Grouping(s)'),
2948 'value' => implode(' & ', $combinations),
2954 * Filter statistics.
2956 * @param array $statistics
2958 public function filterStat(&$statistics) {
2959 foreach ($this->_columns
as $tableName => $table) {
2960 if (array_key_exists('filters', $table)) {
2961 foreach ($table['filters'] as $fieldName => $field) {
2962 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2963 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2964 CRM_Utils_Array
::value('operatorType', $field) !=
2965 CRM_Report_Form
::OP_MONTH
2969 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2970 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2971 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2972 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2973 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2975 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2976 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2978 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2979 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2982 $statistics['filters'][] = array(
2983 'title' => $field['title'],
2984 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2987 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2988 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2990 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2991 $statistics['filters'][] = array(
2992 'title' => $field['title'],
2993 'value' => $pair[$rel],
2998 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3001 $pair = $this->getOperationPair(
3002 CRM_Utils_Array
::value('operatorType', $field),
3005 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3006 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3007 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3008 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3009 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3011 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3012 $this->setEntityRefDefaults($field, $tableName);
3013 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3014 array('id' => $val) +
3015 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3017 foreach ($result['values'] as $v) {
3018 $values[] = $v['label'];
3020 $value = "{$pair[$op]} " . implode(', ', $values);
3022 elseif ($op == 'nll' ||
$op == 'nnll') {
3023 $value = $pair[$op];
3025 elseif (is_array($val) && (!empty($val))) {
3026 $options = CRM_Utils_Array
::value('options', $field, array());
3027 foreach ($val as $key => $valIds) {
3028 if (isset($options[$valIds])) {
3029 $val[$key] = $options[$valIds];
3032 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3033 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3034 $val = implode(', ', $val);
3035 $value = "{$pair[$op]} " . $val;
3037 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3038 isset($field['options']) &&
3039 is_array($field['options']) && !empty($field['options'])
3041 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3042 CRM_Utils_Array
::value($val, $field['options'], $val);
3045 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3048 if ($value && empty($field['no_display'])) {
3049 $statistics['filters'][] = array(
3050 'title' => CRM_Utils_Array
::value('title', $field),
3061 * End post processing.
3063 * @param array|null $rows
3065 public function endPostProcess(&$rows = NULL) {
3066 $this->assign('report_class', get_class($this));
3067 if ($this->_storeResultSet
) {
3068 $this->_resultSet
= $rows;
3071 if ($this->_outputMode
== 'print' ||
3072 $this->_outputMode
== 'pdf' ||
3076 $content = $this->compileContent();
3077 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3081 if ($this->_sendmail
) {
3082 $config = CRM_Core_Config
::singleton();
3083 $attachments = array();
3085 if ($this->_outputMode
== 'csv') {
3087 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3088 ": {$url}</p>" . '<p>' .
3089 ts('The report is attached as a CSV file.') . '</p>' .
3090 $this->_formValues
['report_footer'];
3092 $csvFullFilename = $config->templateCompileDir
.
3093 CRM_Utils_File
::makeFileName('CiviReport.csv');
3094 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3095 file_put_contents($csvFullFilename, $csvContent);
3096 $attachments[] = array(
3097 'fullPath' => $csvFullFilename,
3098 'mime_type' => 'text/csv',
3099 'cleanName' => 'CiviReport.csv',
3102 if ($this->_outputMode
== 'pdf') {
3103 // generate PDF content
3104 $pdfFullFilename = $config->templateCompileDir
.
3105 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3106 file_put_contents($pdfFullFilename,
3107 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3108 TRUE, array('orientation' => 'landscape')
3111 // generate Email Content
3113 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3114 ": {$url}</p>" . '<p>' .
3115 ts('The report is attached as a PDF file.') . '</p>' .
3116 $this->_formValues
['report_footer'];
3118 $attachments[] = array(
3119 'fullPath' => $pdfFullFilename,
3120 'mime_type' => 'application/pdf',
3121 'cleanName' => 'CiviReport.pdf',
3125 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3126 $this->_outputMode
, $attachments
3129 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3132 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3136 elseif ($this->_outputMode
== 'print') {
3140 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3141 $config = CRM_Core_Config
::singleton();
3142 //get chart image name
3143 $chartImg = $this->_chartId
. '.png';
3144 //get image url path
3146 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3148 $uploadUrl .= $chartImg;
3149 //get image doc path to overwrite
3151 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3152 'openFlashChart/' . $chartImg;
3154 $chart = imagecreatefrompng($uploadUrl);
3155 //convert it into formatted png
3156 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3157 //overwrite with same image
3158 imagepng($chart, $uploadImg);
3160 imagedestroy($chart);
3162 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3164 CRM_Utils_System
::civiExit();
3166 elseif ($this->_outputMode
== 'csv') {
3167 CRM_Report_Utils_Report
::export2csv($this, $rows);
3169 elseif ($this->_outputMode
== 'group') {
3170 $group = $this->_params
['groups'];
3171 $this->add2group($group);
3176 * Set store result set indicator to TRUE.
3178 * @todo explain what this does
3180 public function storeResultSet() {
3181 $this->_storeResultSet
= TRUE;
3189 public function getResultSet() {
3190 return $this->_resultSet
;
3194 * Get the sql used to generate the report.
3198 public function getReportSql() {
3199 return $this->sqlArray
;
3203 * Use the form name to create the tpl file name.
3207 public function getTemplateFileName() {
3208 $defaultTpl = parent
::getTemplateFileName();
3209 $template = CRM_Core_Smarty
::singleton();
3210 if (!$template->template_exists($defaultTpl)) {
3211 $defaultTpl = 'CRM/Report/Form.tpl';
3217 * Compile the report content.
3219 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3223 public function compileContent() {
3224 $templateFile = $this->getHookedTemplateFileName();
3225 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3226 CRM_Core_Form
::$_template->fetch($templateFile) .
3227 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3232 * Post process function.
3234 public function postProcess() {
3235 // get ready with post process params
3236 $this->beginPostProcess();
3239 $sql = $this->buildQuery();
3241 // build array of result based on column headers. This method also allows
3242 // modifying column headers before using it to build result set i.e $rows.
3244 $this->buildRows($sql, $rows);
3246 // format result set.
3247 $this->formatDisplay($rows);
3249 // assign variables to templates
3250 $this->doTemplateAssignment($rows);
3252 // do print / pdf / instance stuff if needed
3253 $this->endPostProcess($rows);
3259 * @param int $rowCount
3263 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3264 // lets do the pager if in html mode
3265 $this->_limit
= NULL;
3267 // CRM-14115, over-ride row count if rowCount is specified in URL
3268 if ($this->_dashBoardRowCount
) {
3269 $rowCount = $this->_dashBoardRowCount
;
3271 if ($this->addPaging
) {
3272 $this->_select
= preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3274 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer');
3276 // @todo all http vars should be extracted in the preProcess
3277 // - not randomly in the class
3278 if (!$pageId && !empty($_POST)) {
3279 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3280 $pageId = max((int) $_POST['crmPID_B'], 1);
3282 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3283 $pageId = max((int) $_POST['crmPID'], 1);
3285 unset($_POST['crmPID_B'], $_POST['crmPID']);
3288 $pageId = $pageId ?
$pageId : 1;
3289 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3290 $offset = ($pageId - 1) * $rowCount;
3292 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3293 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3295 $this->_limit
= " LIMIT $offset, $rowCount";
3296 return array($offset, $rowCount);
3298 if ($this->_limitValue
) {
3299 if ($this->_offsetValue
) {
3300 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3303 $this->_limit
= " LIMIT " . $this->_limitValue
;
3311 * @param int $rowCount
3313 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3314 // CRM-14115, over-ride row count if rowCount is specified in URL
3315 if ($this->_dashBoardRowCount
) {
3316 $rowCount = $this->_dashBoardRowCount
;
3319 if ($this->_limit
&& ($this->_limit
!= '')) {
3320 if (!$this->_rowsFound
) {
3321 $sql = "SELECT FOUND_ROWS();";
3322 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3325 'total' => $this->_rowsFound
,
3326 'rowCount' => $rowCount,
3327 'status' => ts('Records') . ' %%StatusMessage%%',
3328 'buttonBottom' => 'PagerBottomButton',
3329 'buttonTop' => 'PagerTopButton',
3331 if (!empty($this->controller
)) {
3332 // This happens when being called from the api Really we want the api to be able to
3333 // pass paging parameters, but at this stage just preventing test crashes.
3334 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3337 $pager = new CRM_Utils_Pager($params);
3338 $this->assign_by_ref('pager', $pager);
3339 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3344 * Build a group filter with contempt for large data sets.
3346 * This function has been retained as it takes time to migrate the reports over
3347 * to the new method which will not crash on large datasets.
3351 * @param string $field
3352 * @param mixed $value
3357 public function legacySlowGroupFilterClause($field, $value, $op) {
3358 $smartGroupQuery = "";
3360 $group = new CRM_Contact_DAO_Group();
3361 $group->is_active
= 1;
3363 $smartGroups = array();
3364 while ($group->fetch()) {
3365 if (in_array($group->id
, (array) $this->_params
['gid_value']) &&
3366 $group->saved_search_id
3368 $smartGroups[] = $group->id
;
3372 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3374 $smartGroupQuery = '';
3375 if (!empty($smartGroups)) {
3376 $smartGroups = implode(',', $smartGroups);
3377 $smartGroupQuery = " UNION DISTINCT
3378 SELECT DISTINCT smartgroup_contact.contact_id
3379 FROM civicrm_group_contact_cache smartgroup_contact
3380 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3383 $sqlOp = $this->getSQLOperator($op);
3384 if (!is_array($value)) {
3385 $value = array($value);
3387 //include child groups if any
3388 $value = array_merge($value, CRM_Contact_BAO_Group
::getChildGroupIds($value));
3390 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3392 $contactAlias = $this->_aliases
['civicrm_contact'];
3393 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3394 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3396 return " {$contactAlias}.id {$sqlOp} (
3397 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3398 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3399 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3400 {$smartGroupQuery} ) ";
3404 * Build where clause for groups.
3406 * @param string $field
3407 * @param mixed $value
3412 public function whereGroupClause($field, $value, $op) {
3413 if ($this->groupFilterNotOptimised
) {
3414 return $this->legacySlowGroupFilterClause($field, $value, $op);
3416 if ($op === 'notin') {
3417 return " group_temp_table.id IS NULL ";
3419 // We will have used an inner join instead.
3425 * Create a table of the contact ids included by the group filter.
3427 * This function is called by both the api (tests) and the UI.
3429 public function buildGroupTempTable() {
3430 if (!empty($this->groupTempTable
) ||
empty($this->_params
['gid_value']) ||
$this->groupFilterNotOptimised
) {
3433 $filteredGroups = (array) $this->_params
['gid_value'];
3435 $groups = civicrm_api3('Group', 'get', array(
3437 'id' => array('IN' => $filteredGroups),
3438 'saved_search_id' => array('>' => 0),
3441 $smartGroups = array_keys($groups['values']);
3444 SELECT DISTINCT group_contact.contact_id as id
3445 FROM civicrm_group_contact group_contact
3446 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3447 AND group_contact.status = 'Added' ";
3449 if (!empty($smartGroups)) {
3450 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3451 $smartGroups = implode(',', $smartGroups);
3454 SELECT smartgroup_contact.contact_id as id
3455 FROM civicrm_group_contact_cache smartgroup_contact
3456 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3459 $this->groupTempTable
= 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3460 $this->executeReportQuery("
3461 CREATE TEMPORARY TABLE $this->groupTempTable $this->_databaseAttributes
3464 CRM_Core_DAO
::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3468 * Execute query and add it to the developer tab.
3470 * @param string $query
3471 * @param array $params
3473 * @return \CRM_Core_DAO|object
3475 protected function executeReportQuery($query, $params = array()) {
3476 $this->addToDeveloperTab($query);
3477 return CRM_Core_DAO
::executeQuery($query, $params);
3481 * Build where clause for tags.
3483 * @param string $field
3484 * @param mixed $value
3489 public function whereTagClause($field, $value, $op) {
3490 // not using left join in query because if any contact
3491 // belongs to more than one tag, results duplicate
3493 $sqlOp = $this->getSQLOperator($op);
3494 if (!is_array($value)) {
3495 $value = array($value);
3497 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3498 $entity_table = $this->_tagFilterTable
;
3499 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3500 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3501 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3502 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3506 * Generate membership organization clause.
3508 * @param mixed $value
3509 * @param string $op SQL Operator
3513 public function whereMembershipOrgClause($value, $op) {
3514 $sqlOp = $this->getSQLOperator($op);
3515 if (!is_array($value)) {
3516 $value = array($value);
3519 $tmp_membership_org_sql_list = implode(', ', $value);
3520 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3521 SELECT DISTINCT mem.contact_id
3522 FROM civicrm_membership mem
3523 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3524 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3525 WHERE mt.member_of_contact_id IN (" .
3526 $tmp_membership_org_sql_list . ")
3527 AND mt.is_active = '1'
3528 AND mem_status.is_current_member = '1'
3529 AND mem_status.is_active = '1' ) ";
3533 * Generate Membership Type SQL Clause.
3535 * @param mixed $value
3541 public function whereMembershipTypeClause($value, $op) {
3542 $sqlOp = $this->getSQLOperator($op);
3543 if (!is_array($value)) {
3544 $value = array($value);
3547 $tmp_membership_sql_list = implode(', ', $value);
3548 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3549 SELECT DISTINCT mem.contact_id
3550 FROM civicrm_membership mem
3551 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3552 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3553 WHERE mem.membership_type_id IN (" .
3554 $tmp_membership_sql_list . ")
3555 AND mt.is_active = '1'
3556 AND mem_status.is_current_member = '1'
3557 AND mem_status.is_active = '1' ) ";
3561 * Buld contact acl clause
3562 * @deprecated in favor of buildPermissionClause
3564 * @param string $tableAlias
3566 public function buildACLClause($tableAlias = 'contact_a') {
3567 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3571 * Build the permision clause for all entities in this report
3573 public function buildPermissionClause() {
3575 foreach ($this->selectedTables() as $tableName) {
3576 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables
::getClassForTable($tableName));
3577 if ($baoName && class_exists($baoName) && !empty($this->_columns
[$tableName]['alias'])) {
3578 $tableAlias = $this->_columns
[$tableName]['alias'];
3579 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3580 foreach ($clauses as $field => $clause) {
3581 // Skip contact_id field if redundant
3582 if ($field != 'contact_id' ||
!in_array('civicrm_contact', $this->selectedTables())) {
3583 $ret["$tableName.$field"] = $clause;
3588 // Override output from buildACLClause
3589 $this->_aclFrom
= NULL;
3590 $this->_aclWhere
= implode(' AND ', $ret);
3594 * Add custom data to the columns.
3596 * @param bool $addFields
3597 * @param array $permCustomGroupIds
3599 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3600 if (empty($this->_customGroupExtends
)) {
3603 if (!is_array($this->_customGroupExtends
)) {
3604 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3606 $customGroupWhere = '';
3607 if (!empty($permCustomGroupIds)) {
3608 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3612 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3613 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3614 FROM civicrm_custom_group cg
3615 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3616 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3618 cg.is_active = 1 AND
3619 cf.is_active = 1 AND
3620 cf.is_searchable = 1
3621 ORDER BY cg.weight, cf.weight";
3622 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3625 while ($customDAO->fetch()) {
3626 if ($customDAO->table_name
!= $curTable) {
3627 $curTable = $customDAO->table_name
;
3628 $curFields = $curFilters = array();
3631 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3632 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3633 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3634 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3636 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3637 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3638 $this->_columns
[$curTable][$colKey] = array();
3642 $fieldName = 'custom_' . $customDAO->cf_id
;
3645 // this makes aliasing work in favor
3646 $curFields[$fieldName] = array(
3647 'name' => $customDAO->column_name
,
3648 'title' => $customDAO->label
,
3649 'dataType' => $customDAO->data_type
,
3650 'htmlType' => $customDAO->html_type
,
3653 if ($this->_customGroupFilters
) {
3654 // this makes aliasing work in favor
3655 $curFilters[$fieldName] = array(
3656 'name' => $customDAO->column_name
,
3657 'title' => $customDAO->label
,
3658 'dataType' => $customDAO->data_type
,
3659 'htmlType' => $customDAO->html_type
,
3663 switch ($customDAO->data_type
) {
3666 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3667 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3668 // CRM-6946, show time part for datetime date fields
3669 if ($customDAO->time_format
) {
3670 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3675 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3676 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3677 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3681 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3682 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3686 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3687 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3688 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3692 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3693 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3697 case 'StateProvince':
3699 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3701 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3702 if ($options !== FALSE) {
3703 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3704 $curFilters[$fieldName]['options'] = $options;
3708 case 'ContactReference':
3709 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3710 $curFilters[$fieldName]['name'] = 'display_name';
3711 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3713 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3714 $curFields[$fieldName]['name'] = 'display_name';
3715 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3719 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3720 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3724 if ($customDAO->html_type
== 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3725 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3726 if ($options !== FALSE) {
3727 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3728 $curFilters[$fieldName]['options'] = $options;
3732 if (!array_key_exists('type', $curFields[$fieldName])) {
3733 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3737 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3739 if ($this->_customGroupFilters
) {
3740 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3742 if ($this->_customGroupGroupBy
) {
3743 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3749 * Build custom data from clause.
3751 * @param bool $joinsForFiltersOnly
3752 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3754 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3755 if (empty($this->_customGroupExtends
)) {
3758 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3759 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3760 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3761 $customTables = array();
3762 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3763 while ($customTablesDAO->fetch()) {
3764 $customTables[] = $customTablesDAO->table_name
;
3767 foreach ($this->_columns
as $table => $prop) {
3768 if (in_array($table, $customTables)) {
3769 $extendsTable = $mapper[$prop['extends']];
3770 // Check field is required for rendering the report.
3771 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3774 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3776 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3778 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3779 // handle for ContactReference
3780 if (array_key_exists('fields', $prop)) {
3781 foreach ($prop['fields'] as $fieldName => $field) {
3782 if (CRM_Utils_Array
::value('dataType', $field) ==
3785 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3787 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3796 * Check if the field is selected.
3798 * @param string $prop
3802 public function isFieldSelected($prop) {
3807 if (!empty($this->_params
['fields'])) {
3808 foreach (array_keys($prop['fields']) as $fieldAlias) {
3809 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3810 if ($customFieldId) {
3811 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3815 //might be survey response field.
3816 if (!empty($this->_params
['fields']['survey_response']) &&
3817 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3825 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3826 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3827 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3828 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3835 if (!empty($this->_params
['order_bys'])) {
3836 foreach (array_keys($prop['fields']) as $fieldAlias) {
3837 foreach ($this->_params
['order_bys'] as $orderBy) {
3838 if ($fieldAlias == $orderBy['column'] &&
3839 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3846 return $this->isFieldFiltered($prop);
3851 * Check if the field is used as a filter.
3853 * @param string $prop
3857 protected function isFieldFiltered($prop) {
3858 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3859 foreach ($prop['filters'] as $fieldAlias => $val) {
3868 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3869 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3870 ||
($attach != 'relative' &&
3871 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3877 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3878 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3889 * Check for empty order_by configurations and remove them.
3891 * Also set template to hide them.
3893 * @param array $formValues
3895 public function preProcessOrderBy(&$formValues) {
3896 // Object to show/hide form elements
3897 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3899 $_showHide->addShow('optionField_1');
3901 // Cycle through order_by options; skip any empty ones, and hide them as well
3904 if (!empty($formValues['order_bys'])) {
3905 foreach ($formValues['order_bys'] as $order_by) {
3906 if ($order_by['column'] && $order_by['column'] != '-') {
3907 $_showHide->addShow('optionField_' . $n);
3908 $orderBys[$n] = $order_by;
3913 for ($i = $n; $i <= 5; $i++
) {
3915 $_showHide->addHide('optionField_' . $i);
3919 // overwrite order_by options with modified values
3920 if (!empty($orderBys)) {
3921 $formValues['order_bys'] = $orderBys;
3924 $formValues['order_bys'] = array(1 => array('column' => '-'));
3927 // assign show/hide data to template
3928 $_showHide->addToTemplate();
3932 * Check if table name has columns in SELECT clause.
3934 * @param string $tableName
3935 * Name of table (index of $this->_columns array).
3939 public function isTableSelected($tableName) {
3940 return in_array($tableName, $this->selectedTables());
3944 * Check if table name has columns in WHERE or HAVING clause.
3946 * @param string $tableName
3947 * Name of table (index of $this->_columns array).
3951 public function isTableFiltered($tableName) {
3952 // Cause the array to be generated if not previously done.
3953 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3954 $this->selectedTables();
3956 return in_array($tableName, $this->filteredTables
);
3960 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3962 * If the array is unset it will be built.
3967 public function selectedTables() {
3968 if (!$this->_selectedTables
) {
3969 $orderByColumns = array();
3970 if (array_key_exists('order_bys', $this->_params
) &&
3971 is_array($this->_params
['order_bys'])
3973 foreach ($this->_params
['order_bys'] as $orderBy) {
3974 $orderByColumns[] = $orderBy['column'];
3978 foreach ($this->_columns
as $tableName => $table) {
3979 if (array_key_exists('fields', $table)) {
3980 foreach ($table['fields'] as $fieldName => $field) {
3981 if (!empty($field['required']) ||
3982 !empty($this->_params
['fields'][$fieldName])
3984 $this->_selectedTables
[] = $tableName;
3989 if (array_key_exists('order_bys', $table)) {
3990 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3991 if (in_array($orderByName, $orderByColumns)) {
3992 $this->_selectedTables
[] = $tableName;
3997 if (array_key_exists('filters', $table)) {
3998 foreach ($table['filters'] as $filterName => $filter) {
3999 if (!empty($this->_params
["{$filterName}_value"]) ||
4000 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4002 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4005 $this->_selectedTables
[] = $tableName;
4006 $this->filteredTables
[] = $tableName;
4013 return $this->_selectedTables
;
4017 * Add address fields.
4019 * @deprecated - use getAddressColumns which is a more accurate description
4020 * and also accepts an array of options rather than a long list
4022 * adding address fields to construct function in reports
4024 * @param bool $groupBy
4025 * Add GroupBy? Not appropriate for detail report.
4026 * @param bool $orderBy
4027 * Add GroupBy? Not appropriate for detail report.
4028 * @param bool $filters
4029 * @param array $defaults
4032 * address fields for construct clause
4034 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4035 $defaultAddressFields = array(
4036 'street_address' => ts('Street Address'),
4037 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4038 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4039 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4040 'street_number' => ts('Street Number'),
4041 'street_name' => ts('Street Name'),
4042 'street_unit' => ts('Street Unit'),
4043 'city' => ts('City'),
4044 'postal_code' => ts('Postal Code'),
4045 'postal_code_suffix' => ts('Postal Code Suffix'),
4046 'country_id' => ts('Country'),
4047 'state_province_id' => ts('State/Province'),
4048 'county_id' => ts('County'),
4050 $addressFields = array(
4051 'civicrm_address' => array(
4052 'dao' => 'CRM_Core_DAO_Address',
4054 'address_name' => array(
4055 'title' => ts('Address Name'),
4056 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4060 'grouping' => 'location-fields',
4063 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4064 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4065 'title' => $fieldLabel,
4066 'default' => CRM_Utils_Array
::value($fieldName, $defaults, FALSE),
4070 $street_address_filters = $general_address_filters = array();
4072 // Address filter depends on whether street address parsing is enabled.
4074 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4077 if ($addressOptions['street_address_parsing']) {
4078 $street_address_filters = array(
4079 'street_number' => array(
4080 'title' => ts('Street Number'),
4081 'type' => CRM_Utils_Type
::T_INT
,
4082 'name' => 'street_number',
4084 'street_name' => array(
4085 'title' => ts('Street Name'),
4086 'name' => 'street_name',
4087 'type' => CRM_Utils_Type
::T_STRING
,
4092 $street_address_filters = array(
4093 'street_address' => array(
4094 'title' => ts('Street Address'),
4095 'type' => CRM_Utils_Type
::T_STRING
,
4096 'name' => 'street_address',
4100 $general_address_filters = array(
4101 'postal_code' => array(
4102 'title' => ts('Postal Code'),
4103 'type' => CRM_Utils_Type
::T_STRING
,
4104 'name' => 'postal_code',
4107 'title' => ts('City'),
4108 'type' => CRM_Utils_Type
::T_STRING
,
4111 'country_id' => array(
4112 'name' => 'country_id',
4113 'title' => ts('Country'),
4114 'type' => CRM_Utils_Type
::T_INT
,
4115 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4116 'options' => CRM_Core_PseudoConstant
::country(),
4118 'state_province_id' => array(
4119 'name' => 'state_province_id',
4120 'title' => ts('State/Province'),
4121 'type' => CRM_Utils_Type
::T_INT
,
4122 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4123 'options' => array(),
4125 'county_id' => array(
4126 'name' => 'county_id',
4127 'title' => ts('County'),
4128 'type' => CRM_Utils_Type
::T_INT
,
4129 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4130 'options' => array(),
4134 $addressFields['civicrm_address']['filters'] = array_merge(
4135 $street_address_filters,
4136 $general_address_filters);
4139 $addressFields['civicrm_address']['order_bys'] = array(
4140 'street_name' => array('title' => ts('Street Name')),
4141 'street_number' => array('title' => ts('Odd / Even Street Number')),
4142 'street_address' => NULL,
4144 'postal_code' => NULL,
4149 $addressFields['civicrm_address']['group_bys'] = array(
4150 'street_address' => NULL,
4152 'postal_code' => NULL,
4153 'state_province_id' => array(
4154 'title' => ts('State/Province'),
4156 'country_id' => array(
4157 'title' => ts('Country'),
4159 'county_id' => array(
4160 'title' => ts('County'),
4164 return $addressFields;
4168 * Do AlterDisplay processing on Address Fields.
4171 * @param array $rows
4172 * @param int $rowNum
4173 * @param string $baseUrl
4174 * @param string $linkText
4178 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4179 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4180 $entryFound = FALSE;
4182 if (array_key_exists('civicrm_address_country_id', $row)) {
4183 if ($value = $row['civicrm_address_country_id']) {
4184 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4186 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4187 "reset=1&force=1&{$criteriaQueryParams}&" .
4188 "country_id_op=in&country_id_value={$value}",
4189 $this->_absoluteUrl
, $this->_id
4191 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4192 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4193 array(1 => $linkText)
4200 if (array_key_exists('civicrm_address_county_id', $row)) {
4201 if ($value = $row['civicrm_address_county_id']) {
4202 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4204 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4205 "reset=1&force=1&{$criteriaQueryParams}&" .
4206 "county_id_op=in&county_id_value={$value}",
4207 $this->_absoluteUrl
, $this->_id
4209 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4210 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4211 array(1 => $linkText)
4217 // handle state province
4218 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4219 if ($value = $row['civicrm_address_state_province_id']) {
4220 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4222 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4223 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4224 $this->_absoluteUrl
, $this->_id
4226 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4227 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4228 array(1 => $linkText)
4239 * Do AlterDisplay processing on Address Fields.
4242 * @param array $rows
4243 * @param int $rowNum
4244 * @param string $baseUrl
4245 * @param string $linkText
4249 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4250 $entryFound = FALSE;
4251 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4252 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4253 $addLinks = array('gender_id' => 'Gender');
4254 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4255 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4256 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4257 $rowValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
4258 $rowLabels = array();
4259 foreach ($rowValues as $rowValue) {
4261 $rowLabels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4264 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4265 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4266 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4272 $yesNoFields = array(
4273 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4275 foreach ($yesNoFields as $fieldName) {
4276 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4277 // Since these are essentially 'negative fields' it feels like it
4278 // makes sense to only highlight the exceptions hence no 'No'.
4279 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4287 * Adjusts dates passed in to YEAR() for fiscal year.
4289 * @param string $fieldName
4293 public function fiscalYearOffset($fieldName) {
4294 $config = CRM_Core_Config
::singleton();
4295 $fy = $config->fiscalYearStart
;
4296 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4297 ($fy['d'] == 1 && $fy['M'] == 1)
4299 return "YEAR( $fieldName )";
4301 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4302 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4306 * Add Address into From Table if required.
4308 public function addAddressFromClause() {
4309 // include address field if address column is to be included
4310 if ((isset($this->_addressField
) &&
4311 $this->_addressField
4313 $this->isTableSelected('civicrm_address')
4316 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4317 ON ({$this->_aliases['civicrm_contact']}.id =
4318 {$this->_aliases['civicrm_address']}.contact_id) AND
4319 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4324 * Add Phone into From Table if required.
4326 public function addPhoneFromClause() {
4327 // include address field if address column is to be included
4328 if ($this->isTableSelected('civicrm_phone')) {
4330 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4331 ON ({$this->_aliases['civicrm_contact']}.id =
4332 {$this->_aliases['civicrm_phone']}.contact_id) AND
4333 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4338 * Add Financial Transaction into From Table if required.
4340 public function addFinancialTrxnFromClause() {
4341 if ($this->isTableSelected('civicrm_financial_trxn')) {
4343 LEFT JOIN civicrm_entity_financial_trxn eftcc
4344 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4345 eftcc.entity_table = 'civicrm_contribution')
4346 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4347 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4352 * Get phone columns to add to array.
4354 * @param array $options
4355 * - prefix Prefix to add to table (in case of more than one instance of the table)
4356 * - prefix_label Label to give columns from this phone table instance
4359 * phone columns definition
4361 public function getPhoneColumns($options = array()) {
4362 $defaultOptions = array(
4364 'prefix_label' => '',
4367 $options = array_merge($defaultOptions, $options);
4370 $options['prefix'] . 'civicrm_phone' => array(
4371 'dao' => 'CRM_Core_DAO_Phone',
4373 $options['prefix'] . 'phone' => array(
4374 'title' => $options['prefix_label'] . ts('Phone'),
4384 * Get address columns to add to array.
4386 * @param array $options
4387 * - prefix Prefix to add to table (in case of more than one instance of the table)
4388 * - prefix_label Label to give columns from this address table instance
4391 * address columns definition
4393 public function getAddressColumns($options = array()) {
4396 'prefix_label' => '',
4400 'defaults' => array(),
4402 return $this->addAddressFields(
4403 $options['group_by'],
4404 $options['order_by'],
4405 $options['filters'],
4406 $options['defaults']
4411 * Get a standard set of contact fields.
4415 public function getBasicContactFields() {
4417 'sort_name' => array(
4418 'title' => ts('Contact Name'),
4423 'no_display' => TRUE,
4426 'prefix_id' => array(
4427 'title' => ts('Contact Prefix'),
4429 'first_name' => array(
4430 'title' => ts('First Name'),
4432 'nick_name' => array(
4433 'title' => ts('Nick Name'),
4435 'middle_name' => array(
4436 'title' => ts('Middle Name'),
4438 'last_name' => array(
4439 'title' => ts('Last Name'),
4441 'suffix_id' => array(
4442 'title' => ts('Contact Suffix'),
4444 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4445 'email_greeting_display' => array('title' => ts('Email Greeting')),
4446 'addressee_display' => array('title' => ts('Addressee')),
4447 'contact_type' => array(
4448 'title' => ts('Contact Type'),
4450 'contact_sub_type' => array(
4451 'title' => ts('Contact Subtype'),
4453 'gender_id' => array(
4454 'title' => ts('Gender'),
4456 'birth_date' => array(
4457 'title' => ts('Birth Date'),
4460 'title' => ts('Age'),
4461 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4463 'job_title' => array(
4464 'title' => ts('Contact Job title'),
4466 'organization_name' => array(
4467 'title' => ts('Organization Name'),
4469 'external_identifier' => array(
4470 'title' => ts('Contact identifier from external system'),
4472 'do_not_email' => array(),
4473 'do_not_phone' => array(),
4474 'do_not_mail' => array(),
4475 'do_not_sms' => array(),
4476 'is_opt_out' => array(),
4477 'is_deceased' => array(),
4478 'preferred_language' => array(),
4483 * Get a standard set of contact filters.
4487 public function getBasicContactFilters() {
4489 'sort_name' => array(
4490 'title' => ts('Contact Name'),
4493 'title' => ts('Contact Source'),
4494 'type' => CRM_Utils_Type
::T_STRING
,
4497 'title' => ts('Contact ID'),
4498 'no_display' => TRUE,
4500 'gender_id' => array(
4501 'title' => ts('Gender'),
4502 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4503 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4505 'birth_date' => array(
4506 'title' => ts('Birth Date'),
4507 'operatorType' => CRM_Report_Form
::OP_DATE
,
4509 'contact_type' => array(
4510 'title' => ts('Contact Type'),
4512 'contact_sub_type' => array(
4513 'title' => ts('Contact Subtype'),
4515 'modified_date' => array(
4516 'title' => ts('Contact Modified'),
4517 'operatorType' => CRM_Report_Form
::OP_DATE
,
4518 'type' => CRM_Utils_Type
::T_DATE
,
4520 'is_deceased' => array(
4521 'title' => ts('Deceased'),
4522 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4525 'do_not_email' => array(
4526 'title' => ts('Do not email'),
4527 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4529 'do_not_phone' => array(
4530 'title' => ts('Do not phone'),
4531 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4533 'do_not_mail' => array(
4534 'title' => ts('Do not mail'),
4535 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4537 'do_not_sms' => array(
4538 'title' => ts('Do not SMS'),
4539 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4541 'is_opt_out' => array(
4542 'title' => ts('Do not bulk email'),
4543 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4545 'preferred_language' => array(
4546 'title' => ts('Preferred Language'),
4548 'is_deleted' => array(
4549 'no_display' => TRUE,
4551 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4557 * Add contact to group.
4559 * @param int $groupID
4561 public function add2group($groupID) {
4562 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4563 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4564 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select
);
4565 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4566 $sql = str_replace('WITH ROLLUP', '', $sql);
4567 $dao = CRM_Core_DAO
::executeQuery($sql);
4569 $contact_ids = array();
4570 // Add resulting contacts to group
4571 while ($dao->fetch()) {
4572 if ($dao->addtogroup_contact_id
) {
4573 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4577 if (!empty($contact_ids)) {
4578 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4579 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4582 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4588 * Show charts on print screen.
4590 public static function uploadChartImage() {
4591 // upload strictly for '.png' images
4592 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4593 if (preg_match('/\.png$/', $name)) {
4595 // Get the RAW .png from the input.
4596 $httpRawPostData = file_get_contents("php://input");
4598 // prepare the directory
4599 $config = CRM_Core_Config
::singleton();
4601 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4603 if (!file_exists($defaultPath)) {
4604 mkdir($defaultPath, 0777, TRUE);
4607 // full path to the saved image including filename
4608 $destination = $defaultPath . $name;
4611 $jfh = fopen($destination, 'w') or die("can't open file");
4612 fwrite($jfh, $httpRawPostData);
4614 CRM_Utils_System
::civiExit();
4619 * Apply common settings to entityRef fields.
4621 * @param array $field
4622 * @param string $table
4624 private function setEntityRefDefaults(&$field, $table) {
4625 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4626 $field['attributes'] +
= array(
4627 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4629 'placeholder' => ts('- select -'),
4634 * Add link fields to the row.
4636 * Function adds the _link & _hover fields to the row.
4639 * @param string $baseUrl
4640 * @param string $linkText
4641 * @param string $value
4642 * @param string $fieldName
4643 * @param string $tablePrefix
4644 * @param string $fieldLabel
4648 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4649 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4650 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4651 "reset=1&force=1&{$criteriaQueryParams}&" .
4652 $fieldName . "_op=in&{$fieldName}_value={$value}",
4653 $this->_absoluteUrl
, $this->_id
4655 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4656 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4657 array(1 => $linkText, 2 => $fieldLabel)
4662 * Get label for show results buttons.
4666 public function getResultsLabel() {
4667 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4668 return $showResultsLabel;
4672 * Determine the output mode from the url or input.
4675 * - pdf : Render as pdf
4676 * - csv : Render as csv
4677 * - print : Render in print format
4678 * - save : save the report and display the new report
4679 * - copy : save the report as a new instance and display that.
4680 * - group : go to the add to group screen.
4682 * Potentially chart variations could also be included but the complexity
4683 * is that we might print a bar chart as a pdf.
4685 protected function setOutputMode() {
4686 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4689 CRM_Core_DAO
::$_nullObject,
4691 CRM_Utils_Array
::value('task', $this->_params
)
4693 // if contacts are added to group
4694 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4695 $this->_outputMode
= 'group';
4697 if (isset($this->_params
['task'])) {
4698 unset($this->_params
['task']);
4703 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4706 * @param $columnName
4708 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4709 // add new column with date value for the datetime field
4710 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4711 CRM_Core_DAO
::executeQuery($tempQuery);
4712 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4713 CRM_Core_DAO
::executeQuery($updateQuery);
4714 $this->_selectClauses
[] = "{$columnName}_date";
4715 $this->_select
.= ", {$columnName}_date";
4716 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4717 unset($this->_sections
["{$columnName}"]);
4718 $this->assign('sections', $this->_sections
);
4722 * Get an array of the columns that have been selected for display.
4726 public function getSelectColumns() {
4727 $selectColumns = array();
4728 foreach ($this->_columns
as $tableName => $table) {
4729 if (array_key_exists('fields', $table)) {
4730 foreach ($table['fields'] as $fieldName => $field) {
4731 if (!empty($field['required']) ||
4732 !empty($this->_params
['fields'][$fieldName])
4735 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4740 return $selectColumns;
4744 * Add location tables to the query if they are used for filtering.
4746 * This is for when we are running the query separately for filtering and retrieving display fields.
4748 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4749 if ($this->isTableFiltered('civicrm_email')) {
4751 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4752 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4753 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4755 if ($this->isTableFiltered('civicrm_phone')) {
4757 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4758 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4759 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4761 if ($this->isTableFiltered('civicrm_address')) {
4763 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4764 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4765 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4770 * Set the base table for the FROM clause.
4772 * Sets up the from clause, allowing for the possibility it might be a
4773 * temp table pre-filtered by groups if a group filter is in use.
4775 * @param string $baseTable
4776 * @param string $field
4777 * @param null $tableAlias
4779 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4781 $tableAlias = $this->_aliases
[$baseTable];
4783 $this->_from
= $this->_from
= " FROM $baseTable $tableAlias ";
4784 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4785 $this->_from
.= " {$this->_aclFrom} ";
4789 * Join the temp table contacting contacts who are members of the filtered groups.
4791 * If we are using an IN filter we use an inner join, otherwise a left join.
4793 * @param string $baseTable
4794 * @param string $field
4795 * @param string $tableAlias
4797 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4798 if ($this->groupTempTable
) {
4799 if ($this->_params
['gid_op'] == 'in') {
4800 $this->_from
= " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4801 ON group_temp_table.id = $tableAlias.{$field} ";
4805 LEFT JOIN $this->groupTempTable group_temp_table
4806 ON $tableAlias.{$field} = group_temp_table.id ";
4812 * Get all labels for fields that are used in a group concat.
4814 * @param string $options
4815 * comma separated option values.
4816 * @param string $baoName
4817 * The BAO name for the field.
4818 * @param string $fieldName
4819 * The name of the field for which labels should be retrieved.
4823 public function getLabels($options, $baoName, $fieldName) {
4824 $types = explode(',', $options);
4826 foreach ($types as $value) {
4827 $labels[$value] = CRM_Core_PseudoConstant
::getLabel($baoName, $fieldName, $value);
4829 return implode(', ', array_filter($labels));
4833 * Add statistics columns.
4835 * If a group by is in play then add columns for the statistics fields.
4837 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
4838 * column header field.
4840 * @param array $field
4841 * @param string $tableName
4842 * @param string $fieldName
4843 * @param array $select
4847 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
4848 foreach ($field['statistics'] as $stat => $label) {
4849 $alias = "{$tableName}_{$fieldName}_{$stat}";
4850 switch (strtolower($stat)) {
4853 $select[] = "$stat({$field['dbAlias']}) as $alias";
4854 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4855 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4856 $this->_statFields
[$label] = $alias;
4857 $this->_selectAliases
[] = $alias;
4861 $select[] = "COUNT({$field['dbAlias']}) as $alias";
4862 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4863 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4864 $this->_statFields
[$label] = $alias;
4865 $this->_selectAliases
[] = $alias;
4868 case 'count_distinct':
4869 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
4870 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4871 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
4872 $this->_statFields
[$label] = $alias;
4873 $this->_selectAliases
[] = $alias;
4877 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
4878 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
4879 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
4880 $this->_statFields
[$label] = $alias;
4881 $this->_selectAliases
[] = $alias;
4889 * Add a basic field to the select clause.
4891 * @param string $tableName
4892 * @param string $fieldName
4893 * @param array $field
4894 * @param string $select
4897 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
4898 $alias = "{$tableName}_{$fieldName}";
4899 $select[] = "{$field['dbAlias']} as $alias";
4900 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
4901 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
4902 $this->_selectAliases
[] = $alias;
4909 * @param array $table
4910 * @param string $tableName
4915 protected function setTableAlias($table, $tableName) {
4916 if (!isset($table['alias'])) {
4917 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
4921 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
4924 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
4925 return $this->_aliases
[$tableName];
4929 * Function to add columns to reports.
4931 * This is ported from extended reports, which also adds join filters to the options.
4933 * @param string $type
4934 * @param array $options
4935 * - prefix - A string to prepend to the table name
4936 * - prefix_label A string to prepend to the fields
4937 * - fields (bool) - should the fields for this table be made available
4938 * - group_by (bool) - should the group bys for this table be made available.
4939 * - order_by (bool) - should the group bys for this table be made available.
4940 * - filters (bool) - should the filters for this table by made available.
4941 * - fields_defaults (array) array of fields that should be displayed by default.
4942 * - filters_defaults (array) array of fields that should be filtered by default.
4943 * - join_filters (array) fields available for filtering joins (requires additional custom code).
4944 * - join_fields (array) fields available from join (requires additional custom code).
4945 * - group_by_defaults (array) array of group bys that should be applied by default.
4946 * - order_by_defaults (array) array of order bys that should be applied by default.
4947 * - custom_fields (array) array of entity types for custom fields (not usually required).
4948 * - contact_type (string) optional restriction on contact type for some tables.
4949 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
4953 protected function getColumns($type, $options = array()) {
4954 $defaultOptions = array(
4956 'prefix_label' => '',
4958 'group_bys' => FALSE,
4959 'order_bys' => TRUE,
4961 'join_filters' => FALSE,
4962 'fields_defaults' => array(),
4963 'filters_defaults' => array(),
4964 'group_bys_defaults' => array(),
4965 'order_bys_defaults' => array(),
4967 $options = array_merge($defaultOptions, $options);
4969 $fn = 'get' . $type . 'Columns';
4970 return $this->$fn($options);
4974 * Get columns for contact table.
4976 * @param array $options
4980 protected function getContactColumns($options = array()) {
4981 $defaultOptions = array(
4982 'custom_fields' => array('Individual', 'Contact', 'Organization'),
4983 'fields_defaults' => array('display_name', 'id'),
4984 'order_bys_defaults' => array('sort_name ASC'),
4985 'contact_type' => NULL,
4988 $options = array_merge($defaultOptions, $options);
4990 $tableAlias = $options['prefix'] . 'contact';
4993 $options['prefix'] . 'display_name' => array(
4994 'name' => 'display_name',
4995 'title' => $options['prefix_label'] . ts('Contact Name'),
4996 'is_fields' => TRUE,
4998 $options['prefix'] . 'sort_name' => array(
4999 'name' => 'sort_name',
5000 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5001 'is_fields' => TRUE,
5002 'is_filters' => TRUE,
5003 'is_order_bys' => TRUE,
5005 $options['prefix'] . 'id' => array(
5007 'title' => $options['prefix_label'] . ts('Contact ID'),
5008 'alter_display' => 'alterContactID',
5009 'type' => CRM_Utils_Type
::T_INT
,
5010 'is_order_bys' => TRUE,
5011 'is_group_bys' => TRUE,
5012 'is_fields' => TRUE,
5014 $options['prefix'] . 'external_identifier' => array(
5015 'name' => 'external_identifier',
5016 'title' => $options['prefix_label'] . ts('External ID'),
5017 'type' => CRM_Utils_Type
::T_INT
,
5018 'is_fields' => TRUE,
5020 $options['prefix'] . 'contact_type' => array(
5021 'title' => $options['prefix_label'] . ts('Contact Type'),
5022 'name' => 'contact_type',
5023 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5024 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_type'),
5025 'is_fields' => TRUE,
5026 'is_filters' => TRUE,
5027 'is_group_bys' => TRUE,
5029 $options['prefix'] . 'contact_sub_type' => array(
5030 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5031 'name' => 'contact_sub_type',
5032 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5033 'options' => CRM_Contact_BAO_Contact
::buildOptions('contact_sub_type'),
5034 'is_fields' => TRUE,
5035 'is_filters' => TRUE,
5036 'is_group_bys' => TRUE,
5038 $options['prefix'] . 'is_deleted' => array(
5039 'title' => $options['prefix_label'] . ts('Is deleted'),
5040 'name' => 'is_deleted',
5041 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5042 'is_fields' => FALSE,
5043 'is_filters' => TRUE,
5044 'is_group_bys' => FALSE,
5047 $individualFields = array(
5048 $options['prefix'] . 'first_name' => array(
5049 'name' => 'first_name',
5050 'title' => $options['prefix_label'] . ts('First Name'),
5051 'is_fields' => TRUE,
5052 'is_filters' => TRUE,
5053 'is_order_bys' => TRUE,
5055 $options['prefix'] . 'middle_name' => array(
5056 'name' => 'middle_name',
5057 'title' => $options['prefix_label'] . ts('Middle Name'),
5058 'is_fields' => TRUE,
5060 $options['prefix'] . 'last_name' => array(
5061 'name' => 'last_name',
5062 'title' => $options['prefix_label'] . ts('Last Name'),
5063 'default_order' => 'ASC',
5064 'is_fields' => TRUE,
5066 $options['prefix'] . 'nick_name' => array(
5067 'name' => 'nick_name',
5068 'title' => $options['prefix_label'] . ts('Nick Name'),
5069 'is_fields' => TRUE,
5071 $options['prefix'] . 'gender_id' => array(
5072 'name' => 'gender_id',
5073 'title' => $options['prefix_label'] . ts('Gender'),
5074 'options' => CRM_Contact_BAO_Contact
::buildOptions('gender_id'),
5075 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
5076 'alter_display' => 'alterGenderID',
5077 'is_fields' => TRUE,
5078 'is_filters' => TRUE,
5080 'birth_date' => array(
5081 'title' => $options['prefix_label'] . ts('Birth Date'),
5082 'operatorType' => CRM_Report_Form
::OP_DATE
,
5083 'type' => CRM_Utils_Type
::T_DATE
,
5084 'is_fields' => TRUE,
5085 'is_filters' => TRUE,
5088 'title' => $options['prefix_label'] . ts('Age'),
5089 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '.birth_date, CURDATE())',
5090 'type' => CRM_Utils_Type
::T_INT
,
5091 'is_fields' => TRUE,
5093 $options['prefix'] . 'is_deceased' => array(
5094 'title' => $options['prefix_label'] . ts('Is deceased'),
5095 'name' => 'is_deceased',
5096 'type' => CRM_Utils_Type
::T_BOOLEAN
,
5097 'is_fields' => FALSE,
5098 'is_filters' => TRUE,
5099 'is_group_bys' => FALSE,
5102 if (!$options['contact_type'] ||
$options['contact_type'] === 'Individual') {
5103 $spec = array_merge($spec, $individualFields);
5106 if (!empty($options['custom_fields'])) {
5107 $this->_customGroupExtended
[$options['prefix'] . 'civicrm_contact'] = array(
5108 'extends' => $options['custom_fields'],
5109 'title' => $options['prefix_label'],
5110 'filters' => $options['filters'],
5111 'prefix' => $options['prefix'],
5112 'prefix_label' => $options['prefix_label'],
5116 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5120 * Build the columns.
5122 * The normal report class needs you to remember to do a few things that are often erratic
5124 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5125 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5126 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5127 * means any saved filters / fields on saved report instances. This will mean that matching names from
5128 * different tables may be ambigious, but it will smooth any code transition.
5129 * - note that it assumes the value being passed in is the actual table field name
5131 * 2) set the field & set it to no display if you don't want the field but you might want to use the field in other
5132 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5134 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5135 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5136 * the core classes can start to move towards that.
5138 * @param array $specs
5139 * @param string $tableName
5140 * @param string $daoName
5141 * @param string $tableAlias
5142 * @param array $defaults
5143 * @param array $options
5147 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = array(), $options = array()) {
5149 $tableAlias = str_replace('civicrm_', '', $tableName);
5151 $types = array('filters', 'group_bys', 'order_bys', 'join_filters');
5152 $columns = array($tableName => array_fill_keys($types, array()));
5153 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5154 $columns[$tableName]['dao'] = $daoName;
5155 $columns[$tableName]['alias'] = $tableAlias;
5157 foreach ($specs as $specName => $spec) {
5158 if (empty($spec['name'])) {
5159 $spec['name'] = $specName;
5162 $fieldAlias = (empty($options['no_field_disambiguation']) ?
$tableAlias . '_' : '') . $specName;
5163 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5164 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5165 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5166 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5169 if (!$spec['is_fields'] ||
(isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5170 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5173 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5174 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5177 foreach ($types as $type) {
5178 if ($options[$type] && !empty($spec['is_' . $type])) {
5179 $columns[$tableName][$type][$fieldAlias] = $spec;
5180 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5181 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5190 * Store group bys into array - so we can check elsewhere what is grouped.
5192 protected function storeGroupByArray() {
5194 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
5195 is_array($this->_params
['group_bys']) &&
5196 !empty($this->_params
['group_bys'])
5198 foreach ($this->_columns
as $tableName => $table) {
5199 $table = $this->_columns
[$tableName];
5200 if (array_key_exists('group_bys', $table)) {
5201 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5202 $field = $this->_columns
[$tableName]['metadata'][$fieldName];
5203 if (!empty($this->_params
['group_bys'][$fieldName])) {
5204 if (!empty($field['chart'])) {
5205 $this->assign('chartSupported', TRUE);
5208 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5209 !empty($this->_params
['group_bys_freq'][$fieldName])
5212 switch ($this->_params
['group_bys_freq'][$fieldName]) {
5214 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = self
::fiscalYearOffset($field['dbAlias']);
5217 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = " {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
5220 $this->_groupByArray
[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_{$this->_params['group_bys_freq'][$fieldName]} FROM {$field['dbAlias']})";
5225 if (!in_array($field['dbAlias'], $this->_groupByArray
)) {
5226 $this->_groupByArray
[$tableName . '_' . $fieldName] = $field['dbAlias'];
5242 protected function getDefaultsFromOptions($options) {
5244 'fields_defaults' => $options['fields_defaults'],
5245 'filters_defaults' => $options['filters_defaults'],
5246 'group_bys_defaults' => $options['group_bys_defaults'],
5247 'order_bys_defaults' => $options['order_bys_defaults'],