3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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,
53 * The id of the report instance
60 * The id of the report template
64 protected $_templateID;
72 protected $_noFields = FALSE;
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attribues as the value
80 protected $_columns = array();
83 * The set of filters in the report
87 protected $_filters = array();
90 * The set of optional columns in the report
94 protected $_options = array();
96 protected $_defaults = array();
99 * By default most reports hide contact id.
100 * Setting this to true makes it available
102 protected $_exposeContactID = TRUE;
105 * Set of statistic fields
109 protected $_statFields = array();
112 * Set of statistics data
116 protected $_statistics = array();
119 * List of fields not to be repeated during display
123 protected $_noRepeats = array();
126 * List of fields not to be displayed
130 protected $_noDisplay = array();
133 * Object type that a custom group extends
137 protected $_customGroupExtends = NULL;
138 protected $_customGroupFilters = TRUE;
139 protected $_customGroupGroupBy = FALSE;
140 protected $_customGroupJoin = 'LEFT JOIN';
146 protected $_tagFilter = FALSE;
149 * build groups filter
152 protected $_groupFilter = FALSE;
159 public $_navigation = array();
161 public $_drilldownReport = array();
164 * An attribute for checkbox/radio form field layout
168 protected $_fourColumnAttribute = array(
169 '</td><td width="25%">', '</td><td width="25%">',
170 '</td><td width="25%">', '</tr><tr><td>',
173 protected $_force = 1;
175 protected $_params = NULL;
176 protected $_formValues = NULL;
177 protected $_instanceValues = NULL;
179 protected $_instanceForm = FALSE;
180 protected $_criteriaForm = FALSE;
182 protected $_instanceButtonName = NULL;
183 protected $_createNewButtonName = NULL;
184 protected $_printButtonName = NULL;
185 protected $_pdfButtonName = NULL;
186 protected $_csvButtonName = NULL;
187 protected $_groupButtonName = NULL;
188 protected $_chartButtonName = NULL;
189 protected $_csvSupported = TRUE;
190 protected $_add2groupSupported = TRUE;
191 protected $_groups = NULL;
192 protected $_grandFlag = FALSE;
193 protected $_rowsFound = NULL;
194 protected $_selectAliases = array();
195 protected $_rollup = NULL;
196 protected $_limit = NULL;
197 protected $_sections = NULL;
198 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
199 protected $_absoluteUrl = FALSE;
202 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
206 protected $_storeResultSet = FALSE;
209 * When _storeResultSet Flag is set use this var to store result set in form of array
213 protected $_resultSet = array();
216 * To what frequency group-by a date column
220 protected $_groupByDateFreq = array(
222 'YEARWEEK' => 'Week',
223 'QUARTER' => 'Quarter',
228 * Variables to hold the acl inner join and where clause
230 protected $_aclFrom = NULL;
231 protected $_aclWhere = NULL;
234 * Array of DAO tables having columns included in SELECT or ORDER BY clause
238 protected $_selectedTables;
240 public $_having = NULL;
241 public $_select = NULL;
242 public $_selectClauses = array();
243 public $_columnHeaders = array();
244 public $_orderBy = NULL;
245 public $_orderByFields = array();
246 public $_orderByArray = array();
247 public $_groupBy = NULL;
248 public $_whereClauses = array();
249 public $_havingClauses = array();
252 * Variable to hold the currency alias
254 protected $_currencyColumn = NULL;
259 function __construct() {
260 parent
::__construct();
263 if ($this->_tagFilter
) {
264 $this->buildTagFilter();
266 if ($this->_exposeContactID
) {
267 if (array_key_exists('civicrm_contact', $this->_columns
)) {
268 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
270 'title' => 'Contact ID',
276 if ($this->_groupFilter
) {
277 $this->buildGroupFilter();
280 // Get all custom groups
281 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
283 // Get the custom groupIds for which the user has VIEW permission
284 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
285 // and addCustomDataToColumns() will allow access to all custom groups.
286 $permCustomGroupIds = array();
287 if (!CRM_Core_Permission
::check('access all custom data')) {
288 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
289 // do not allow custom data for reports if user doesn't have
290 // permission to access custom data.
291 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
292 $this->_customGroupExtends
= array();
296 // merge custom data columns to _columns list, if any
297 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
299 // add / modify display columns, filters ..etc
300 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
302 //assign currencyColumn variable to tpl
303 $this->assign('currencyColumn', $this->_currencyColumn
);
306 function preProcessCommon() {
308 CRM_Utils_Request
::retrieve(
311 CRM_Core_DAO
::$_nullObject
314 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
316 $this->assign('section', $this->_section
);
317 CRM_Core_Region
::instance('page-header')->add(array(
318 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
321 $this->_id
= $this->get('instanceId');
323 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
325 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
329 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
330 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
331 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
334 $this->assign('instanceId', $this->_id
);
335 $params = array('id' => $this->_id
);
336 $this->_instanceValues
= array();
337 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
339 $this->_instanceValues
341 if (empty($this->_instanceValues
)) {
342 CRM_Core_Error
::fatal("Report could not be loaded.");
345 if (!empty($this->_instanceValues
['permission']) &&
346 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
347 CRM_Core_Permission
::check('administer Reports')
350 CRM_Utils_System
::permissionDenied();
351 CRM_Utils_System
::civiExit();
354 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
356 $this->_formValues
= unserialize($formValues);
359 $this->_formValues
= NULL;
362 // lets always do a force if reset is found in the url.
363 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
368 $this->assign('mode', 'instance');
371 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
372 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
373 if (($instanceCount > 0) && $optionValueID) {
374 $this->assign('instanceUrl',
375 CRM_Utils_System
::url('civicrm/report/list',
376 "reset=1&ovid=$optionValueID"
380 if ($optionValueID) {
381 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
385 $this->assign('mode', 'template');
388 // lets display the Report Settings section
389 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
391 // Do not display Report Settings section if administer Reports permission is absent OR
392 // if report instance is reserved and administer reserved reports absent
393 if (!CRM_Core_Permission
::check('administer Reports') ||
394 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
395 $this->_instanceForm
= FALSE;
398 $this->assign('criteriaForm', FALSE);
399 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
400 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
401 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
402 $this->assign('criteriaForm', TRUE);
403 $this->_criteriaForm
= TRUE;
407 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
408 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
409 $this->_printButtonName
= $this->getButtonName('submit', 'print');
410 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
411 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
412 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
413 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
416 function addBreadCrumb() {
420 'title' => ts('Report Templates'),
421 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
425 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
428 function preProcess() {
429 $this->preProcessCommon();
432 $this->addBreadCrumb();
435 foreach ($this->_columns
as $tableName => $table) {
437 if (!isset($table['alias'])) {
438 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
441 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
444 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
446 $daoOrBaoName = NULL;
447 // higher preference to bao object
448 if (array_key_exists('bao', $table)) {
449 $daoOrBaoName = $table['bao'];
450 $expFields = $daoOrBaoName::exportableFields( );
452 elseif (array_key_exists('dao', $table)){
453 $daoOrBaoName = $table['dao'];
454 $expFields = $daoOrBaoName::export( );
457 $expFields = array();
460 $doNotCopy = array('required');
462 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
463 foreach ($fieldGroups as $fieldGrp) {
464 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
465 foreach ($table[$fieldGrp] as $fieldName => $field) {
466 // $name is the field name used to reference the BAO/DAO export fields array
467 $name = isset($field['name']) ?
$field['name'] : $fieldName;
469 // Sometimes the field name key in the BAO/DAO export fields array is
470 // different from the actual database field name.
471 // Unset $field['name'] so that actual database field name can be obtained
472 // from the BAO/DAO export fields array.
473 unset($field['name']);
475 if (array_key_exists($name, $expFields)) {
476 foreach ($doNotCopy as $dnc) {
477 // unset the values we don't want to be copied.
478 unset($expFields[$name][$dnc]);
481 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
484 foreach ($expFields[$name] as $property => $val) {
485 if (!array_key_exists($property, $field)) {
486 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
493 if (CRM_Utils_Array
::value('no_repeat', $field)) {
494 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
496 if (CRM_Utils_Array
::value('no_display', $field)) {
497 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
500 // set alias = table-name, unless already set
501 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
502 $this->_columns
[$tableName]['alias'] : $tableName
504 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
506 // set name = fieldName, unless already set
507 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
508 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
511 // set dbAlias = alias.name, unless already set
512 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
513 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
516 // a few auto fills for filters
517 if ($fieldGrp == 'filters') {
518 // fill operator types
519 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
520 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
521 case CRM_Utils_Type
::T_MONEY
:
522 case CRM_Utils_Type
::T_FLOAT
:
523 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
525 case CRM_Utils_Type
::T_INT
:
526 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
528 case CRM_Utils_Type
::T_DATE
:
529 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
531 case CRM_Utils_Type
::T_BOOLEAN
:
532 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
533 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
534 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
535 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
540 (array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
541 ||
array_key_exists('enumValues', $this->_columns
[$tableName][$fieldGrp][$fieldName]))
543 // with multiple options operator-type is generally multi-select
544 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
545 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
547 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
558 // copy filters to a separate handy variable
559 if (array_key_exists('filters', $table)) {
560 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
563 if (array_key_exists('group_bys', $table)) {
564 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
567 if (array_key_exists('fields', $table)) {
568 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
573 $this->setDefaultValues(FALSE);
576 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
577 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
578 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
579 CRM_Report_Utils_Get
::processChart($this->_defaults
);
582 $this->_formValues
= $this->_defaults
;
583 $this->postProcess();
587 function setDefaultValues($freeze = TRUE) {
588 $freezeGroup = array();
590 // FIXME: generalizing form field naming conventions would reduce
591 // lots of lines below.
592 foreach ($this->_columns
as $tableName => $table) {
593 if (array_key_exists('fields', $table)) {
594 foreach ($table['fields'] as $fieldName => $field) {
595 if (!CRM_Utils_Array
::value('no_display', $field)) {
596 if (isset($field['required'])) {
598 $this->_defaults
['fields'][$fieldName] = 1;
601 // find element object, so that we could use quickform's freeze method
602 // for required elements
603 $obj = $this->getElementFromGroup("fields", $fieldName);
605 $freezeGroup[] = $obj;
609 elseif (isset($field['default'])) {
610 $this->_defaults
['fields'][$fieldName] = $field['default'];
616 if (array_key_exists('group_bys', $table)) {
617 foreach ($table['group_bys'] as $fieldName => $field) {
618 if (isset($field['default'])) {
619 if (CRM_Utils_Array
::value('frequency', $field)) {
620 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
622 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
626 if (array_key_exists('filters', $table)) {
627 foreach ($table['filters'] as $fieldName => $field) {
628 if (isset($field['default'])) {
629 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
630 if(is_array($field['default'])){
631 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
632 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
633 $this->_defaults
["{$fieldName}_relative"] = 0;
636 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
640 $this->_defaults
["{$fieldName}_value"] = $field['default'];
643 //assign default value as "in" for multiselect
644 //operator, To freeze the select element
645 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
646 $this->_defaults
["{$fieldName}_op"] = 'in';
648 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
649 $this->_defaults
["{$fieldName}_op"] = 'mhas';
651 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
652 $this->_defaults
["{$fieldName}_op"] = $op;
658 array_key_exists('order_bys', $table) &&
659 is_array($table['order_bys'])
661 if (!array_key_exists('order_bys', $this->_defaults
)) {
662 $this->_defaults
['order_bys'] = array();
664 foreach ($table['order_bys'] as $fieldName => $field) {
666 CRM_Utils_Array
::value('default', $field) ||
667 CRM_Utils_Array
::value('default_order', $field) ||
668 CRM_Utils_Array
::value('default_is_section', $field) ||
669 CRM_Utils_Array
::value('default_weight', $field)
672 'column' => $fieldName,
673 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
674 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
677 if (CRM_Utils_Array
::value('default_weight', $field)) {
678 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
681 array_unshift($this->_defaults
['order_bys'], $order_by);
687 foreach ($this->_options
as $fieldName => $field) {
688 if (isset($field['default'])) {
689 $this->_defaults
['options'][$fieldName] = $field['default'];
694 if (!empty($this->_submitValues
)) {
695 $this->preProcessOrderBy($this->_submitValues
);
698 $this->preProcessOrderBy($this->_defaults
);
701 // lets finish freezing task here itself
702 if (!empty($freezeGroup)) {
703 foreach ($freezeGroup as $elem) {
708 if ($this->_formValues
) {
709 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
712 if ($this->_instanceValues
) {
713 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
716 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
718 return $this->_defaults
;
721 function getElementFromGroup($group, $grpFieldName) {
722 $eleObj = $this->getElement($group);
723 foreach ($eleObj->_elements
as $index => $obj) {
724 if ($grpFieldName == $obj->_attributes
['name']) {
731 function addColumns() {
734 foreach ($this->_columns
as $tableName => $table) {
735 if (array_key_exists('fields', $table)) {
736 foreach ($table['fields'] as $fieldName => $field) {
738 if (!CRM_Utils_Array
::value('no_display', $field)) {
739 foreach ( array('table', 'field') as $var) {
740 if (!empty($
{$var}['grouping'])) {
741 if (!is_array($
{$var}['grouping'])) {
742 $tableName = $
{$var}['grouping'];
744 $tableName = array_keys($
{$var}['grouping']);
745 $tableName = $tableName[0];
746 $groupTitle = array_values($
{$var}['grouping']);
747 $groupTitle = $groupTitle[0];
752 if (!$groupTitle && isset($table['group_title'])) {
753 $groupTitle = $table['group_title'];
756 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
757 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
758 $colGroups[$tableName]['group_title'] = $groupTitle;
761 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
767 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
768 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
770 $this->assign('colGroups', $colGroups);
773 function addFilters() {
774 $options = $filters = array();
776 foreach ($this->_filters
as $table => $attributes) {
777 foreach ($attributes as $fieldName => $field) {
778 // get ready with option value pair
779 // @ 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
781 $operations = $this->getOperationPair(
782 CRM_Utils_Array
::value('operatorType', $field),
785 $filters[$table][$fieldName] = $field;
787 switch (CRM_Utils_Array
::value('operatorType', $field)) {
788 case CRM_Report_Form
::OP_MONTH
:
789 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
790 // If there's no option list for this filter, define one.
791 $field['options'] = array(
800 9 => ts('September'),
802 11 => ts('November'),
803 12 => ts('December'),
805 // Add this option list to this column _columns. This is
806 // required so that filter statistics show properly.
807 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
809 case CRM_Report_FORM
::OP_MULTISELECT
:
810 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
811 // assume a multi-select field
812 if (!empty($field['options'])) {
813 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
814 if (count($operations) <= 1) {
817 $select = $this->addElement('select', "{$fieldName}_value", NULL,
818 $field['options'], array(
820 'style' => 'min-width:250px',
823 $select->setMultiple(TRUE);
827 case CRM_Report_FORM
::OP_SELECT
:
828 // assume a select field
829 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
830 if (!empty($field['options']))
831 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
834 case CRM_Report_FORM
::OP_DATE
:
835 // build datetime fields
836 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
840 case CRM_Report_FORM
::OP_DATETIME
:
841 // build datetime fields
842 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
846 case CRM_Report_FORM
::OP_INT
:
847 case CRM_Report_FORM
::OP_FLOAT
:
848 // and a min value input box
849 $this->add('text', "{$fieldName}_min", ts('Min'));
850 // and a max value input box
851 $this->add('text', "{$fieldName}_max", ts('Max'));
853 // default type is string
854 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
855 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
857 // we need text box for value input
858 $this->add('text', "{$fieldName}_value", NULL);
863 $this->assign('filters', $filters);
866 function addOptions() {
867 if (!empty($this->_options
)) {
868 // FIXME: For now lets build all elements as checkboxes.
869 // Once we clear with the format we can build elements based on type
872 foreach ($this->_options
as $fieldName => $field) {
873 if ($field['type'] == 'select') {
874 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
876 else if ($field['type'] == 'checkbox') {
877 $options[$field['title']] = $fieldName;
878 $this->addCheckBox($fieldName, NULL,
880 NULL, NULL, NULL, $this->_fourColumnAttribute
885 $this->assign('otherOptions', $this->_options
);
888 function addChartOptions() {
889 if (!empty($this->_charts
)) {
890 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
891 $this->assign('charts', $this->_charts
);
892 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
896 function addGroupBys() {
897 $options = $freqElements = array();
899 foreach ($this->_columns
as $tableName => $table) {
900 if (array_key_exists('group_bys', $table)) {
901 foreach ($table['group_bys'] as $fieldName => $field) {
902 if (!empty($field)) {
903 $options[$field['title']] = $fieldName;
904 if (CRM_Utils_Array
::value('frequency', $field)) {
905 $freqElements[$field['title']] = $fieldName;
911 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
912 NULL, NULL, NULL, $this->_fourColumnAttribute
914 $this->assign('groupByElements', $options);
916 foreach ($freqElements as $name) {
917 $this->addElement('select', "group_bys_freq[$name]",
918 ts('Frequency'), $this->_groupByDateFreq
923 function addOrderBys() {
925 foreach ($this->_columns
as $tableName => $table) {
927 // Report developer may define any column to order by; include these as order-by options
928 if (array_key_exists('order_bys', $table)) {
929 foreach ($table['order_bys'] as $fieldName => $field) {
930 if (!empty($field)) {
931 $options[$fieldName] = $field['title'];
936 /* Add searchable custom fields as order-by options, if so requested
937 * (These are already indexed, so allowing to order on them is cheap.)
941 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
942 foreach ($table['fields'] as $fieldName => $field) {
943 if (!CRM_Utils_Array
::value('no_display', $field)) {
944 $options[$fieldName] = $field['title'];
952 $this->assign('orderByOptions', $options);
954 if (!empty($options)) {
956 '-' => ' - none - ') +
$options;
957 for ($i = 1; $i <= 5; $i++
) {
958 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
959 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
960 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
965 function buildInstanceAndButtons() {
966 CRM_Report_Form_Instance
::buildForm($this);
968 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
970 $this->addElement('submit', $this->_instanceButtonName
, $label);
971 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
972 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
975 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
977 if ($this->_instanceForm
) {
978 $this->assign('instanceForm', TRUE);
981 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
982 $this->addElement('submit', $this->_printButtonName
, $label);
984 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
985 $this->addElement('submit', $this->_pdfButtonName
, $label);
987 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
989 if ($this->_csvSupported
) {
990 $this->addElement('submit', $this->_csvButtonName
, $label);
993 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
994 $this->addElement('select', 'groups', ts('Group'),
995 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
997 $this->assign('group', TRUE);
1000 $label = ts('Add these Contacts to Group');
1001 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1003 $this->addChartOptions();
1004 $this->addButtons(array(
1007 'name' => ts('Preview Report'),
1008 'isDefault' => TRUE,
1014 function buildQuickForm() {
1015 $this->addColumns();
1017 $this->addFilters();
1019 $this->addOptions();
1021 $this->addGroupBys();
1023 $this->addOrderBys();
1025 $this->buildInstanceAndButtons();
1027 //add form rule for report
1028 if (is_callable(array(
1029 $this, 'formRule'))) {
1030 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1034 // a formrule function to ensure that fields selected in group_by
1035 // (if any) should only be the ones present in display/select fields criteria;
1036 // note: works if and only if any custom field selected in group_by.
1037 function customDataFormRule($fields, $ignoreFields = array( )) {
1039 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1040 foreach ($this->_columns
as $tableName => $table) {
1041 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1042 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1043 if (array_key_exists($fieldName, $fields['group_bys']) &&
1044 !array_key_exists($fieldName, $fields['fields'])
1046 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1048 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1049 foreach ($fields['fields'] as $fld => $val) {
1050 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1051 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1062 // Note: $fieldName param allows inheriting class to build operationPairs
1063 // specific to a field.
1064 function getOperationPair($type = "string", $fieldName = NULL) {
1065 // FIXME: At some point we should move these key-val pairs
1066 // to option_group and option_value table.
1068 case CRM_Report_FORM
::OP_INT
:
1069 case CRM_Report_FORM
::OP_FLOAT
:
1071 'lte' => ts('Is less than or equal to'),
1072 'gte' => ts('Is greater than or equal to'),
1073 'bw' => ts('Is between'),
1074 'eq' => ts('Is equal to'),
1075 'lt' => ts('Is less than'),
1076 'gt' => ts('Is greater than'),
1077 'neq' => ts('Is not equal to'),
1078 'nbw' => ts('Is not between'),
1079 'nll' => ts('Is empty (Null)'),
1080 'nnll' => ts('Is not empty (Null)'),
1084 case CRM_Report_FORM
::OP_SELECT
:
1086 'eq' => ts('Is equal to'),
1089 case CRM_Report_FORM
::OP_MONTH
:
1090 case CRM_Report_FORM
::OP_MULTISELECT
:
1092 'in' => ts('Is one of'),
1093 'notin' => ts('Is not one of'),
1097 case CRM_Report_FORM
::OP_DATE
:
1099 'nll' => ts('Is empty (Null)'),
1100 'nnll' => ts('Is not empty (Null)'),
1104 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1105 // use this operator for the values, concatenated with separator. For e.g if
1106 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1108 'mhas' => ts('Is one of'),
1114 'has' => ts('Contains'),
1115 'sw' => ts('Starts with'),
1116 'ew' => ts('Ends with'),
1117 'nhas' => ts('Does not contain'),
1118 'eq' => ts('Is equal to'),
1119 'neq' => ts('Is not equal to'),
1120 'nll' => ts('Is empty (Null)'),
1121 'nnll' => ts('Is not empty (Null)'),
1126 function buildTagFilter() {
1127 $contactTags = CRM_Core_BAO_Tag
::getTags();
1128 if (!empty($contactTags)) {
1129 $this->_columns
['civicrm_tag'] = array(
1130 'dao' => 'CRM_Core_DAO_Tag',
1136 'title' => ts('Tag'),
1138 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1139 'options' => $contactTags,
1147 * Adds group filters to _columns (called from _Constuct
1149 function buildGroupFilter() {
1150 $this->_columns
['civicrm_group']['filters'] = array(
1153 'name' => 'group_id',
1154 'title' => ts('Group'),
1155 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1157 'options' => CRM_Core_PseudoConstant
::group(),
1160 if (empty($this->_columns
['civicrm_group']['dao'])) {
1161 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1163 if (empty($this->_columns
['civicrm_group']['alias'])) {
1164 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1168 function getSQLOperator($operator = "like") {
1169 switch ($operator) {
1202 return 'IS NOT NULL';
1210 function whereClause(&$field, $op,
1214 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1220 if (($min !== NULL && strlen($min) > 0) ||
1221 ($max !== NULL && strlen($max) > 0)
1223 $min = CRM_Utils_Type
::escape($min, $type);
1224 $max = CRM_Utils_Type
::escape($max, $type);
1228 $clauses[] = "( {$field['dbAlias']} >= $min )";
1231 $clauses[] = "( {$field['dbAlias']} < $min )";
1236 $clauses[] = "( {$field['dbAlias']} <= $max )";
1239 $clauses[] = "( {$field['dbAlias']} > $max )";
1243 if (!empty($clauses)) {
1245 $clause = implode(' AND ', $clauses);
1248 $clause = implode(' OR ', $clauses);
1256 if ($value !== NULL && strlen($value) > 0) {
1257 $value = CRM_Utils_Type
::escape($value, $type);
1258 if (strpos($value, '%') === FALSE) {
1259 $value = "'%{$value}%'";
1262 $value = "'{$value}'";
1264 $sqlOP = $this->getSQLOperator($op);
1265 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1271 if ($value !== NULL && is_array($value) && count($value) > 0) {
1272 $sqlOP = $this->getSQLOperator($op);
1273 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1274 //cycle through selections and esacape values
1275 foreach ($value as $key => $selection) {
1276 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1278 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1281 // for numerical values
1282 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1284 if ($op == 'notin') {
1285 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1288 $clause = "( " . $clause . " )";
1294 // mhas == multiple has
1295 if ($value !== NULL && count($value) > 0) {
1296 $sqlOP = $this->getSQLOperator($op);
1297 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1303 if ($value !== NULL && strlen($value) > 0) {
1304 $value = CRM_Utils_Type
::escape($value, $type);
1305 if (strpos($value, '%') === FALSE) {
1307 $value = "'{$value}%'";
1310 $value = "'%{$value}'";
1314 $value = "'{$value}'";
1316 $sqlOP = $this->getSQLOperator($op);
1317 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1323 $sqlOP = $this->getSQLOperator($op);
1324 $clause = "( {$field['dbAlias']} $sqlOP )";
1328 if ($value !== NULL && strlen($value) > 0) {
1329 if (isset($field['clause'])) {
1330 // FIXME: we not doing escape here. Better solution is to use two
1331 // different types - data-type and filter-type
1332 $clause = $field['clause'];
1335 $value = CRM_Utils_Type
::escape($value, $type);
1336 $sqlOP = $this->getSQLOperator($op);
1337 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1338 $value = "'{$value}'";
1340 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1346 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1347 $clause = $this->whereGroupClause($field, $value, $op);
1349 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1350 // not using left join in query because if any contact
1351 // belongs to more than one tag, results duplicate
1353 $clause = $this->whereTagClause($field, $value, $op);
1359 function dateClause($fieldName,
1360 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1363 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1364 $sqlOP = $this->getSQLOperator($relative);
1365 return "( {$fieldName} {$sqlOP} )";
1368 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1371 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1372 $clauses[] = "( {$fieldName} >= $from )";
1376 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1377 $clauses[] = "( {$fieldName} <= {$to} )";
1380 if (!empty($clauses)) {
1381 return implode(' AND ', $clauses);
1387 * @todo - could not find any instances where this is called
1388 * @param unknown_type $relative
1389 * @param String $from
1390 * @param String_type $to
1391 * @return string|NULL
1393 function dateDisplay($relative, $from, $to) {
1394 list($from, $to) = $this->getFromTo($relative, $from, $to);
1397 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1400 $clauses[] = 'Past';
1404 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1407 $clauses[] = 'Today';
1410 if (!empty($clauses)) {
1411 return implode(' - ', $clauses);
1417 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1418 if (empty($totime)) {
1421 //FIX ME not working for relative
1423 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1424 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1425 $from = substr($dateRange['from'], 0, 8);
1426 //Take only Date Part, Sometime Time part is also present in 'to'
1427 $to = substr($dateRange['to'], 0, 8);
1429 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1430 $to = CRM_Utils_Date
::processDate($to, $totime);
1431 return array($from, $to);
1434 function alterDisplay(&$rows) {
1435 // custom code to alter rows
1438 function alterCustomDataDisplay(&$rows) {
1439 // custom code to alter rows having custom values
1440 if (empty($this->_customGroupExtends
)) {
1444 $customFieldIds = array();
1445 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1446 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1447 $customFieldIds[$fieldAlias] = $fieldId;
1450 if (empty($customFieldIds)) {
1454 $customFields = $fieldValueMap = array();
1455 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1457 // skip for type date and ContactReference since date format is already handled
1459 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1460 FROM civicrm_custom_field cf
1461 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1462 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1463 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1464 cg.is_active = 1 AND
1465 cf.is_active = 1 AND
1466 cf.is_searchable = 1 AND
1467 cf.data_type NOT IN ('ContactReference', 'Date') AND
1468 cf.id IN (" . implode(",", $customFieldIds) . ")";
1470 $dao = CRM_Core_DAO
::executeQuery($query);
1471 while ($dao->fetch()) {
1472 foreach ($customFieldCols as $key) {
1473 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1475 if ($dao->option_group_id
) {
1476 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1481 $entryFound = FALSE;
1482 foreach ($rows as $rowNum => $row) {
1483 foreach ($row as $tableCol => $val) {
1484 if (array_key_exists($tableCol, $customFields)) {
1485 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1490 // skip looking further in rows, if first row itself doesn't
1491 // have the column we need
1498 function formatCustomValues($value, $customField, $fieldValueMap) {
1499 if (CRM_Utils_System
::isNull($value)) {
1503 $htmlType = $customField['html_type'];
1505 switch ($customField['data_type']) {
1507 if ($value == '1') {
1508 $retValue = ts('Yes');
1511 $retValue = ts('No');
1516 $retValue = CRM_Utils_System
::formatWikiURL($value);
1528 if ($htmlType == 'Text') {
1529 $retValue = (float)$value;
1533 if ($htmlType == 'Text') {
1543 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1548 if (in_array($htmlType, array(
1549 'Text', 'TextArea'))) {
1553 case 'StateProvince':
1556 switch ($htmlType) {
1557 case 'Multi-Select Country':
1558 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1559 $customData = array();
1560 foreach ($value as $val) {
1562 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1565 $retValue = implode(', ', $customData);
1568 case 'Select Country':
1569 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1572 case 'Select State/Province':
1573 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1576 case 'Multi-Select State/Province':
1577 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1578 $customData = array();
1579 foreach ($value as $val) {
1581 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1584 $retValue = implode(', ', $customData);
1589 case 'Autocomplete-Select':
1590 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1594 case 'AdvMulti-Select':
1595 case 'Multi-Select':
1596 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1597 $customData = array();
1598 foreach ($value as $val) {
1600 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1603 $retValue = implode(', ', $customData);
1618 function removeDuplicates(&$rows) {
1619 if (empty($this->_noRepeats
)) {
1622 $checkList = array();
1624 foreach ($rows as $key => $list) {
1625 foreach ($list as $colName => $colVal) {
1626 if (array_key_exists($colName, $checkList) &&
1627 $checkList[$colName] == $colVal) {
1628 $rows[$key][$colName] = "";
1630 if (in_array($colName, $this->_noRepeats
)) {
1631 $checkList[$colName] = $colVal;
1637 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1638 foreach ($row as $colName => $colVal) {
1639 if (in_array($colName, $fields)) {
1640 $row[$colName] = $row[$colName];
1642 elseif (isset($this->_columnHeaders
[$colName])) {
1644 $row[$colName] = "Subtotal";
1648 unset($row[$colName]);
1654 function grandTotal(&$rows) {
1655 if (!$this->_rollup ||
($this->_rollup
== '') ||
1656 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1660 $lastRow = array_pop($rows);
1662 foreach ($this->_columnHeaders
as $fld => $val) {
1663 if (!in_array($fld, $this->_statFields
)) {
1664 if (!$this->_grandFlag
) {
1665 $lastRow[$fld] = "Grand Total";
1666 $this->_grandFlag
= TRUE;
1669 $lastRow[$fld] = "";
1674 $this->assign('grandStat', $lastRow);
1678 function formatDisplay(&$rows, $pager = TRUE) {
1679 // set pager based on if any limit was applied in the query.
1684 // allow building charts if any
1685 if (!empty($this->_params
['charts']) && !empty($rows)) {
1686 $this->buildChart($rows);
1687 $this->assign('chartEnabled', TRUE);
1688 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1689 $this->assign('chartId', $this->_chartId
);
1692 // unset columns not to be displayed.
1693 foreach ($this->_columnHeaders
as $key => $value) {
1694 if (CRM_Utils_Array
::value('no_display', $value)) {
1695 unset($this->_columnHeaders
[$key]);
1699 // unset columns not to be displayed.
1700 if (!empty($rows)) {
1701 foreach ($this->_noDisplay
as $noDisplayField) {
1702 foreach ($rows as $rowNum => $row) {
1703 unset($this->_columnHeaders
[$noDisplayField]);
1708 // build array of section totals
1709 $this->sectionTotals();
1711 // process grand-total row
1712 $this->grandTotal($rows);
1714 // use this method for formatting rows for display purpose.
1715 $this->alterDisplay($rows);
1716 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1718 // use this method for formatting custom rows for display purpose.
1719 $this->alterCustomDataDisplay($rows);
1722 function buildChart(&$rows) {
1723 // override this method for building charts.
1726 // select() method below has been added recently (v3.3), and many of the report templates might
1727 // still be having their own select() method. We should fix them as and when encountered and move
1728 // towards generalizing the select() method below.
1730 $select = $this->_selectAliases
= array();
1732 foreach ($this->_columns
as $tableName => $table) {
1733 if (array_key_exists('fields', $table)) {
1734 foreach ($table['fields'] as $fieldName => $field) {
1735 if ($tableName == 'civicrm_address') {
1736 $this->_addressField
= TRUE;
1738 if ($tableName == 'civicrm_email') {
1739 $this->_emailField
= TRUE;
1741 if ($tableName == 'civicrm_phone') {
1742 $this->_phoneField
= TRUE;
1745 if (CRM_Utils_Array
::value('required', $field) ||
1746 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1749 // 1. In many cases we want select clause to be built in slightly different way
1750 // for a particular field of a particular type.
1751 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1753 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1754 if ($selectClause) {
1755 $select[] = $selectClause;
1759 // include statistics columns only if set
1760 if (CRM_Utils_Array
::value('statistics', $field)) {
1761 foreach ($field['statistics'] as $stat => $label) {
1762 $alias = "{$tableName}_{$fieldName}_{$stat}";
1763 switch (strtolower($stat)) {
1766 $select[] = "$stat({$field['dbAlias']}) as $alias";
1767 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1768 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1769 $this->_statFields
[$label] = $alias;
1770 $this->_selectAliases
[] = $alias;
1774 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1775 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1776 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1777 $this->_statFields
[$label] = $alias;
1778 $this->_selectAliases
[] = $alias;
1781 case 'count_distinct':
1782 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1783 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1784 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1785 $this->_statFields
[$label] = $alias;
1786 $this->_selectAliases
[] = $alias;
1790 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1791 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1792 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1793 $this->_statFields
[$label] = $alias;
1794 $this->_selectAliases
[] = $alias;
1800 $alias = "{$tableName}_{$fieldName}";
1801 $select[] = "{$field['dbAlias']} as $alias";
1802 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1803 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1804 $this->_selectAliases
[] = $alias;
1810 // select for group bys
1811 if (array_key_exists('group_bys', $table)) {
1812 foreach ($table['group_bys'] as $fieldName => $field) {
1814 if ($tableName == 'civicrm_address') {
1815 $this->_addressField
= TRUE;
1817 if ($tableName == 'civicrm_email') {
1818 $this->_emailField
= TRUE;
1820 if ($tableName == 'civicrm_phone') {
1821 $this->_phoneField
= TRUE;
1823 // 1. In many cases we want select clause to be built in slightly different way
1824 // for a particular field of a particular type.
1825 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1827 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1828 if ($selectClause) {
1829 $select[] = $selectClause;
1833 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1834 && !empty($this->_params
['group_bys_freq'])) {
1835 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1837 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1838 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1839 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1840 $field['title'] = 'Week';
1844 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1845 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1846 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1847 $field['title'] = 'Year';
1851 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1852 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1853 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1854 $field['title'] = 'Month';
1858 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1859 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1860 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1861 $field['title'] = 'Quarter';
1864 // for graphs and charts -
1865 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1866 $this->_interval
= $field['title'];
1867 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1868 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1869 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1871 // just to make sure these values are transfered to rows.
1872 // since we 'll need them for calculation purpose,
1873 // e.g making subtotals look nicer or graphs
1874 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1875 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1882 $this->_selectClauses
= $select;
1883 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1886 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1891 $this->storeWhereHavingClauseArray();
1893 if (empty($this->_whereClauses
)) {
1894 $this->_where
= "WHERE ( 1 ) ";
1895 $this->_having
= "";
1898 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1901 if ($this->_aclWhere
) {
1902 $this->_where
.= " AND {$this->_aclWhere} ";
1905 if (!empty($this->_havingClauses
)) {
1906 // use this clause to construct group by clause.
1907 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1912 * Store Where clauses into an array - breaking out this step makes
1913 * over-riding more flexible as the clauses can be used in constructing a
1914 * temp table that may not be part of the final where clause or added
1915 * in other functions
1917 function storeWhereHavingClauseArray(){
1918 foreach ($this->_columns
as $tableName => $table) {
1919 if (array_key_exists('filters', $table)) {
1920 foreach ($table['filters'] as $fieldName => $field) {
1921 // respect pseudofield to filter spec so fields can be marked as
1922 // not to be handled here
1923 if(!empty($field['pseudofield'])){
1927 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1928 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1929 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1930 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1931 if (is_array($value) && !empty($value)) {
1932 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1936 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1937 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1938 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1939 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1940 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1941 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1945 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1947 $clause = $this->whereClause($field,
1949 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1950 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1951 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1956 if (!empty($clause)) {
1957 if (CRM_Utils_Array
::value('having', $field)) {
1958 $this->_havingClauses
[] = $clause;
1961 $this->_whereClauses
[] = $clause;
1969 function processReportMode() {
1970 $buttonName = $this->controller
->getButtonName();
1972 $output = CRM_Utils_Request
::retrieve(
1975 CRM_Core_DAO
::$_nullObject
1979 CRM_Utils_Request
::retrieve(
1982 CRM_Core_DAO
::$_nullObject
1985 $this->_absoluteUrl
= FALSE;
1987 $this->assign('printOnly', FALSE);
1989 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1990 $this->assign('printOnly', TRUE);
1992 $this->assign('outputMode', 'print');
1993 $this->_outputMode
= 'print';
1994 if ($this->_sendmail
) {
1995 $this->_absoluteUrl
= TRUE;
1998 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1999 $this->assign('printOnly', TRUE);
2001 $this->assign('outputMode', 'pdf');
2002 $this->_outputMode
= 'pdf';
2003 $this->_absoluteUrl
= TRUE;
2005 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2006 $this->assign('printOnly', TRUE);
2008 $this->assign('outputMode', 'csv');
2009 $this->_outputMode
= 'csv';
2010 $this->_absoluteUrl
= TRUE;
2012 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2013 $this->assign('outputMode', 'group');
2014 $this->_outputMode
= 'group';
2016 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2017 $this->assign('outputMode', 'create_report');
2018 $this->_outputMode
= 'create_report';
2021 $this->assign('outputMode', 'html');
2022 $this->_outputMode
= 'html';
2025 // Get today's date to include in printed reports
2027 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2028 $this->assign('reportDate', $reportDate);
2032 function beginPostProcess() {
2033 $this->_params
= $this->controller
->exportValues($this->_name
);
2035 if (empty($this->_params
) &&
2038 $this->_params
= $this->_formValues
;
2041 // hack to fix params when submitted from dashboard, CRM-8532
2042 // fields array is missing because form building etc is skipped
2043 // in dashboard mode for report
2044 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2045 $this->_params
= $this->_formValues
;
2048 $this->_formValues
= $this->_params
;
2049 if (CRM_Core_Permission
::check('administer Reports') &&
2050 isset($this->_id
) &&
2051 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2052 $this->_chartButtonName
== $this->controller
->getButtonName()
2055 $this->assign('updateReportButton', TRUE);
2057 $this->processReportMode();
2060 function buildQuery($applyLimit = TRUE) {
2063 $this->customDataFrom();
2068 // order_by columns not selected for display need to be included in SELECT
2069 $unselectedSectionColumns = $this->unselectedSectionColumns();
2070 foreach ($unselectedSectionColumns as $alias => $section) {
2071 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2074 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2077 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2079 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2083 function groupBy() {
2084 $groupBys = array();
2085 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2086 is_array($this->_params
['group_bys']) &&
2087 !empty($this->_params
['group_bys'])
2089 foreach ($this->_columns
as $tableName => $table) {
2090 if (array_key_exists('group_bys', $table)) {
2091 foreach ($table['group_bys'] as $fieldName => $field) {
2092 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2093 $groupBys[] = $field['dbAlias'];
2100 if (!empty($groupBys)) {
2101 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2105 function orderBy() {
2106 $this->_orderBy
= "";
2107 $this->_sections
= array();
2108 $this->storeOrderByArray();
2109 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2110 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2112 $this->assign('sections', $this->_sections
);
2116 * In some cases other functions want to know which fields are selected for ordering by
2117 * Separating this into a separate function allows it to be called separately from constructing
2118 * the order by clause
2120 function storeOrderByArray() {
2121 $orderBys = array();
2123 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2124 is_array($this->_params
['order_bys']) &&
2125 !empty($this->_params
['order_bys'])
2128 // Proces order_bys in user-specified order
2129 foreach ($this->_params
['order_bys'] as $orderBy) {
2130 $orderByField = array();
2131 foreach ($this->_columns
as $tableName => $table) {
2132 if (array_key_exists('order_bys', $table)) {
2133 // For DAO columns defined in $this->_columns
2134 $fields = $table['order_bys'];
2136 elseif (array_key_exists('extends', $table)) {
2137 // For custom fields referenced in $this->_customGroupExtends
2138 $fields = $table['fields'];
2140 if (!empty($fields) && is_array($fields)) {
2141 foreach ($fields as $fieldName => $field) {
2142 if ($fieldName == $orderBy['column']) {
2143 $orderByField = array_merge($field, $orderBy);
2144 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2151 if (!empty($orderByField)) {
2152 $this->_orderByFields
[] = $orderByField;
2153 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2155 // Record any section headers for assignment to the template
2156 if (CRM_Utils_Array
::value('section', $orderBy)) {
2157 $this->_sections
[$orderByField['tplField']] = $orderByField;
2163 $this->_orderByArray
= $orderBys;
2165 $this->assign('sections', $this->_sections
);
2168 function unselectedSectionColumns() {
2169 $selectColumns = array();
2170 foreach ($this->_columns
as $tableName => $table) {
2171 if (array_key_exists('fields', $table)) {
2172 foreach ($table['fields'] as $fieldName => $field) {
2173 if (CRM_Utils_Array
::value('required', $field) ||
2174 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2177 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2183 if (is_array($this->_sections
)) {
2184 return array_diff_key($this->_sections
, $selectColumns);
2191 function buildRows($sql, &$rows) {
2192 $dao = CRM_Core_DAO
::executeQuery($sql);
2193 if (!is_array($rows)) {
2197 // use this method to modify $this->_columnHeaders
2198 $this->modifyColumnHeaders();
2200 $unselectedSectionColumns = $this->unselectedSectionColumns();
2202 while ($dao->fetch()) {
2204 foreach ($this->_columnHeaders
as $key => $value) {
2205 if (property_exists($dao, $key)) {
2206 $row[$key] = $dao->$key;
2210 // section headers not selected for display need to be added to row
2211 foreach ($unselectedSectionColumns as $key => $values) {
2212 if (property_exists($dao, $key)) {
2213 $row[$key] = $dao->$key;
2222 * When "order by" fields are marked as sections, this assigns to the template
2223 * an array of total counts for each section. This data is used by the Smarty
2224 * plugin {sectionTotal}
2226 function sectionTotals() {
2228 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2229 if (empty($this->_selectAliases
)) {
2233 if (!empty($this->_sections
)) {
2234 // build the query with no LIMIT clause
2235 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2236 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2238 // pull section aliases out of $this->_sections
2239 $sectionAliases = array_keys($this->_sections
);
2242 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2243 $ifnulls[] = "ifnull($alias, '') as $alias";
2246 /* Group (un-limited) report by all aliases and get counts. This might
2247 * be done more efficiently when the contents of $sql are known, ie. by
2248 * overriding this method in the report class.
2252 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2254 // initialize array of total counts
2256 $dao = CRM_Core_DAO
::executeQuery($query);
2257 while ($dao->fetch()) {
2259 // let $this->_alterDisplay translate any integer ids to human-readable values.
2260 $rows[0] = $dao->toArray();
2261 $this->alterDisplay($rows);
2264 // add totals for all permutations of section values
2267 $aliasCount = count($sectionAliases);
2268 foreach ($sectionAliases as $alias) {
2269 $values[] = $row[$alias];
2270 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2271 if ($i == $aliasCount) {
2272 // the last alias is the lowest-level section header; use count as-is
2273 $totals[$key] = $dao->ct
;
2276 // other aliases are higher level; roll count into their total
2277 $totals[$key] +
= $dao->ct
;
2281 $this->assign('sectionTotals', $totals);
2285 function modifyColumnHeaders() {
2286 // use this method to modify $this->_columnHeaders
2289 function doTemplateAssignment(&$rows) {
2290 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2291 $this->assign_by_ref('rows', $rows);
2292 $this->assign('statistics', $this->statistics($rows));
2295 // override this method to build your own statistics
2296 function statistics(&$rows) {
2297 $statistics = array();
2299 $count = count($rows);
2301 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2305 $this->countStat($statistics, $count);
2307 $this->groupByStat($statistics);
2309 $this->filterStat($statistics);
2314 function countStat(&$statistics, $count) {
2315 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2319 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2320 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2321 'value' => $this->_rowsFound
,
2326 function groupByStat(&$statistics) {
2327 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2328 is_array($this->_params
['group_bys']) &&
2329 !empty($this->_params
['group_bys'])
2331 foreach ($this->_columns
as $tableName => $table) {
2332 if (array_key_exists('group_bys', $table)) {
2333 foreach ($table['group_bys'] as $fieldName => $field) {
2334 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2335 $combinations[] = $field['title'];
2340 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2341 'value' => implode(' & ', $combinations),
2346 function filterStat(&$statistics) {
2347 foreach ($this->_columns
as $tableName => $table) {
2348 if (array_key_exists('filters', $table)) {
2349 foreach ($table['filters'] as $fieldName => $field) {
2350 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2353 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2354 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2355 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2356 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2357 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2359 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2360 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2362 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2363 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2366 $statistics['filters'][] = array(
2367 'title' => $field['title'],
2368 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2371 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2372 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2374 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2375 $statistics['filters'][] = array(
2376 'title' => $field['title'],
2377 'value' => $pair[$rel],
2382 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2385 $pair = $this->getOperationPair(
2386 CRM_Utils_Array
::value('operatorType', $field),
2389 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2390 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2391 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2392 if (in_array($op, array(
2393 'bw', 'nbw')) && ($min ||
$max)) {
2394 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2396 elseif ($op == 'nll' ||
$op == 'nnll') {
2397 $value = $pair[$op];
2399 elseif (is_array($val) && (!empty($val))) {
2400 $options = CRM_Utils_Array
::value('options', $field, array());
2401 foreach ($val as $key => $valIds) {
2402 if (isset($options[$valIds])) {
2403 $val[$key] = $options[$valIds];
2406 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2407 $val = implode(', ', $val);
2408 $value = "{$pair[$op]} " . $val;
2410 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2411 is_array($field['options']) && !empty($field['options'])
2413 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2416 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2420 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2430 function endPostProcess(&$rows = NULL) {
2431 if ( $this->_storeResultSet
) {
2432 $this->_resultSet
= $rows;
2435 if ($this->_outputMode
== 'print' ||
2436 $this->_outputMode
== 'pdf' ||
2440 $content = $this->compileContent();
2441 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2445 if ($this->_sendmail
) {
2446 $config = CRM_Core_Config
::singleton();
2447 $attachments = array();
2449 if ($this->_outputMode
== 'csv') {
2450 $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'];
2452 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2453 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2454 file_put_contents($csvFullFilename, $csvContent);
2455 $attachments[] = array(
2456 'fullPath' => $csvFullFilename,
2457 'mime_type' => 'text/csv',
2458 'cleanName' => 'CiviReport.csv',
2461 if ($this->_outputMode
== 'pdf') {
2462 // generate PDF content
2463 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2464 file_put_contents($pdfFullFilename,
2465 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2466 TRUE, array('orientation' => 'landscape')
2469 // generate Email Content
2470 $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'];
2472 $attachments[] = array(
2473 'fullPath' => $pdfFullFilename,
2474 'mime_type' => 'application/pdf',
2475 'cleanName' => 'CiviReport.pdf',
2479 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2480 $this->_outputMode
, $attachments
2482 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2485 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2488 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2490 elseif ($this->_outputMode
== 'print') {
2494 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2495 $config = CRM_Core_Config
::singleton();
2496 //get chart image name
2497 $chartImg = $this->_chartId
. '.png';
2498 //get image url path
2499 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2500 $uploadUrl .= $chartImg;
2501 //get image doc path to overwrite
2502 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2504 $chart = imagecreatefrompng($uploadUrl);
2505 //convert it into formattd png
2506 header('Content-type: image/png');
2507 //overwrite with same image
2508 imagepng($chart, $uploadImg);
2510 imagedestroy($chart);
2512 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2514 CRM_Utils_System
::civiExit();
2516 elseif ($this->_outputMode
== 'csv') {
2517 CRM_Report_Utils_Report
::export2csv($this, $rows);
2519 elseif ($this->_outputMode
== 'group') {
2520 $group = $this->_params
['groups'];
2521 $this->add2group($group);
2523 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2524 CRM_Report_Form_Instance
::postProcess($this);
2526 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2527 $this->_outputMode
== 'create_report' ) {
2528 $this->_createNew
= TRUE;
2529 CRM_Report_Form_Instance
::postProcess($this);
2533 function storeResultSet() {
2534 $this->_storeResultSet
= TRUE;
2537 function getResultSet() {
2538 return $this->_resultSet
;
2542 * Get Template file name - use default form template if a specific one has not been set up for this report
2545 function getTemplateFileName(){
2546 $defaultTpl = parent
::getTemplateFileName();
2547 $template = CRM_Core_Smarty
::singleton();
2548 if (!$template->template_exists($defaultTpl)) {
2549 $defaultTpl = 'CRM/Report/Form.tpl';
2555 * Compile the report content
2557 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2559 function compileContent(){
2560 $templateFile = $this->getHookedTemplateFileName();
2561 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2565 function postProcess() {
2566 // get ready with post process params
2567 $this->beginPostProcess();
2570 $sql = $this->buildQuery();
2572 // build array of result based on column headers. This method also allows
2573 // modifying column headers before using it to build result set i.e $rows.
2575 $this->buildRows($sql, $rows);
2577 // format result set.
2578 $this->formatDisplay($rows);
2580 // assign variables to templates
2581 $this->doTemplateAssignment($rows);
2583 // do print / pdf / instance stuff if needed
2584 $this->endPostProcess($rows);
2587 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2588 // lets do the pager if in html mode
2589 $this->_limit
= NULL;
2590 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2591 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2593 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2595 if (!$pageId && !empty($_POST)) {
2596 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2597 $pageId = max((int)@$_POST['crmPID_B'], 1);
2599 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2600 $pageId = max((int)@$_POST['crmPID'], 1);
2602 unset($_POST['crmPID_B'], $_POST['crmPID']);
2605 $pageId = $pageId ?
$pageId : 1;
2606 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2607 $offset = ($pageId - 1) * $rowCount;
2609 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2610 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2612 $this->_limit
= " LIMIT $offset, $rowCount";
2613 return array($offset, $rowCount);
2617 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2618 if ($this->_limit
&& ($this->_limit
!= '')) {
2619 $sql = "SELECT FOUND_ROWS();";
2620 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2622 'total' => $this->_rowsFound
,
2623 'rowCount' => $rowCount,
2624 'status' => ts('Records') . ' %%StatusMessage%%',
2625 'buttonBottom' => 'PagerBottomButton',
2626 'buttonTop' => 'PagerTopButton',
2627 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2630 $pager = new CRM_Utils_Pager($params);
2631 $this->assign_by_ref('pager', $pager);
2635 function whereGroupClause($field, $value, $op) {
2637 $smartGroupQuery = "";
2639 $group = new CRM_Contact_DAO_Group();
2640 $group->is_active
= 1;
2642 $smartGroups = array();
2643 while ($group->fetch()) {
2644 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2645 $smartGroups[] = $group->id
;
2649 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2651 $smartGroupQuery = '';
2652 if (!empty($smartGroups)) {
2653 $smartGroups = implode(',', $smartGroups);
2654 $smartGroupQuery = " UNION DISTINCT
2655 SELECT DISTINCT smartgroup_contact.contact_id
2656 FROM civicrm_group_contact_cache smartgroup_contact
2657 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2660 $sqlOp = $this->getSQLOperator($op);
2661 if (!is_array($value)) {
2662 $value = array($value);
2664 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2666 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2667 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2668 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2669 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2670 {$smartGroupQuery} ) ";
2673 function whereTagClause($field, $value, $op) {
2674 // not using left join in query because if any contact
2675 // belongs to more than one tag, results duplicate
2677 $sqlOp = $this->getSQLOperator($op);
2678 if (!is_array($value)) {
2679 $value = array($value);
2681 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2683 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2684 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2685 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2686 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2689 function buildACLClause($tableAlias = 'contact_a') {
2690 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2693 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2694 if (empty($this->_customGroupExtends
)) {
2697 if (!is_array($this->_customGroupExtends
)) {
2698 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2700 $customGroupWhere = '';
2701 if (!empty($permCustomGroupIds)) {
2702 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2705 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2706 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2707 FROM civicrm_custom_group cg
2708 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2709 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2711 cg.is_active = 1 AND
2712 cf.is_active = 1 AND
2713 cf.is_searchable = 1
2714 ORDER BY cg.weight, cf.weight";
2715 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2718 while ($customDAO->fetch()) {
2719 if ($customDAO->table_name
!= $curTable) {
2720 $curTable = $customDAO->table_name
;
2721 $curFields = $curFilters = array();
2724 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2725 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2726 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2727 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2730 'fields', 'filters', 'group_bys') as $colKey) {
2731 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2732 $this->_columns
[$curTable][$colKey] = array();
2736 $fieldName = 'custom_' . $customDAO->cf_id
;
2739 // this makes aliasing work in favor
2740 $curFields[$fieldName] = array(
2741 'name' => $customDAO->column_name
,
2742 'title' => $customDAO->label
,
2743 'dataType' => $customDAO->data_type
,
2744 'htmlType' => $customDAO->html_type
,
2747 if ($this->_customGroupFilters
) {
2748 // this makes aliasing work in favor
2749 $curFilters[$fieldName] = array(
2750 'name' => $customDAO->column_name
,
2751 'title' => $customDAO->label
,
2752 'dataType' => $customDAO->data_type
,
2753 'htmlType' => $customDAO->html_type
,
2757 switch ($customDAO->data_type
) {
2760 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2761 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2762 // CRM-6946, show time part for datetime date fields
2763 if ($customDAO->time_format
) {
2764 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2769 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2770 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2774 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2778 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2779 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2783 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2784 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2788 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2789 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2793 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2795 if (!empty($customDAO->option_group_id
)) {
2796 if (in_array($customDAO->html_type
, array(
2797 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2798 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2801 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2803 if ($this->_customGroupFilters
) {
2804 $curFilters[$fieldName]['options'] = array();
2805 $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')));
2806 while ($ogDAO->fetch()) {
2807 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2813 case 'StateProvince':
2814 if (in_array($customDAO->html_type
, array(
2815 'Multi-Select State/Province'))) {
2816 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2819 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2821 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2825 if (in_array($customDAO->html_type
, array(
2826 'Multi-Select Country'))) {
2827 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2830 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2832 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2835 case 'ContactReference':
2836 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2837 $curFilters[$fieldName]['name'] = 'display_name';
2838 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2840 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2841 $curFields[$fieldName]['name'] = 'display_name';
2842 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2846 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2847 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2850 if (!array_key_exists('type', $curFields[$fieldName])) {
2851 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2855 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2857 if ($this->_customGroupFilters
) {
2858 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2860 if ($this->_customGroupGroupBy
) {
2861 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2866 function customDataFrom() {
2867 if (empty($this->_customGroupExtends
)) {
2870 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2872 foreach ($this->_columns
as $table => $prop) {
2873 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2874 $extendsTable = $mapper[$prop['extends']];
2876 // check field is in params
2877 if (!$this->isFieldSelected($prop)) {
2881 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2883 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2884 // handle for ContactReference
2885 if (array_key_exists('fields', $prop)) {
2886 foreach ($prop['fields'] as $fieldName => $field) {
2887 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2888 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2890 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2898 function isFieldSelected($prop) {
2903 if (!empty($this->_params
['fields'])) {
2904 foreach (array_keys($prop['fields']) as $fieldAlias) {
2905 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2906 if ($customFieldId) {
2907 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2911 //might be survey response field.
2912 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2913 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2921 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2922 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2923 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2929 if (!empty($this->_params
['order_bys'])) {
2930 foreach (array_keys($prop['fields']) as $fieldAlias) {
2931 foreach ($this->_params
['order_bys'] as $orderBy) {
2932 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2939 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2940 foreach ($prop['filters'] as $fieldAlias => $val) {
2942 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2943 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2944 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2945 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2951 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2952 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2963 * Check for empty order_by configurations and remove them; also set
2964 * template to hide them.
2966 function preProcessOrderBy(&$formValues) {
2967 // Object to show/hide form elements
2968 $_showHide = new CRM_Core_ShowHideBlocks('', '');
2970 $_showHide->addShow('optionField_1');
2972 // Cycle through order_by options; skip any empty ones, and hide them as well
2975 if (!empty($formValues['order_bys'])) {
2976 foreach ($formValues['order_bys'] as $order_by) {
2977 if ($order_by['column'] && $order_by['column'] != '-') {
2978 $_showHide->addShow('optionField_' . $n);
2979 $orderBys[$n] = $order_by;
2984 for ($i = $n; $i <= 5; $i++
) {
2986 $_showHide->addHide('optionField_' . $i);
2990 // overwrite order_by options with modified values
2991 if (!empty($orderBys)) {
2992 $formValues['order_bys'] = $orderBys;
2995 $formValues['order_bys'] = array(1 => array('column' => '-'));
2998 // assign show/hide data to template
2999 $_showHide->addToTemplate();
3003 * Does table name have columns in SELECT clause?
3005 * @param string $tableName Name of table (index of $this->_columns array)
3009 function isTableSelected($tableName) {
3010 return in_array($tableName, $this->selectedTables());
3014 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3015 * (building the array if it's unset)
3017 * @return Array $this->_selectedTables
3019 function selectedTables() {
3020 if (!$this->_selectedTables
) {
3021 $orderByColumns = array();
3022 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3023 foreach ($this->_params
['order_bys'] as $orderBy) {
3024 $orderByColumns[] = $orderBy['column'];
3028 foreach ($this->_columns
as $tableName => $table) {
3029 if (array_key_exists('fields', $table)) {
3030 foreach ($table['fields'] as $fieldName => $field) {
3031 if (CRM_Utils_Array
::value('required', $field) ||
3032 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3034 $this->_selectedTables
[] = $tableName;
3039 if (array_key_exists('order_bys', $table)) {
3040 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3041 if (in_array($orderByName, $orderByColumns)) {
3042 $this->_selectedTables
[] = $tableName;
3047 if (array_key_exists('filters', $table)) {
3048 foreach ($table['filters'] as $filterName => $filter) {
3049 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3050 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3051 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3053 $this->_selectedTables
[] = $tableName;
3060 return $this->_selectedTables
;
3064 * @deprecated - use getAddressColumns which is a more accurate description
3065 * and also accepts an array of options rather than a long list
3067 * function for adding address fields to construct function in reports
3068 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3069 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3070 * @return array address fields for construct clause
3072 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3073 'country_id' => TRUE)) {
3074 $addressFields = array(
3075 'civicrm_address' =>
3077 'dao' => 'CRM_Core_DAO_Address',
3081 array('title' => ts('Address Name'),
3082 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3085 array('title' => ts('Street Address'),
3086 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3088 'supplemental_address_1' =>
3089 array('title' => ts('Supplementary Address Field 1'),
3090 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3092 'supplemental_address_2' =>
3093 array('title' => ts('Supplementary Address Field 2'),
3094 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3098 'name' => 'street_number',
3099 'title' => ts('Street Number'),
3101 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3105 'name' => 'street_name',
3106 'title' => ts('Street Name'),
3108 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3112 'name' => 'street_unit',
3113 'title' => ts('Street Unit'),
3115 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3118 array('title' => ts('City'),
3119 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3122 array('title' => ts('Postal Code'),
3123 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3125 'postal_code_suffix' =>
3126 array('title' => ts('Postal Code Suffix'),
3127 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3130 array('title' => ts('County'),
3131 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3133 'state_province_id' =>
3134 array('title' => ts('State/Province'),
3135 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3138 array('title' => ts('Country'),
3139 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3142 'grouping' => 'location-fields',
3147 $addressFields['civicrm_address']['filters'] = array(
3148 'street_number' => array('title' => ts('Street Number'),
3150 'name' => 'street_number',
3152 'street_name' => array('title' => ts('Street Name'),
3153 'name' => 'street_name',
3154 'operator' => 'like',
3156 'postal_code' => array('title' => ts('Postal Code'),
3158 'name' => 'postal_code',
3160 'city' => array('title' => ts('City'),
3161 'operator' => 'like',
3164 'county_id' => array(
3165 'name' => 'county_id',
3166 'title' => ts('County'),
3167 'type' => CRM_Utils_Type
::T_INT
,
3169 CRM_Report_Form
::OP_MULTISELECT
,
3171 CRM_Core_PseudoConstant
::county(),
3173 'state_province_id' => array(
3174 'name' => 'state_province_id',
3175 'title' => ts('State/Province'),
3176 'type' => CRM_Utils_Type
::T_INT
,
3178 CRM_Report_Form
::OP_MULTISELECT
,
3180 CRM_Core_PseudoConstant
::stateProvince(),
3182 'country_id' => array(
3183 'name' => 'country_id',
3184 'title' => ts('Country'),
3185 'type' => CRM_Utils_Type
::T_INT
,
3187 CRM_Report_Form
::OP_MULTISELECT
,
3189 CRM_Core_PseudoConstant
::country(),
3195 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3196 'street_number' => array('title' => 'Odd / Even Street Number'),
3197 'street_address' => NULL,
3199 'postal_code' => NULL,
3204 $addressFields['civicrm_address']['group_bys'] = array(
3205 'street_address' => NULL,
3207 'postal_code' => NULL,
3208 'state_province_id' =>
3209 array('title' => ts('State/Province'),
3212 array('title' => ts('Country'),
3215 array('title' => ts('County'),
3219 return $addressFields;
3223 * Do AlterDisplay processing on Address Fields
3225 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3226 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3227 $entryFound = FALSE;
3229 if (array_key_exists('civicrm_address_country_id', $row)) {
3230 if ($value = $row['civicrm_address_country_id']) {
3231 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3232 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3233 "reset=1&force=1&{$criteriaQueryParams}&" .
3234 "country_id_op=in&country_id_value={$value}",
3235 $this->_absoluteUrl
, $this->_id
3237 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3238 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3245 if (array_key_exists('civicrm_address_county_id', $row)) {
3246 if ($value = $row['civicrm_address_county_id']) {
3247 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3248 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3249 "reset=1&force=1&{$criteriaQueryParams}&" .
3250 "county_id_op=in&county_id_value={$value}",
3251 $this->_absoluteUrl
, $this->_id
3253 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3254 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3260 // handle state province
3261 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3262 if ($value = $row['civicrm_address_state_province_id']) {
3263 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3265 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3266 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3267 $this->_absoluteUrl
, $this->_id
3269 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3270 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3281 * Adjusts dates passed in to YEAR() for fiscal year.
3283 function fiscalYearOffset($fieldName) {
3284 $config = CRM_Core_Config
::singleton();
3285 $fy = $config->fiscalYearStart
;
3286 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3287 return "YEAR( $fieldName )";
3289 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3293 * Add Address into From Table if required
3295 function addAddressFromClause() {
3296 // include address field if address column is to be included
3297 if ((isset($this->_addressField
) &&
3298 $this->_addressField
3300 $this->isTableSelected('civicrm_address')
3303 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3304 ON ({$this->_aliases['civicrm_contact']}.id =
3305 {$this->_aliases['civicrm_address']}.contact_id) AND
3306 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3311 * Add Phone into From Table if required
3313 function addPhoneFromClause() {
3314 // include address field if address column is to be included
3315 if ($this->isTableSelected('civicrm_phone')
3318 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3319 ON ({$this->_aliases['civicrm_contact']}.id =
3320 {$this->_aliases['civicrm_phone']}.contact_id) AND
3321 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3326 * Get phone columns to add to array
3327 * @param array $options
3328 * - prefix Prefix to add to table (in case of more than one instance of the table)
3329 * - prefix_label Label to give columns from this phone table instance
3330 * @return array phone columns definition
3332 function getPhoneColumns($options = array()){
3333 $defaultOptions = array(
3335 'prefix_label' => '',
3338 $options = array_merge($defaultOptions,$options);
3341 $options['prefix'] . 'civicrm_phone' => array(
3342 'dao' => 'CRM_Core_DAO_Phone',
3344 $options['prefix'] . 'phone' => array(
3345 'title' => ts($options['prefix_label'] . 'Phone'),
3355 * Get address columns to add to array
3356 * @param array $options
3357 * - prefix Prefix to add to table (in case of more than one instance of the table)
3358 * - prefix_label Label to give columns from this address table instance
3359 * @return array address columns definition
3361 function getAddressColumns($options = array()){
3362 $defaultOptions = array(
3364 'prefix_label' => '',
3368 'defaults' => array(
3371 $options = array_merge($defaultOptions,$options);
3372 return $this->addAddressFields(
3373 $options['group_by'],
3374 $options['order_by'],
3375 $options['filters'],
3376 $options['defaults']
3381 function add2group($groupID) {
3382 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3383 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3384 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3386 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3387 $dao = CRM_Core_DAO
::executeQuery($sql);
3389 $contact_ids = array();
3390 // Add resulting contacts to group
3391 while ($dao->fetch()) {
3392 if ($dao->addtogroup_contact_id
) {
3393 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3397 if ( !empty($contact_ids) ) {
3398 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3399 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3402 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3407 /* function used for showing charts on print screen */
3408 static function uploadChartImage() {
3409 // upload strictly for '.png' images
3410 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3411 if (preg_match('/\.png$/', $name)) {
3413 // POST data is usually string data, but we are passing a RAW .png
3414 // so PHP is a bit confused and $_POST is empty. But it has saved
3415 // the raw bits into $HTTP_RAW_POST_DATA
3417 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3419 // prepare the directory
3420 $config = CRM_Core_Config
::singleton();
3421 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3422 if (!file_exists($defaultPath)) {
3423 mkdir($defaultPath, 0777, TRUE);
3426 // full path to the saved image including filename
3427 $destination = $defaultPath . $name;
3430 $jfh = fopen($destination, 'w') or die("can't open file");
3431 fwrite($jfh, $httpRawPostData);
3433 CRM_Utils_System
::civiExit();