3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 CONST ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
54 * The id of the report instance
61 * The id of the report template
65 protected $_templateID;
73 protected $_noFields = FALSE;
76 * The set of all columns in the report. An associative array
77 * with column name as the key and attribues as the value
81 protected $_columns = array();
84 * The set of filters in the report
88 protected $_filters = array();
91 * The set of optional columns in the report
95 protected $_options = array();
97 protected $_defaults = array();
100 * By default most reports hide contact id.
101 * Setting this to true makes it available
103 protected $_exposeContactID = TRUE;
106 * Set of statistic fields
110 protected $_statFields = array();
113 * Set of statistics data
117 protected $_statistics = array();
120 * List of fields not to be repeated during display
124 protected $_noRepeats = array();
127 * List of fields not to be displayed
131 protected $_noDisplay = array();
134 * Object type that a custom group extends
138 protected $_customGroupExtends = NULL;
139 protected $_customGroupExtendsJoin = array();
140 protected $_customGroupFilters = TRUE;
141 protected $_customGroupGroupBy = FALSE;
142 protected $_customGroupJoin = 'LEFT JOIN';
148 protected $_tagFilter = FALSE;
151 * build groups filter
154 protected $_groupFilter = FALSE;
161 public $_navigation = array();
163 public $_drilldownReport = array();
166 * An attribute for checkbox/radio form field layout
170 protected $_fourColumnAttribute = array(
171 '</td><td width="25%">', '</td><td width="25%">',
172 '</td><td width="25%">', '</tr><tr><td>',
175 protected $_force = 1;
177 protected $_params = NULL;
178 protected $_formValues = NULL;
179 protected $_instanceValues = NULL;
181 protected $_instanceForm = FALSE;
182 protected $_criteriaForm = FALSE;
184 protected $_instanceButtonName = NULL;
185 protected $_createNewButtonName = NULL;
186 protected $_printButtonName = NULL;
187 protected $_pdfButtonName = NULL;
188 protected $_csvButtonName = NULL;
189 protected $_groupButtonName = NULL;
190 protected $_chartButtonName = NULL;
191 protected $_csvSupported = TRUE;
192 protected $_add2groupSupported = TRUE;
193 protected $_groups = NULL;
194 protected $_grandFlag = FALSE;
195 protected $_rowsFound = NULL;
196 protected $_selectAliases = array();
197 protected $_rollup = NULL;
203 protected $_limit = NULL;
206 * This can be set to specify a limit to the number of rows
207 * Since it is currently envisaged as part of the api usage it is only being applied
208 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
209 * of the code (see limit() fn
212 protected $_limitValue = NULL;
215 * This can be set to specify row offset
216 * See notes on _limitValue
219 protected $_offsetValue = NULL;
220 protected $_sections = NULL;
221 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
222 protected $_absoluteUrl = FALSE;
225 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
229 protected $_storeResultSet = FALSE;
232 * When _storeResultSet Flag is set use this var to store result set in form of array
236 protected $_resultSet = array();
239 * To what frequency group-by a date column
243 protected $_groupByDateFreq = array(
245 'YEARWEEK' => 'Week',
246 'QUARTER' => 'Quarter',
251 * Variables to hold the acl inner join and where clause
253 protected $_aclFrom = NULL;
254 protected $_aclWhere = NULL;
257 * Array of DAO tables having columns included in SELECT or ORDER BY clause
261 protected $_selectedTables;
264 * outputmode e.g 'print', 'csv', 'pdf'
267 protected $_outputMode;
269 public $_having = NULL;
270 public $_select = NULL;
271 public $_selectClauses = array();
272 public $_columnHeaders = array();
273 public $_orderBy = NULL;
274 public $_orderByFields = array();
275 public $_orderByArray = array();
276 public $_groupBy = NULL;
277 public $_whereClauses = array();
278 public $_havingClauses = array();
281 * dashBoardRowCount Dashboard row count
284 public $_dashBoardRowCount;
287 * Is this being called without a form controller (ie. the report is being render outside the normal form
288 * - e.g the api is retrieving the rows
291 public $noController = FALSE;
294 * Variable to hold the currency alias
296 protected $_currencyColumn = NULL;
301 function __construct() {
302 parent
::__construct();
305 if ($this->_tagFilter
) {
306 $this->buildTagFilter();
308 if ($this->_exposeContactID
) {
309 if (array_key_exists('civicrm_contact', $this->_columns
)) {
310 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
312 'title' => 'Contact ID',
318 if ($this->_groupFilter
) {
319 $this->buildGroupFilter();
322 // Get all custom groups
323 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
325 // Get the custom groupIds for which the user has VIEW permission
326 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
327 // and addCustomDataToColumns() will allow access to all custom groups.
328 $permCustomGroupIds = array();
329 if (!CRM_Core_Permission
::check('access all custom data')) {
330 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
331 // do not allow custom data for reports if user doesn't have
332 // permission to access custom data.
333 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
334 $this->_customGroupExtends
= array();
338 // merge custom data columns to _columns list, if any
339 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
341 // add / modify display columns, filters ..etc
342 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
344 //assign currencyColumn variable to tpl
345 $this->assign('currencyColumn', $this->_currencyColumn
);
348 function preProcessCommon() {
350 CRM_Utils_Request
::retrieve(
353 CRM_Core_DAO
::$_nullObject
356 $this->_dashBoardRowCount
=
357 CRM_Utils_Request
::retrieve(
360 CRM_Core_DAO
::$_nullObject
363 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
365 $this->assign('section', $this->_section
);
366 CRM_Core_Region
::instance('page-header')->add(array(
367 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
369 if(!$this->noController
) {
370 $this->setID($this->get('instanceId'));
373 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
375 $this->setID( CRM_Report_Utils_Report
::getInstanceIDForPath());
379 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
380 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
381 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
385 $this->assign('instanceId', $this->_id
);
386 $params = array('id' => $this->_id
);
387 $this->_instanceValues
= array();
388 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
390 $this->_instanceValues
392 if (empty($this->_instanceValues
)) {
393 CRM_Core_Error
::fatal("Report could not be loaded.");
395 $this->_title
= $this->_instanceValues
['title'];
396 if (!empty($this->_instanceValues
['permission']) &&
397 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
398 CRM_Core_Permission
::check('administer Reports')
401 CRM_Utils_System
::permissionDenied();
402 CRM_Utils_System
::civiExit();
405 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
407 $this->_formValues
= unserialize($formValues);
410 $this->_formValues
= NULL;
413 // lets always do a force if reset is found in the url.
414 if (!empty($_REQUEST['reset'])) {
419 $this->assign('mode', 'instance');
421 elseif (!$this->noController
) {
422 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
423 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
424 if (($instanceCount > 0) && $optionValueID) {
425 $this->assign('instanceUrl',
426 CRM_Utils_System
::url('civicrm/report/list',
427 "reset=1&ovid=$optionValueID"
431 if ($optionValueID) {
432 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
436 $this->assign('mode', 'template');
439 // lets display the Report Settings section
440 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
442 // Do not display Report Settings section if administer Reports permission is absent OR
443 // if report instance is reserved and administer reserved reports absent
444 if (!CRM_Core_Permission
::check('administer Reports') ||
445 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
446 $this->_instanceForm
= FALSE;
449 $this->assign('criteriaForm', FALSE);
450 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
451 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
452 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
453 $this->assign('criteriaForm', TRUE);
454 $this->_criteriaForm
= TRUE;
458 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
459 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
460 $this->_printButtonName
= $this->getButtonName('submit', 'print');
461 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
462 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
463 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
464 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
467 function addBreadCrumb() {
471 'title' => ts('Report Templates'),
472 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
476 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
479 function preProcess() {
480 $this->preProcessCommon();
483 $this->addBreadCrumb();
486 foreach ($this->_columns
as $tableName => $table) {
488 if (!isset($table['alias'])) {
489 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
492 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
495 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
497 $daoOrBaoName = NULL;
498 // higher preference to bao object
499 if (array_key_exists('bao', $table)) {
500 $daoOrBaoName = $table['bao'];
501 $expFields = $daoOrBaoName::exportableFields( );
503 elseif (array_key_exists('dao', $table)){
504 $daoOrBaoName = $table['dao'];
505 $expFields = $daoOrBaoName::export( );
508 $expFields = array();
511 $doNotCopy = array('required');
513 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
514 foreach ($fieldGroups as $fieldGrp) {
515 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
516 foreach ($table[$fieldGrp] as $fieldName => $field) {
517 // $name is the field name used to reference the BAO/DAO export fields array
518 $name = isset($field['name']) ?
$field['name'] : $fieldName;
520 // Sometimes the field name key in the BAO/DAO export fields array is
521 // different from the actual database field name.
522 // Unset $field['name'] so that actual database field name can be obtained
523 // from the BAO/DAO export fields array.
524 unset($field['name']);
526 if (array_key_exists($name, $expFields)) {
527 foreach ($doNotCopy as $dnc) {
528 // unset the values we don't want to be copied.
529 unset($expFields[$name][$dnc]);
532 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
535 foreach ($expFields[$name] as $property => $val) {
536 if (!array_key_exists($property, $field)) {
537 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
544 if (!empty($field['no_repeat'])) {
545 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
547 if (!empty($field['no_display'])) {
548 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
551 // set alias = table-name, unless already set
552 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
553 $this->_columns
[$tableName]['alias'] : $tableName
555 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
557 // set name = fieldName, unless already set
558 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
559 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
562 // set dbAlias = alias.name, unless already set
563 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
564 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
567 // a few auto fills for filters
568 if ($fieldGrp == 'filters') {
569 // fill operator types
570 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
571 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
572 case CRM_Utils_Type
::T_MONEY
:
573 case CRM_Utils_Type
::T_FLOAT
:
574 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
576 case CRM_Utils_Type
::T_INT
:
577 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
579 case CRM_Utils_Type
::T_DATE
:
580 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
582 case CRM_Utils_Type
::T_BOOLEAN
:
583 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
584 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
585 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
586 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
591 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
592 // with multiple options operator-type is generally multi-select
593 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
594 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
596 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
607 // copy filters to a separate handy variable
608 if (array_key_exists('filters', $table)) {
609 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
612 if (array_key_exists('group_bys', $table)) {
613 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
616 if (array_key_exists('fields', $table)) {
617 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
622 $this->setDefaultValues(FALSE);
625 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
626 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
627 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
628 CRM_Report_Utils_Get
::processChart($this->_defaults
);
631 $this->_formValues
= $this->_defaults
;
632 $this->postProcess();
637 * @param bool $freeze
641 function setDefaultValues($freeze = TRUE) {
642 $freezeGroup = array();
644 // FIXME: generalizing form field naming conventions would reduce
645 // lots of lines below.
646 foreach ($this->_columns
as $tableName => $table) {
647 if (array_key_exists('fields', $table)) {
648 foreach ($table['fields'] as $fieldName => $field) {
649 if (empty($field['no_display'])) {
650 if (isset($field['required'])) {
652 $this->_defaults
['fields'][$fieldName] = 1;
655 // find element object, so that we could use quickform's freeze method
656 // for required elements
657 $obj = $this->getElementFromGroup("fields", $fieldName);
659 $freezeGroup[] = $obj;
663 elseif (isset($field['default'])) {
664 $this->_defaults
['fields'][$fieldName] = $field['default'];
670 if (array_key_exists('group_bys', $table)) {
671 foreach ($table['group_bys'] as $fieldName => $field) {
672 if (isset($field['default'])) {
673 if (!empty($field['frequency'])) {
674 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
676 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
680 if (array_key_exists('filters', $table)) {
681 foreach ($table['filters'] as $fieldName => $field) {
682 if (isset($field['default'])) {
683 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
684 if(is_array($field['default'])){
685 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
686 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
687 $this->_defaults
["{$fieldName}_relative"] = 0;
690 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
694 $this->_defaults
["{$fieldName}_value"] = $field['default'];
697 //assign default value as "in" for multiselect
698 //operator, To freeze the select element
699 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT
) {
700 $this->_defaults
["{$fieldName}_op"] = 'in';
702 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_ENTITYREF
) {
703 $this->_defaults
["{$fieldName}_op"] = 'in';
705 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
) {
706 $this->_defaults
["{$fieldName}_op"] = 'mhas';
708 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
709 $this->_defaults
["{$fieldName}_op"] = $op;
715 array_key_exists('order_bys', $table) &&
716 is_array($table['order_bys'])
718 if (!array_key_exists('order_bys', $this->_defaults
)) {
719 $this->_defaults
['order_bys'] = array();
721 foreach ($table['order_bys'] as $fieldName => $field) {
722 if (!empty($field['default']) ||
!empty($field['default_order']) ||
723 CRM_Utils_Array
::value('default_is_section', $field) ||
!empty($field['default_weight'])) {
725 'column' => $fieldName,
726 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
727 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
730 if (!empty($field['default_weight'])) {
731 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
734 array_unshift($this->_defaults
['order_bys'], $order_by);
740 foreach ($this->_options
as $fieldName => $field) {
741 if (isset($field['default'])) {
742 $this->_defaults
['options'][$fieldName] = $field['default'];
747 if (!empty($this->_submitValues
)) {
748 $this->preProcessOrderBy($this->_submitValues
);
751 $this->preProcessOrderBy($this->_defaults
);
754 // lets finish freezing task here itself
755 if (!empty($freezeGroup)) {
756 foreach ($freezeGroup as $elem) {
761 if ($this->_formValues
) {
762 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
765 if ($this->_instanceValues
) {
766 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
769 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
771 return $this->_defaults
;
776 * @param $grpFieldName
780 function getElementFromGroup($group, $grpFieldName) {
781 $eleObj = $this->getElement($group);
782 foreach ($eleObj->_elements
as $index => $obj) {
783 if ($grpFieldName == $obj->_attributes
['name']) {
791 * Setter for $_params
792 * @param array $params
794 function setParams($params) {
795 $this->_params
= $params;
803 * @internal param int $id
805 function setID($instanceid) {
806 $this->_id
= $instanceid;
812 * @internal param bool $force
814 function setForce($isForce) {
815 $this->_force
= $isForce;
819 * Setter for $_limitValue
820 * @param number $_limitValue
822 function setLimitValue($_limitValue) {
823 $this->_limitValue
= $_limitValue;
827 * Setter for $_offsetValue
828 * @param number $_offsetValue
830 function setOffsetValue($_offsetValue) {
831 $this->_offsetValue
= $_offsetValue;
835 * Getter for $_defaultValues
836 * @return array $_defaultValues
838 function getDefaultValues() {
839 return $this->_defaults
;
842 function addColumns() {
845 foreach ($this->_columns
as $tableName => $table) {
846 if (array_key_exists('fields', $table)) {
847 foreach ($table['fields'] as $fieldName => $field) {
849 if (empty($field['no_display'])) {
850 foreach ( array('table', 'field') as $var) {
851 if (!empty($
{$var}['grouping'])) {
852 if (!is_array($
{$var}['grouping'])) {
853 $tableName = $
{$var}['grouping'];
855 $tableName = array_keys($
{$var}['grouping']);
856 $tableName = $tableName[0];
857 $groupTitle = array_values($
{$var}['grouping']);
858 $groupTitle = $groupTitle[0];
863 if (!$groupTitle && isset($table['group_title'])) {
864 $groupTitle = $table['group_title'];
867 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
868 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
869 $colGroups[$tableName]['group_title'] = $groupTitle;
872 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
878 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
879 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
881 $this->assign('colGroups', $colGroups);
884 function addFilters() {
887 foreach ($this->_filters
as $table => $attributes) {
888 foreach ($attributes as $fieldName => $field) {
889 // get ready with option value pair
890 // @ 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
892 $operations = $this->getOperationPair(
893 CRM_Utils_Array
::value('operatorType', $field),
896 $filters[$table][$fieldName] = $field;
898 switch (CRM_Utils_Array
::value('operatorType', $field)) {
899 case CRM_Report_Form
::OP_MONTH
:
900 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
901 // If there's no option list for this filter, define one.
902 $field['options'] = array(
911 9 => ts('September'),
913 11 => ts('November'),
914 12 => ts('December'),
916 // Add this option list to this column _columns. This is
917 // required so that filter statistics show properly.
918 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
920 case CRM_Report_Form
::OP_MULTISELECT
:
921 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
922 // assume a multi-select field
923 if (!empty($field['options']) ||
$fieldName == 'state_province_id' ||
$fieldName == 'county_id') {
924 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
925 if (count($operations) <= 1) {
928 if ($fieldName == 'state_province_id' ||
$fieldName == 'county_id') {
929 $this->addChainSelect($fieldName . '_value', array('multiple' => TRUE, 'label' => NULL, 'class' => 'huge'));
932 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
933 'style' => 'min-width:250px',
934 'class' => 'crm-select2 huge',
936 'placeholder' => ts('- select -'),
942 case CRM_Report_Form
::OP_SELECT
:
943 // assume a select field
944 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
945 if (!empty($field['options']))
946 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
949 case CRM_Report_Form
::OP_ENTITYREF
:
950 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
951 $this->setEntityRefDefaults($field, $table);
952 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
955 case CRM_Report_Form
::OP_DATE
:
956 // build datetime fields
957 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
961 case CRM_Report_Form
::OP_DATETIME
:
962 // build datetime fields
963 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
967 case CRM_Report_Form
::OP_INT
:
968 case CRM_Report_Form
::OP_FLOAT
:
969 // and a min value input box
970 $this->add('text', "{$fieldName}_min", ts('Min'));
971 // and a max value input box
972 $this->add('text', "{$fieldName}_max", ts('Max'));
974 // default type is string
975 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
976 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
978 // we need text box for value input
979 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
984 $this->assign('filters', $filters);
987 function addOptions() {
988 if (!empty($this->_options
)) {
989 // FIXME: For now lets build all elements as checkboxes.
990 // Once we clear with the format we can build elements based on type
993 foreach ($this->_options
as $fieldName => $field) {
994 if ($field['type'] == 'select') {
995 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
997 else if ($field['type'] == 'checkbox') {
998 $options[$field['title']] = $fieldName;
999 $this->addCheckBox($fieldName, NULL,
1001 NULL, NULL, NULL, $this->_fourColumnAttribute
1006 $this->assign('otherOptions', $this->_options
);
1009 function addChartOptions() {
1010 if (!empty($this->_charts
)) {
1011 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
1012 $this->assign('charts', $this->_charts
);
1013 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1017 function addGroupBys() {
1018 $options = $freqElements = array();
1020 foreach ($this->_columns
as $tableName => $table) {
1021 if (array_key_exists('group_bys', $table)) {
1022 foreach ($table['group_bys'] as $fieldName => $field) {
1023 if (!empty($field)) {
1024 $options[$field['title']] = $fieldName;
1025 if (!empty($field['frequency'])) {
1026 $freqElements[$field['title']] = $fieldName;
1032 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1033 NULL, NULL, NULL, $this->_fourColumnAttribute
1035 $this->assign('groupByElements', $options);
1037 foreach ($freqElements as $name) {
1038 $this->addElement('select', "group_bys_freq[$name]",
1039 ts('Frequency'), $this->_groupByDateFreq
1044 function addOrderBys() {
1046 foreach ($this->_columns
as $tableName => $table) {
1048 // Report developer may define any column to order by; include these as order-by options
1049 if (array_key_exists('order_bys', $table)) {
1050 foreach ($table['order_bys'] as $fieldName => $field) {
1051 if (!empty($field)) {
1052 $options[$fieldName] = $field['title'];
1057 /* Add searchable custom fields as order-by options, if so requested
1058 * (These are already indexed, so allowing to order on them is cheap.)
1062 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1063 foreach ($table['fields'] as $fieldName => $field) {
1064 if (empty($field['no_display'])) {
1065 $options[$fieldName] = $field['title'];
1073 $this->assign('orderByOptions', $options);
1075 if (!empty($options)) {
1077 '-' => ' - none - ') +
$options;
1078 for ($i = 1; $i <= 5; $i++
) {
1079 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1080 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1081 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1082 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1087 function buildInstanceAndButtons() {
1088 CRM_Report_Form_Instance
::buildForm($this);
1090 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1092 $this->addElement('submit', $this->_instanceButtonName
, $label);
1093 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1094 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1097 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1099 if ($this->_instanceForm
) {
1100 $this->assign('instanceForm', TRUE);
1103 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1104 $this->addElement('submit', $this->_printButtonName
, $label);
1106 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1107 $this->addElement('submit', $this->_pdfButtonName
, $label);
1109 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1111 if ($this->_csvSupported
) {
1112 $this->addElement('submit', $this->_csvButtonName
, $label);
1115 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1116 $this->addElement('select', 'groups', ts('Group'),
1117 array('' => ts('Add Contacts to Group')) + CRM_Core_PseudoConstant
::nestedGroup(),
1118 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1120 $this->assign('group', TRUE);
1123 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1125 $this->addChartOptions();
1126 $this->addButtons(array(
1129 'name' => ts('Preview Report'),
1130 'isDefault' => TRUE,
1136 function buildQuickForm() {
1137 $this->addColumns();
1139 $this->addFilters();
1141 $this->addOptions();
1143 $this->addGroupBys();
1145 $this->addOrderBys();
1147 $this->buildInstanceAndButtons();
1149 //add form rule for report
1150 if (is_callable(array(
1151 $this, 'formRule'))) {
1152 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1156 // a formrule function to ensure that fields selected in group_by
1157 // (if any) should only be the ones present in display/select fields criteria;
1158 // note: works if and only if any custom field selected in group_by.
1161 * @param array $ignoreFields
1165 function customDataFormRule($fields, $ignoreFields = array( )) {
1167 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1168 foreach ($this->_columns
as $tableName => $table) {
1169 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1170 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1171 if (array_key_exists($fieldName, $fields['group_bys']) &&
1172 !array_key_exists($fieldName, $fields['fields'])
1174 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1176 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1177 foreach ($fields['fields'] as $fld => $val) {
1178 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1179 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1190 // Note: $fieldName param allows inheriting class to build operationPairs
1191 // specific to a field.
1193 * @param string $type
1194 * @param null $fieldName
1198 function getOperationPair($type = "string", $fieldName = NULL) {
1199 // FIXME: At some point we should move these key-val pairs
1200 // to option_group and option_value table.
1202 case CRM_Report_Form
::OP_INT
:
1203 case CRM_Report_Form
::OP_FLOAT
:
1205 'lte' => ts('Is less than or equal to'),
1206 'gte' => ts('Is greater than or equal to'),
1207 'bw' => ts('Is between'),
1208 'eq' => ts('Is equal to'),
1209 'lt' => ts('Is less than'),
1210 'gt' => ts('Is greater than'),
1211 'neq' => ts('Is not equal to'),
1212 'nbw' => ts('Is not between'),
1213 'nll' => ts('Is empty (Null)'),
1214 'nnll' => ts('Is not empty (Null)'),
1218 case CRM_Report_Form
::OP_SELECT
:
1220 'eq' => ts('Is equal to'),
1223 case CRM_Report_Form
::OP_MONTH
:
1224 case CRM_Report_Form
::OP_MULTISELECT
:
1225 case CRM_Report_Form
::OP_ENTITYREF
:
1227 'in' => ts('Is one of'),
1228 'notin' => ts('Is not one of'),
1232 case CRM_Report_Form
::OP_DATE
:
1234 'nll' => ts('Is empty (Null)'),
1235 'nnll' => ts('Is not empty (Null)'),
1239 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1240 // use this operator for the values, concatenated with separator. For e.g if
1241 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1243 'mhas' => ts('Is one of'),
1244 'mnot' => ts('Is not one of'),
1250 'has' => ts('Contains'),
1251 'sw' => ts('Starts with'),
1252 'ew' => ts('Ends with'),
1253 'nhas' => ts('Does not contain'),
1254 'eq' => ts('Is equal to'),
1255 'neq' => ts('Is not equal to'),
1256 'nll' => ts('Is empty (Null)'),
1257 'nnll' => ts('Is not empty (Null)'),
1262 function buildTagFilter() {
1263 $contactTags = CRM_Core_BAO_Tag
::getTags();
1264 if (!empty($contactTags)) {
1265 $this->_columns
['civicrm_tag'] = array(
1266 'dao' => 'CRM_Core_DAO_Tag',
1272 'title' => ts('Tag'),
1274 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1275 'options' => $contactTags,
1283 * Adds group filters to _columns (called from _Constuct
1285 function buildGroupFilter() {
1286 $this->_columns
['civicrm_group']['filters'] = array(
1289 'name' => 'group_id',
1290 'title' => ts('Group'),
1291 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1293 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1296 if (empty($this->_columns
['civicrm_group']['dao'])) {
1297 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1299 if (empty($this->_columns
['civicrm_group']['alias'])) {
1300 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1305 * @param string $operator
1309 function getSQLOperator($operator = "like") {
1310 switch ($operator) {
1343 return 'IS NOT NULL';
1358 * @return null|string
1360 function whereClause(&$field, $op,
1364 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1370 if (($min !== NULL && strlen($min) > 0) ||
1371 ($max !== NULL && strlen($max) > 0)
1373 $min = CRM_Utils_Type
::escape($min, $type);
1374 $max = CRM_Utils_Type
::escape($max, $type);
1378 $clauses[] = "( {$field['dbAlias']} >= $min )";
1381 $clauses[] = "( {$field['dbAlias']} < $min )";
1386 $clauses[] = "( {$field['dbAlias']} <= $max )";
1389 $clauses[] = "( {$field['dbAlias']} > $max )";
1393 if (!empty($clauses)) {
1395 $clause = implode(' AND ', $clauses);
1398 $clause = implode(' OR ', $clauses);
1406 if ($value !== NULL && strlen($value) > 0) {
1407 $value = CRM_Utils_Type
::escape($value, $type);
1408 if (strpos($value, '%') === FALSE) {
1409 $value = "'%{$value}%'";
1412 $value = "'{$value}'";
1414 $sqlOP = $this->getSQLOperator($op);
1415 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1421 if (is_string($value) && strlen($value)) {
1422 $value = explode(',', $value);
1424 if ($value !== NULL && is_array($value) && count($value) > 0) {
1425 $sqlOP = $this->getSQLOperator($op);
1426 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1427 //cycle through selections and esacape values
1428 foreach ($value as $key => $selection) {
1429 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1431 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1434 // for numerical values
1435 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1437 if ($op == 'notin') {
1438 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1441 $clause = "( " . $clause . " )";
1447 // mhas == multiple has
1448 if ($value !== NULL && count($value) > 0) {
1449 $sqlOP = $this->getSQLOperator($op);
1450 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1455 // mnot == multiple is not one of
1456 if ($value !== NULL && count($value) > 0) {
1457 $sqlOP = $this->getSQLOperator($op);
1458 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1464 if ($value !== NULL && strlen($value) > 0) {
1465 $value = CRM_Utils_Type
::escape($value, $type);
1466 if (strpos($value, '%') === FALSE) {
1468 $value = "'{$value}%'";
1471 $value = "'%{$value}'";
1475 $value = "'{$value}'";
1477 $sqlOP = $this->getSQLOperator($op);
1478 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1484 $sqlOP = $this->getSQLOperator($op);
1485 $clause = "( {$field['dbAlias']} $sqlOP )";
1489 if ($value !== NULL && strlen($value) > 0) {
1490 if (isset($field['clause'])) {
1491 // FIXME: we not doing escape here. Better solution is to use two
1492 // different types - data-type and filter-type
1493 $clause = $field['clause'];
1496 $value = CRM_Utils_Type
::escape($value, $type);
1497 $sqlOP = $this->getSQLOperator($op);
1498 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1499 $value = "'{$value}'";
1501 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1507 if (!empty($field['group']) && $clause) {
1508 $clause = $this->whereGroupClause($field, $value, $op);
1510 elseif (!empty($field['tag']) && $clause) {
1511 // not using left join in query because if any contact
1512 // belongs to more than one tag, results duplicate
1514 $clause = $this->whereTagClause($field, $value, $op);
1516 elseif (!empty($field['membership_org']) && $clause) {
1517 $clause = $this->whereMembershipOrgClause($field, $value, $op);
1519 elseif (!empty($field['membership_type']) && $clause) {
1520 $clause = $this->whereMembershipTypeClause($field, $value, $op);
1531 * @param null $fromTime
1532 * @param null $toTime
1534 * @return null|string
1536 function dateClause($fieldName,
1537 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1540 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1541 $sqlOP = $this->getSQLOperator($relative);
1542 return "( {$fieldName} {$sqlOP} )";
1545 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1548 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1549 $clauses[] = "( {$fieldName} >= $from )";
1553 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1554 $clauses[] = "( {$fieldName} <= {$to} )";
1557 if (!empty($clauses)) {
1558 return implode(' AND ', $clauses);
1564 * @todo - could not find any instances where this is called
1565 * @param unknown_type $relative
1566 * @param String $from
1567 * @param String_type $to
1568 * @return string|NULL
1570 function dateDisplay($relative, $from, $to) {
1571 list($from, $to) = $this->getFromTo($relative, $from, $to);
1574 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1577 $clauses[] = 'Past';
1581 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1584 $clauses[] = 'Today';
1587 if (!empty($clauses)) {
1588 return implode(' - ', $clauses);
1598 * @param null $fromtime
1599 * @param null $totime
1603 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1604 if (empty($totime)) {
1607 //FIX ME not working for relative
1609 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1610 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1611 $from = substr($dateRange['from'], 0, 8);
1612 //Take only Date Part, Sometime Time part is also present in 'to'
1613 $to = substr($dateRange['to'], 0, 8);
1615 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1616 $to = CRM_Utils_Date
::processDate($to, $totime);
1617 return array($from, $to);
1623 function alterDisplay(&$rows) {
1624 // custom code to alter rows
1630 function alterCustomDataDisplay(&$rows) {
1631 // custom code to alter rows having custom values
1632 if (empty($this->_customGroupExtends
)) {
1636 $customFieldIds = array();
1637 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1638 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1639 $customFieldIds[$fieldAlias] = $fieldId;
1642 if (empty($customFieldIds)) {
1646 $customFields = $fieldValueMap = array();
1647 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1649 // skip for type date and ContactReference since date format is already handled
1651 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1652 FROM civicrm_custom_field cf
1653 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1654 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1655 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1656 cg.is_active = 1 AND
1657 cf.is_active = 1 AND
1658 cf.is_searchable = 1 AND
1659 cf.data_type NOT IN ('ContactReference', 'Date') AND
1660 cf.id IN (" . implode(",", $customFieldIds) . ")";
1662 $dao = CRM_Core_DAO
::executeQuery($query);
1663 while ($dao->fetch()) {
1664 foreach ($customFieldCols as $key) {
1665 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1667 if ($dao->option_group_id
) {
1668 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1673 $entryFound = FALSE;
1674 foreach ($rows as $rowNum => $row) {
1675 foreach ($row as $tableCol => $val) {
1676 if (array_key_exists($tableCol, $customFields)) {
1677 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1682 // skip looking further in rows, if first row itself doesn't
1683 // have the column we need
1692 * @param $customField
1693 * @param $fieldValueMap
1695 * @return float|string
1697 function formatCustomValues($value, $customField, $fieldValueMap) {
1698 if (CRM_Utils_System
::isNull($value)) {
1702 $htmlType = $customField['html_type'];
1704 switch ($customField['data_type']) {
1706 if ($value == '1') {
1707 $retValue = ts('Yes');
1710 $retValue = ts('No');
1715 $retValue = CRM_Utils_System
::formatWikiURL($value);
1727 if ($htmlType == 'Text') {
1728 $retValue = (float)$value;
1732 if ($htmlType == 'Text') {
1742 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1747 if (in_array($htmlType, array(
1748 'Text', 'TextArea'))) {
1752 case 'StateProvince':
1755 switch ($htmlType) {
1756 case 'Multi-Select Country':
1757 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1758 $customData = array();
1759 foreach ($value as $val) {
1761 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1764 $retValue = implode(', ', $customData);
1767 case 'Select Country':
1768 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1771 case 'Select State/Province':
1772 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1775 case 'Multi-Select State/Province':
1776 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1777 $customData = array();
1778 foreach ($value as $val) {
1780 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1783 $retValue = implode(', ', $customData);
1788 case 'Autocomplete-Select':
1789 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1793 case 'AdvMulti-Select':
1794 case 'Multi-Select':
1795 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1796 $customData = array();
1797 foreach ($value as $val) {
1799 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1802 $retValue = implode(', ', $customData);
1820 function removeDuplicates(&$rows) {
1821 if (empty($this->_noRepeats
)) {
1824 $checkList = array();
1826 foreach ($rows as $key => $list) {
1827 foreach ($list as $colName => $colVal) {
1828 if (array_key_exists($colName, $checkList) &&
1829 $checkList[$colName] == $colVal) {
1830 $rows[$key][$colName] = "";
1832 if (in_array($colName, $this->_noRepeats
)) {
1833 $checkList[$colName] = $colVal;
1842 * @param bool $subtotal
1844 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1845 foreach ($row as $colName => $colVal) {
1846 if (in_array($colName, $fields)) {
1847 $row[$colName] = $row[$colName];
1849 elseif (isset($this->_columnHeaders
[$colName])) {
1851 $row[$colName] = "Subtotal";
1855 unset($row[$colName]);
1866 function grandTotal(&$rows) {
1867 if (!$this->_rollup ||
($this->_rollup
== '') ||
1868 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1872 $lastRow = array_pop($rows);
1874 foreach ($this->_columnHeaders
as $fld => $val) {
1875 if (!in_array($fld, $this->_statFields
)) {
1876 if (!$this->_grandFlag
) {
1877 $lastRow[$fld] = "Grand Total";
1878 $this->_grandFlag
= TRUE;
1881 $lastRow[$fld] = "";
1886 $this->assign('grandStat', $lastRow);
1892 * @param bool $pager
1894 function formatDisplay(&$rows, $pager = TRUE) {
1895 // set pager based on if any limit was applied in the query.
1900 // allow building charts if any
1901 if (!empty($this->_params
['charts']) && !empty($rows)) {
1902 $this->buildChart($rows);
1903 $this->assign('chartEnabled', TRUE);
1904 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1905 $this->assign('chartId', $this->_chartId
);
1908 // unset columns not to be displayed.
1909 foreach ($this->_columnHeaders
as $key => $value) {
1910 if (!empty($value['no_display'])) {
1911 unset($this->_columnHeaders
[$key]);
1915 // unset columns not to be displayed.
1916 if (!empty($rows)) {
1917 foreach ($this->_noDisplay
as $noDisplayField) {
1918 foreach ($rows as $rowNum => $row) {
1919 unset($this->_columnHeaders
[$noDisplayField]);
1924 // build array of section totals
1925 $this->sectionTotals();
1927 // process grand-total row
1928 $this->grandTotal($rows);
1930 // use this method for formatting rows for display purpose.
1931 $this->alterDisplay($rows);
1932 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1934 // use this method for formatting custom rows for display purpose.
1935 $this->alterCustomDataDisplay($rows);
1941 function buildChart(&$rows) {
1942 // override this method for building charts.
1945 // select() method below has been added recently (v3.3), and many of the report templates might
1946 // still be having their own select() method. We should fix them as and when encountered and move
1947 // towards generalizing the select() method below.
1949 $select = $this->_selectAliases
= array();
1951 foreach ($this->_columns
as $tableName => $table) {
1952 if (array_key_exists('fields', $table)) {
1953 foreach ($table['fields'] as $fieldName => $field) {
1954 if ($tableName == 'civicrm_address') {
1955 $this->_addressField
= TRUE;
1957 if ($tableName == 'civicrm_email') {
1958 $this->_emailField
= TRUE;
1960 if ($tableName == 'civicrm_phone') {
1961 $this->_phoneField
= TRUE;
1964 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1966 // 1. In many cases we want select clause to be built in slightly different way
1967 // for a particular field of a particular type.
1968 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1970 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1971 if ($selectClause) {
1972 $select[] = $selectClause;
1976 // include statistics columns only if set
1977 if (!empty($field['statistics'])) {
1978 foreach ($field['statistics'] as $stat => $label) {
1979 $alias = "{$tableName}_{$fieldName}_{$stat}";
1980 switch (strtolower($stat)) {
1983 $select[] = "$stat({$field['dbAlias']}) as $alias";
1984 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1985 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1986 $this->_statFields
[$label] = $alias;
1987 $this->_selectAliases
[] = $alias;
1991 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1992 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1993 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1994 $this->_statFields
[$label] = $alias;
1995 $this->_selectAliases
[] = $alias;
1998 case 'count_distinct':
1999 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2000 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2001 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2002 $this->_statFields
[$label] = $alias;
2003 $this->_selectAliases
[] = $alias;
2007 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2008 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2009 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2010 $this->_statFields
[$label] = $alias;
2011 $this->_selectAliases
[] = $alias;
2017 $alias = "{$tableName}_{$fieldName}";
2018 $select[] = "{$field['dbAlias']} as $alias";
2019 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2020 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2021 $this->_selectAliases
[] = $alias;
2027 // select for group bys
2028 if (array_key_exists('group_bys', $table)) {
2029 foreach ($table['group_bys'] as $fieldName => $field) {
2031 if ($tableName == 'civicrm_address') {
2032 $this->_addressField
= TRUE;
2034 if ($tableName == 'civicrm_email') {
2035 $this->_emailField
= TRUE;
2037 if ($tableName == 'civicrm_phone') {
2038 $this->_phoneField
= TRUE;
2040 // 1. In many cases we want select clause to be built in slightly different way
2041 // for a particular field of a particular type.
2042 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2044 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2045 if ($selectClause) {
2046 $select[] = $selectClause;
2050 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
2051 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2053 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2054 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2055 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2056 $field['title'] = 'Week';
2060 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2061 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2062 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2063 $field['title'] = 'Year';
2067 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2068 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2069 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2070 $field['title'] = 'Month';
2074 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2075 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2076 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2077 $field['title'] = 'Quarter';
2080 // for graphs and charts -
2081 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2082 $this->_interval
= $field['title'];
2083 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
2084 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2085 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2087 // just to make sure these values are transfered to rows.
2088 // since we 'll need them for calculation purpose,
2089 // e.g making subtotals look nicer or graphs
2090 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2091 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2098 $this->_selectClauses
= $select;
2099 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2110 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2115 $this->storeWhereHavingClauseArray();
2117 if (empty($this->_whereClauses
)) {
2118 $this->_where
= "WHERE ( 1 ) ";
2119 $this->_having
= "";
2122 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2125 if ($this->_aclWhere
) {
2126 $this->_where
.= " AND {$this->_aclWhere} ";
2129 if (!empty($this->_havingClauses
)) {
2130 // use this clause to construct group by clause.
2131 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2136 * Store Where clauses into an array - breaking out this step makes
2137 * over-riding more flexible as the clauses can be used in constructing a
2138 * temp table that may not be part of the final where clause or added
2139 * in other functions
2141 function storeWhereHavingClauseArray(){
2142 foreach ($this->_columns
as $tableName => $table) {
2143 if (array_key_exists('filters', $table)) {
2144 foreach ($table['filters'] as $fieldName => $field) {
2145 // respect pseudofield to filter spec so fields can be marked as
2146 // not to be handled here
2147 if(!empty($field['pseudofield'])){
2151 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2152 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2153 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2154 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2155 if (is_array($value) && !empty($value)) {
2156 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2160 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2161 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2162 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2163 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2164 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2165 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2169 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2171 $clause = $this->whereClause($field,
2173 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2174 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2175 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2180 if (!empty($clause)) {
2181 if (!empty($field['having'])) {
2182 $this->_havingClauses
[] = $clause;
2185 $this->_whereClauses
[] = $clause;
2193 function processReportMode() {
2194 $buttonName = $this->controller
->getButtonName();
2196 $output = CRM_Utils_Request
::retrieve(
2199 CRM_Core_DAO
::$_nullObject
2203 CRM_Utils_Request
::retrieve(
2206 CRM_Core_DAO
::$_nullObject
2209 $this->_absoluteUrl
= FALSE;
2211 $this->assign('printOnly', FALSE);
2213 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2214 $this->assign('printOnly', TRUE);
2216 $this->assign('outputMode', 'print');
2217 $this->_outputMode
= 'print';
2218 if ($this->_sendmail
) {
2219 $this->_absoluteUrl
= TRUE;
2222 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2223 $this->assign('printOnly', TRUE);
2225 $this->assign('outputMode', 'pdf');
2226 $this->_outputMode
= 'pdf';
2227 $this->_absoluteUrl
= TRUE;
2229 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2230 $this->assign('printOnly', TRUE);
2232 $this->assign('outputMode', 'csv');
2233 $this->_outputMode
= 'csv';
2234 $this->_absoluteUrl
= TRUE;
2236 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2237 $this->assign('outputMode', 'group');
2238 $this->_outputMode
= 'group';
2240 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2241 $this->assign('outputMode', 'create_report');
2242 $this->_outputMode
= 'create_report';
2245 $this->assign('outputMode', 'html');
2246 $this->_outputMode
= 'html';
2249 // Get today's date to include in printed reports
2251 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2252 $this->assign('reportDate', $reportDate);
2257 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2259 function beginPostProcess() {
2260 $this->setParams($this->controller
->exportValues($this->_name
));
2262 if (empty($this->_params
) &&
2265 $this->setParams($this->_formValues
);
2268 // hack to fix params when submitted from dashboard, CRM-8532
2269 // fields array is missing because form building etc is skipped
2270 // in dashboard mode for report
2271 //@todo - this could be done in the dashboard no we have a setter
2272 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2273 $this->setParams($this->_formValues
);
2276 $this->_formValues
= $this->_params
;
2277 if (CRM_Core_Permission
::check('administer Reports') &&
2278 isset($this->_id
) &&
2279 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2280 $this->_chartButtonName
== $this->controller
->getButtonName()
2283 $this->assign('updateReportButton', TRUE);
2285 $this->processReportMode();
2286 $this->beginPostProcessCommon();
2290 * beginPostProcess function run in both report mode and non-report mode (api)
2292 function beginPostProcessCommon() {
2297 * @param bool $applyLimit
2301 function buildQuery($applyLimit = TRUE) {
2304 $this->customDataFrom();
2309 // order_by columns not selected for display need to be included in SELECT
2310 $unselectedSectionColumns = $this->unselectedSectionColumns();
2311 foreach ($unselectedSectionColumns as $alias => $section) {
2312 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2315 if ($applyLimit && empty($this->_params
['charts'])) {
2318 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2320 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2324 function groupBy() {
2325 $groupBys = array();
2326 if (!empty($this->_params
['group_bys']) &&
2327 is_array($this->_params
['group_bys']) &&
2328 !empty($this->_params
['group_bys'])
2330 foreach ($this->_columns
as $tableName => $table) {
2331 if (array_key_exists('group_bys', $table)) {
2332 foreach ($table['group_bys'] as $fieldName => $field) {
2333 if (!empty($this->_params
['group_bys'][$fieldName])) {
2334 $groupBys[] = $field['dbAlias'];
2341 if (!empty($groupBys)) {
2342 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2346 function orderBy() {
2347 $this->_orderBy
= "";
2348 $this->_sections
= array();
2349 $this->storeOrderByArray();
2350 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2351 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2353 $this->assign('sections', $this->_sections
);
2357 * In some cases other functions want to know which fields are selected for ordering by
2358 * Separating this into a separate function allows it to be called separately from constructing
2359 * the order by clause
2361 function storeOrderByArray() {
2362 $orderBys = array();
2364 if (!empty($this->_params
['order_bys']) &&
2365 is_array($this->_params
['order_bys']) &&
2366 !empty($this->_params
['order_bys'])
2369 // Proces order_bys in user-specified order
2370 foreach ($this->_params
['order_bys'] as $orderBy) {
2371 $orderByField = array();
2372 foreach ($this->_columns
as $tableName => $table) {
2373 if (array_key_exists('order_bys', $table)) {
2374 // For DAO columns defined in $this->_columns
2375 $fields = $table['order_bys'];
2377 elseif (array_key_exists('extends', $table)) {
2378 // For custom fields referenced in $this->_customGroupExtends
2379 $fields = CRM_Utils_Array
::value('fields', $table, array());
2381 if (!empty($fields) && is_array($fields)) {
2382 foreach ($fields as $fieldName => $field) {
2383 if ($fieldName == $orderBy['column']) {
2384 $orderByField = array_merge($field, $orderBy);
2385 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2392 if (!empty($orderByField)) {
2393 $this->_orderByFields
[] = $orderByField;
2394 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2396 // Record any section headers for assignment to the template
2397 if (!empty($orderBy['section'])) {
2398 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2399 $this->_sections
[$orderByField['tplField']] = $orderByField;
2405 $this->_orderByArray
= $orderBys;
2407 $this->assign('sections', $this->_sections
);
2413 function unselectedSectionColumns() {
2414 $selectColumns = array();
2415 foreach ($this->_columns
as $tableName => $table) {
2416 if (array_key_exists('fields', $table)) {
2417 foreach ($table['fields'] as $fieldName => $field) {
2418 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2420 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2426 if (is_array($this->_sections
)) {
2427 return array_diff_key($this->_sections
, $selectColumns);
2438 function buildRows($sql, &$rows) {
2439 $dao = CRM_Core_DAO
::executeQuery($sql);
2440 if (!is_array($rows)) {
2444 // use this method to modify $this->_columnHeaders
2445 $this->modifyColumnHeaders();
2447 $unselectedSectionColumns = $this->unselectedSectionColumns();
2449 while ($dao->fetch()) {
2451 foreach ($this->_columnHeaders
as $key => $value) {
2452 if (property_exists($dao, $key)) {
2453 $row[$key] = $dao->$key;
2457 // section headers not selected for display need to be added to row
2458 foreach ($unselectedSectionColumns as $key => $values) {
2459 if (property_exists($dao, $key)) {
2460 $row[$key] = $dao->$key;
2469 * When "order by" fields are marked as sections, this assigns to the template
2470 * an array of total counts for each section. This data is used by the Smarty
2471 * plugin {sectionTotal}
2473 function sectionTotals() {
2475 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2476 if (empty($this->_selectAliases
)) {
2480 if (!empty($this->_sections
)) {
2481 // build the query with no LIMIT clause
2482 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2483 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2485 // pull section aliases out of $this->_sections
2486 $sectionAliases = array_keys($this->_sections
);
2489 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2490 $ifnulls[] = "ifnull($alias, '') as $alias";
2493 /* Group (un-limited) report by all aliases and get counts. This might
2494 * be done more efficiently when the contents of $sql are known, ie. by
2495 * overriding this method in the report class.
2499 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2501 // initialize array of total counts
2503 $dao = CRM_Core_DAO
::executeQuery($query);
2504 while ($dao->fetch()) {
2506 // let $this->_alterDisplay translate any integer ids to human-readable values.
2507 $rows[0] = $dao->toArray();
2508 $this->alterDisplay($rows);
2511 // add totals for all permutations of section values
2514 $aliasCount = count($sectionAliases);
2515 foreach ($sectionAliases as $alias) {
2516 $values[] = $row[$alias];
2517 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2518 if ($i == $aliasCount) {
2519 // the last alias is the lowest-level section header; use count as-is
2520 $totals[$key] = $dao->ct
;
2523 // other aliases are higher level; roll count into their total
2524 $totals[$key] +
= $dao->ct
;
2528 $this->assign('sectionTotals', $totals);
2532 function modifyColumnHeaders() {
2533 // use this method to modify $this->_columnHeaders
2539 function doTemplateAssignment(&$rows) {
2540 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2541 $this->assign_by_ref('rows', $rows);
2542 $this->assign('statistics', $this->statistics($rows));
2545 // override this method to build your own statistics
2551 function statistics(&$rows) {
2552 $statistics = array();
2554 $count = count($rows);
2556 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2560 $this->countStat($statistics, $count);
2562 $this->groupByStat($statistics);
2564 $this->filterStat($statistics);
2570 * @param $statistics
2573 function countStat(&$statistics, $count) {
2574 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2578 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2579 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2580 'value' => $this->_rowsFound
,
2586 * @param $statistics
2588 function groupByStat(&$statistics) {
2589 if (!empty($this->_params
['group_bys']) &&
2590 is_array($this->_params
['group_bys']) &&
2591 !empty($this->_params
['group_bys'])
2593 foreach ($this->_columns
as $tableName => $table) {
2594 if (array_key_exists('group_bys', $table)) {
2595 foreach ($table['group_bys'] as $fieldName => $field) {
2596 if (!empty($this->_params
['group_bys'][$fieldName])) {
2597 $combinations[] = $field['title'];
2602 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2603 'value' => implode(' & ', $combinations),
2609 * @param $statistics
2611 function filterStat(&$statistics) {
2612 foreach ($this->_columns
as $tableName => $table) {
2613 if (array_key_exists('filters', $table)) {
2614 foreach ($table['filters'] as $fieldName => $field) {
2615 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2618 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2619 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2620 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2621 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2622 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2624 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2625 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2627 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2628 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2631 $statistics['filters'][] = array(
2632 'title' => $field['title'],
2633 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2636 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2637 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2639 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2640 $statistics['filters'][] = array(
2641 'title' => $field['title'],
2642 'value' => $pair[$rel],
2647 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2650 $pair = $this->getOperationPair(
2651 CRM_Utils_Array
::value('operatorType', $field),
2654 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2655 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2656 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2657 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
2658 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2660 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
2661 $this->setEntityRefDefaults($field, $tableName);
2662 $result = civicrm_api3($field['attributes']['entity'], 'getlist', array('id' => $val) + CRM_Utils_Array
::value('api', $field['attributes'], array()));
2664 foreach ($result['values'] as $v) {
2665 $values[] = $v['label'];
2667 $value = "{$pair[$op]} " . implode(', ', $values);
2669 elseif ($op == 'nll' ||
$op == 'nnll') {
2670 $value = $pair[$op];
2672 elseif (is_array($val) && (!empty($val))) {
2673 $options = CRM_Utils_Array
::value('options', $field, array());
2674 foreach ($val as $key => $valIds) {
2675 if (isset($options[$valIds])) {
2676 $val[$key] = $options[$valIds];
2679 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2680 $val = implode(', ', $val);
2681 $value = "{$pair[$op]} " . $val;
2683 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2684 is_array($field['options']) && !empty($field['options'])
2686 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2689 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2693 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2706 function endPostProcess(&$rows = NULL) {
2707 if ( $this->_storeResultSet
) {
2708 $this->_resultSet
= $rows;
2711 if ($this->_outputMode
== 'print' ||
2712 $this->_outputMode
== 'pdf' ||
2716 $content = $this->compileContent();
2717 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2721 if ($this->_sendmail
) {
2722 $config = CRM_Core_Config
::singleton();
2723 $attachments = array();
2725 if ($this->_outputMode
== 'csv') {
2726 $content = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') . ": {$url}</p>" . '<p>' . ts('The report is attached as a CSV file.') . '</p>' . $this->_formValues
['report_footer'];
2728 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2729 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2730 file_put_contents($csvFullFilename, $csvContent);
2731 $attachments[] = array(
2732 'fullPath' => $csvFullFilename,
2733 'mime_type' => 'text/csv',
2734 'cleanName' => 'CiviReport.csv',
2737 if ($this->_outputMode
== 'pdf') {
2738 // generate PDF content
2739 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2740 file_put_contents($pdfFullFilename,
2741 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2742 TRUE, array('orientation' => 'landscape')
2745 // generate Email Content
2746 $content = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') . ": {$url}</p>" . '<p>' . ts('The report is attached as a PDF file.') . '</p>' . $this->_formValues
['report_footer'];
2748 $attachments[] = array(
2749 'fullPath' => $pdfFullFilename,
2750 'mime_type' => 'application/pdf',
2751 'cleanName' => 'CiviReport.pdf',
2755 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2756 $this->_outputMode
, $attachments
2758 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2761 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2765 elseif ($this->_outputMode
== 'print') {
2769 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2770 $config = CRM_Core_Config
::singleton();
2771 //get chart image name
2772 $chartImg = $this->_chartId
. '.png';
2773 //get image url path
2774 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2775 $uploadUrl .= $chartImg;
2776 //get image doc path to overwrite
2777 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2779 $chart = imagecreatefrompng($uploadUrl);
2780 //convert it into formattd png
2781 header('Content-type: image/png');
2782 //overwrite with same image
2783 imagepng($chart, $uploadImg);
2785 imagedestroy($chart);
2787 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2789 CRM_Utils_System
::civiExit();
2791 elseif ($this->_outputMode
== 'csv') {
2792 CRM_Report_Utils_Report
::export2csv($this, $rows);
2794 elseif ($this->_outputMode
== 'group') {
2795 $group = $this->_params
['groups'];
2796 $this->add2group($group);
2798 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2799 CRM_Report_Form_Instance
::postProcess($this);
2801 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2802 $this->_outputMode
== 'create_report' ) {
2803 $this->_createNew
= TRUE;
2804 CRM_Report_Form_Instance
::postProcess($this);
2808 function storeResultSet() {
2809 $this->_storeResultSet
= TRUE;
2815 function getResultSet() {
2816 return $this->_resultSet
;
2820 * Get Template file name - use default form template if a specific one has not been set up for this report
2824 * Use the form name to create the tpl file name
2832 function getTemplateFileName(){
2833 $defaultTpl = parent
::getTemplateFileName();
2834 $template = CRM_Core_Smarty
::singleton();
2835 if (!$template->template_exists($defaultTpl)) {
2836 $defaultTpl = 'CRM/Report/Form.tpl';
2842 * Compile the report content
2844 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2849 function compileContent(){
2850 $templateFile = $this->getHookedTemplateFileName();
2851 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2855 function postProcess() {
2856 // get ready with post process params
2857 $this->beginPostProcess();
2860 $sql = $this->buildQuery();
2862 // build array of result based on column headers. This method also allows
2863 // modifying column headers before using it to build result set i.e $rows.
2865 $this->buildRows($sql, $rows);
2867 // format result set.
2868 $this->formatDisplay($rows);
2870 // assign variables to templates
2871 $this->doTemplateAssignment($rows);
2873 // do print / pdf / instance stuff if needed
2874 $this->endPostProcess($rows);
2878 * @param int $rowCount
2880 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2881 // lets do the pager if in html mode
2882 $this->_limit
= NULL;
2884 // CRM-14115, over-ride row count if rowCount is specified in URL
2885 if ($this->_dashBoardRowCount
) {
2886 $rowCount = $this->_dashBoardRowCount
;
2888 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2889 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2891 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2893 if (!$pageId && !empty($_POST)) {
2894 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2895 $pageId = max((int)@$_POST['crmPID_B'], 1);
2897 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2898 $pageId = max((int)@$_POST['crmPID'], 1);
2900 unset($_POST['crmPID_B'], $_POST['crmPID']);
2903 $pageId = $pageId ?
$pageId : 1;
2904 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2905 $offset = ($pageId - 1) * $rowCount;
2907 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2908 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2910 $this->_limit
= " LIMIT $offset, $rowCount";
2911 return array($offset, $rowCount);
2913 if($this->_limitValue
) {
2914 if($this->_offsetValue
) {
2915 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2918 $this->_limit
= " LIMIT " . $this->_limitValue
;
2924 * @param int $rowCount
2926 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2928 // CRM-14115, over-ride row count if rowCount is specified in URL
2929 if ($this->_dashBoardRowCount
) {
2930 $rowCount = $this->_dashBoardRowCount
;
2933 if ($this->_limit
&& ($this->_limit
!= '')) {
2934 $sql = "SELECT FOUND_ROWS();";
2935 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2937 'total' => $this->_rowsFound
,
2938 'rowCount' => $rowCount,
2939 'status' => ts('Records') . ' %%StatusMessage%%',
2940 'buttonBottom' => 'PagerBottomButton',
2941 'buttonTop' => 'PagerTopButton',
2942 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2945 $pager = new CRM_Utils_Pager($params);
2946 $this->assign_by_ref('pager', $pager);
2947 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2958 function whereGroupClause($field, $value, $op) {
2960 $smartGroupQuery = "";
2962 $group = new CRM_Contact_DAO_Group();
2963 $group->is_active
= 1;
2965 $smartGroups = array();
2966 while ($group->fetch()) {
2967 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2968 $smartGroups[] = $group->id
;
2972 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2974 $smartGroupQuery = '';
2975 if (!empty($smartGroups)) {
2976 $smartGroups = implode(',', $smartGroups);
2977 $smartGroupQuery = " UNION DISTINCT
2978 SELECT DISTINCT smartgroup_contact.contact_id
2979 FROM civicrm_group_contact_cache smartgroup_contact
2980 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2983 $sqlOp = $this->getSQLOperator($op);
2984 if (!is_array($value)) {
2985 $value = array($value);
2987 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2989 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2990 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2991 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2992 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2993 {$smartGroupQuery} ) ";
3003 function whereTagClause($field, $value, $op) {
3004 // not using left join in query because if any contact
3005 // belongs to more than one tag, results duplicate
3007 $sqlOp = $this->getSQLOperator($op);
3008 if (!is_array($value)) {
3009 $value = array($value);
3011 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3013 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3014 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3015 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3016 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
3019 function whereMembershipOrgClause($field, $value, $op) {
3020 $sqlOp = $this->getSQLOperator($op);
3021 if (!is_array($value)) {
3022 $value = array($value);
3025 $tmp_membership_org_sql_list = implode(', ', $value);
3026 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3027 SELECT DISTINCT mem.contact_id
3028 FROM civicrm_membership mem
3029 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3030 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3031 WHERE mt.member_of_contact_id IN (".$tmp_membership_org_sql_list.")
3032 AND mt.is_active = '1'
3033 AND mem_status.is_current_member = '1'
3034 AND mem_status.is_active = '1' ) ";
3037 function whereMembershipTypeClause($field, $value, $op) {
3038 $sqlOp = $this->getSQLOperator($op);
3039 if (!is_array($value)) {
3040 $value = array($value);
3043 $tmp_membership_sql_list = implode(', ', $value);
3044 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3045 SELECT DISTINCT mem.contact_id
3046 FROM civicrm_membership mem
3047 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3048 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3049 WHERE mem.membership_type_id IN (".$tmp_membership_sql_list.")
3050 AND mt.is_active = '1'
3051 AND mem_status.is_current_member = '1'
3052 AND mem_status.is_active = '1' ) ";
3056 * @param string $tableAlias
3058 function buildACLClause($tableAlias = 'contact_a') {
3059 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3063 * @param bool $addFields
3064 * @param array $permCustomGroupIds
3066 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3067 if (empty($this->_customGroupExtends
)) {
3070 if (!is_array($this->_customGroupExtends
)) {
3071 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3073 $customGroupWhere = '';
3074 if (!empty($permCustomGroupIds)) {
3075 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
3078 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3079 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3080 FROM civicrm_custom_group cg
3081 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3082 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3084 cg.is_active = 1 AND
3085 cf.is_active = 1 AND
3086 cf.is_searchable = 1
3087 ORDER BY cg.weight, cf.weight";
3088 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3091 while ($customDAO->fetch()) {
3092 if ($customDAO->table_name
!= $curTable) {
3093 $curTable = $customDAO->table_name
;
3094 $curFields = $curFilters = array();
3097 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3098 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3099 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3100 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3103 'fields', 'filters', 'group_bys') as $colKey) {
3104 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3105 $this->_columns
[$curTable][$colKey] = array();
3109 $fieldName = 'custom_' . $customDAO->cf_id
;
3112 // this makes aliasing work in favor
3113 $curFields[$fieldName] = array(
3114 'name' => $customDAO->column_name
,
3115 'title' => $customDAO->label
,
3116 'dataType' => $customDAO->data_type
,
3117 'htmlType' => $customDAO->html_type
,
3120 if ($this->_customGroupFilters
) {
3121 // this makes aliasing work in favor
3122 $curFilters[$fieldName] = array(
3123 'name' => $customDAO->column_name
,
3124 'title' => $customDAO->label
,
3125 'dataType' => $customDAO->data_type
,
3126 'htmlType' => $customDAO->html_type
,
3130 switch ($customDAO->data_type
) {
3133 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3134 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3135 // CRM-6946, show time part for datetime date fields
3136 if ($customDAO->time_format
) {
3137 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3142 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3143 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
3147 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3151 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3152 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3156 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3157 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3161 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3162 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3166 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3168 if (!empty($customDAO->option_group_id
)) {
3169 if (in_array($customDAO->html_type
, array(
3170 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
3171 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3174 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3176 if ($this->_customGroupFilters
) {
3177 $curFilters[$fieldName]['options'] = array();
3178 $ogDAO = CRM_Core_DAO
::executeQuery("SELECT ov.value, ov.label FROM civicrm_option_value ov WHERE ov.option_group_id = %1 ORDER BY ov.weight", array(1 => array($customDAO->option_group_id
, 'Integer')));
3179 while ($ogDAO->fetch()) {
3180 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3186 case 'StateProvince':
3187 if (in_array($customDAO->html_type
, array(
3188 'Multi-Select State/Province'))) {
3189 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3192 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3194 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3198 if (in_array($customDAO->html_type
, array(
3199 'Multi-Select Country'))) {
3200 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3203 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3205 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3208 case 'ContactReference':
3209 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3210 $curFilters[$fieldName]['name'] = 'display_name';
3211 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3213 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3214 $curFields[$fieldName]['name'] = 'display_name';
3215 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3219 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3220 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3223 if (!array_key_exists('type', $curFields[$fieldName])) {
3224 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3228 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3230 if ($this->_customGroupFilters
) {
3231 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3233 if ($this->_customGroupGroupBy
) {
3234 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3239 function customDataFrom() {
3240 if (empty($this->_customGroupExtends
)) {
3243 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3245 foreach ($this->_columns
as $table => $prop) {
3246 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
3247 $extendsTable = $mapper[$prop['extends']];
3249 // check field is in params
3250 if (!$this->isFieldSelected($prop)) {
3253 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3255 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3257 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3258 // handle for ContactReference
3259 if (array_key_exists('fields', $prop)) {
3260 foreach ($prop['fields'] as $fieldName => $field) {
3261 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
3262 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3264 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3277 function isFieldSelected($prop) {
3282 if (!empty($this->_params
['fields'])) {
3283 foreach (array_keys($prop['fields']) as $fieldAlias) {
3284 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3285 if ($customFieldId) {
3286 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3290 //might be survey response field.
3291 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3298 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3299 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3300 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3306 if (!empty($this->_params
['order_bys'])) {
3307 foreach (array_keys($prop['fields']) as $fieldAlias) {
3308 foreach ($this->_params
['order_bys'] as $orderBy) {
3309 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3316 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3317 foreach ($prop['filters'] as $fieldAlias => $val) {
3319 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3320 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3321 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3322 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3328 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3329 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3340 * Check for empty order_by configurations and remove them; also set
3341 * template to hide them.
3343 function preProcessOrderBy(&$formValues) {
3344 // Object to show/hide form elements
3345 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3347 $_showHide->addShow('optionField_1');
3349 // Cycle through order_by options; skip any empty ones, and hide them as well
3352 if (!empty($formValues['order_bys'])) {
3353 foreach ($formValues['order_bys'] as $order_by) {
3354 if ($order_by['column'] && $order_by['column'] != '-') {
3355 $_showHide->addShow('optionField_' . $n);
3356 $orderBys[$n] = $order_by;
3361 for ($i = $n; $i <= 5; $i++
) {
3363 $_showHide->addHide('optionField_' . $i);
3367 // overwrite order_by options with modified values
3368 if (!empty($orderBys)) {
3369 $formValues['order_bys'] = $orderBys;
3372 $formValues['order_bys'] = array(1 => array('column' => '-'));
3375 // assign show/hide data to template
3376 $_showHide->addToTemplate();
3380 * Does table name have columns in SELECT clause?
3382 * @param string $tableName Name of table (index of $this->_columns array)
3386 function isTableSelected($tableName) {
3387 return in_array($tableName, $this->selectedTables());
3391 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3392 * (building the array if it's unset)
3394 * @return Array $this->_selectedTables
3396 function selectedTables() {
3397 if (!$this->_selectedTables
) {
3398 $orderByColumns = array();
3399 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3400 foreach ($this->_params
['order_bys'] as $orderBy) {
3401 $orderByColumns[] = $orderBy['column'];
3405 foreach ($this->_columns
as $tableName => $table) {
3406 if (array_key_exists('fields', $table)) {
3407 foreach ($table['fields'] as $fieldName => $field) {
3408 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3409 $this->_selectedTables
[] = $tableName;
3414 if (array_key_exists('order_bys', $table)) {
3415 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3416 if (in_array($orderByName, $orderByColumns)) {
3417 $this->_selectedTables
[] = $tableName;
3422 if (array_key_exists('filters', $table)) {
3423 foreach ($table['filters'] as $filterName => $filter) {
3424 if (!empty($this->_params
["{$filterName}_value"]) ||
3425 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3426 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3428 $this->_selectedTables
[] = $tableName;
3435 return $this->_selectedTables
;
3439 * @deprecated - use getAddressColumns which is a more accurate description
3440 * and also accepts an array of options rather than a long list
3442 * function for adding address fields to construct function in reports
3444 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3445 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3446 * @param bool $filters
3447 * @param array $defaults
3449 * @return array address fields for construct clause
3451 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3452 $addressFields = array(
3453 'civicrm_address' =>
3455 'dao' => 'CRM_Core_DAO_Address',
3459 array('title' => ts('Address Name'),
3460 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3463 array('title' => ts('Street Address'),
3464 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3466 'supplemental_address_1' =>
3467 array('title' => ts('Supplementary Address Field 1'),
3468 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3470 'supplemental_address_2' =>
3471 array('title' => ts('Supplementary Address Field 2'),
3472 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3476 'name' => 'street_number',
3477 'title' => ts('Street Number'),
3479 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3483 'name' => 'street_name',
3484 'title' => ts('Street Name'),
3486 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3490 'name' => 'street_unit',
3491 'title' => ts('Street Unit'),
3493 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3496 array('title' => ts('City'),
3497 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3500 array('title' => ts('Postal Code'),
3501 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3503 'postal_code_suffix' =>
3504 array('title' => ts('Postal Code Suffix'),
3505 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3508 array('title' => ts('Country'),
3509 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3511 'state_province_id' =>
3512 array('title' => ts('State/Province'),
3513 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3516 array('title' => ts('County'),
3517 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3520 'grouping' => 'location-fields',
3525 $addressFields['civicrm_address']['filters'] = array(
3526 'street_number' => array('title' => ts('Street Number'),
3528 'name' => 'street_number',
3530 'street_name' => array('title' => ts('Street Name'),
3531 'name' => 'street_name',
3532 'operator' => 'like',
3534 'postal_code' => array('title' => ts('Postal Code'),
3536 'name' => 'postal_code',
3538 'city' => array('title' => ts('City'),
3539 'operator' => 'like',
3542 'country_id' => array(
3543 'name' => 'country_id',
3544 'title' => ts('Country'),
3545 'type' => CRM_Utils_Type
::T_INT
,
3547 CRM_Report_Form
::OP_MULTISELECT
,
3548 'options' => CRM_Core_PseudoConstant
::country(),
3550 'state_province_id' => array(
3551 'name' => 'state_province_id',
3552 'title' => ts('State/Province'),
3553 'type' => CRM_Utils_Type
::T_INT
,
3554 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3555 'options' => array(),
3557 'county_id' => array(
3558 'name' => 'county_id',
3559 'title' => ts('County'),
3560 'type' => CRM_Utils_Type
::T_INT
,
3561 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3562 'options' => array(),
3568 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3569 'street_number' => array('title' => 'Odd / Even Street Number'),
3570 'street_address' => NULL,
3572 'postal_code' => NULL,
3577 $addressFields['civicrm_address']['group_bys'] = array(
3578 'street_address' => NULL,
3580 'postal_code' => NULL,
3581 'state_province_id' =>
3582 array('title' => ts('State/Province'),
3585 array('title' => ts('Country'),
3588 array('title' => ts('County'),
3592 return $addressFields;
3596 * Do AlterDisplay processing on Address Fields
3607 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3608 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3609 $entryFound = FALSE;
3611 if (array_key_exists('civicrm_address_country_id', $row)) {
3612 if ($value = $row['civicrm_address_country_id']) {
3613 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3614 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3615 "reset=1&force=1&{$criteriaQueryParams}&" .
3616 "country_id_op=in&country_id_value={$value}",
3617 $this->_absoluteUrl
, $this->_id
3619 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3620 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3627 if (array_key_exists('civicrm_address_county_id', $row)) {
3628 if ($value = $row['civicrm_address_county_id']) {
3629 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3630 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3631 "reset=1&force=1&{$criteriaQueryParams}&" .
3632 "county_id_op=in&county_id_value={$value}",
3633 $this->_absoluteUrl
, $this->_id
3635 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3636 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3642 // handle state province
3643 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3644 if ($value = $row['civicrm_address_state_province_id']) {
3645 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3647 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3648 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3649 $this->_absoluteUrl
, $this->_id
3651 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3652 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3663 * Adjusts dates passed in to YEAR() for fiscal year.
3670 function fiscalYearOffset($fieldName) {
3671 $config = CRM_Core_Config
::singleton();
3672 $fy = $config->fiscalYearStart
;
3673 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3674 return "YEAR( $fieldName )";
3676 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3680 * Add Address into From Table if required
3682 function addAddressFromClause() {
3683 // include address field if address column is to be included
3684 if ((isset($this->_addressField
) &&
3685 $this->_addressField
3687 $this->isTableSelected('civicrm_address')
3690 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3691 ON ({$this->_aliases['civicrm_contact']}.id =
3692 {$this->_aliases['civicrm_address']}.contact_id) AND
3693 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3698 * Add Phone into From Table if required
3700 function addPhoneFromClause() {
3701 // include address field if address column is to be included
3702 if ($this->isTableSelected('civicrm_phone')
3705 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3706 ON ({$this->_aliases['civicrm_contact']}.id =
3707 {$this->_aliases['civicrm_phone']}.contact_id) AND
3708 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3713 * Get phone columns to add to array
3714 * @param array $options
3715 * - prefix Prefix to add to table (in case of more than one instance of the table)
3716 * - prefix_label Label to give columns from this phone table instance
3717 * @return array phone columns definition
3719 function getPhoneColumns($options = array()){
3720 $defaultOptions = array(
3722 'prefix_label' => '',
3725 $options = array_merge($defaultOptions,$options);
3728 $options['prefix'] . 'civicrm_phone' => array(
3729 'dao' => 'CRM_Core_DAO_Phone',
3731 $options['prefix'] . 'phone' => array(
3732 'title' => ts($options['prefix_label'] . 'Phone'),
3742 * Get address columns to add to array
3743 * @param array $options
3744 * - prefix Prefix to add to table (in case of more than one instance of the table)
3745 * - prefix_label Label to give columns from this address table instance
3746 * @return array address columns definition
3748 function getAddressColumns($options = array()) {
3751 'prefix_label' => '',
3755 'defaults' => array(),
3757 return $this->addAddressFields(
3758 $options['group_by'],
3759 $options['order_by'],
3760 $options['filters'],
3761 $options['defaults']
3768 function add2group($groupID) {
3769 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3770 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3771 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3773 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3774 $dao = CRM_Core_DAO
::executeQuery($sql);
3776 $contact_ids = array();
3777 // Add resulting contacts to group
3778 while ($dao->fetch()) {
3779 if ($dao->addtogroup_contact_id
) {
3780 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3784 if ( !empty($contact_ids) ) {
3785 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3786 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3789 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3794 /* function used for showing charts on print screen */
3795 static function uploadChartImage() {
3796 // upload strictly for '.png' images
3797 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3798 if (preg_match('/\.png$/', $name)) {
3800 // POST data is usually string data, but we are passing a RAW .png
3801 // so PHP is a bit confused and $_POST is empty. But it has saved
3802 // the raw bits into $HTTP_RAW_POST_DATA
3804 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3806 // prepare the directory
3807 $config = CRM_Core_Config
::singleton();
3808 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3809 if (!file_exists($defaultPath)) {
3810 mkdir($defaultPath, 0777, TRUE);
3813 // full path to the saved image including filename
3814 $destination = $defaultPath . $name;
3817 $jfh = fopen($destination, 'w') or die("can't open file");
3818 fwrite($jfh, $httpRawPostData);
3820 CRM_Utils_System
::civiExit();
3825 * Apply common settings to entityRef fields
3826 * @param array $field
3827 * @param string $table
3829 private function setEntityRefDefaults(&$field, $table) {
3830 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
3831 $field['attributes'] +
= array(
3832 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
3834 'placeholder' => ts('- select -'),