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"));
961 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
966 function buildInstanceAndButtons() {
967 CRM_Report_Form_Instance
::buildForm($this);
969 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
971 $this->addElement('submit', $this->_instanceButtonName
, $label);
972 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
973 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
976 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
978 if ($this->_instanceForm
) {
979 $this->assign('instanceForm', TRUE);
982 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
983 $this->addElement('submit', $this->_printButtonName
, $label);
985 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
986 $this->addElement('submit', $this->_pdfButtonName
, $label);
988 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
990 if ($this->_csvSupported
) {
991 $this->addElement('submit', $this->_csvButtonName
, $label);
994 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
995 $this->addElement('select', 'groups', ts('Group'),
996 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
998 $this->assign('group', TRUE);
1001 $label = ts('Add these Contacts to Group');
1002 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1004 $this->addChartOptions();
1005 $this->addButtons(array(
1008 'name' => ts('Preview Report'),
1009 'isDefault' => TRUE,
1015 function buildQuickForm() {
1016 $this->addColumns();
1018 $this->addFilters();
1020 $this->addOptions();
1022 $this->addGroupBys();
1024 $this->addOrderBys();
1026 $this->buildInstanceAndButtons();
1028 //add form rule for report
1029 if (is_callable(array(
1030 $this, 'formRule'))) {
1031 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1035 // a formrule function to ensure that fields selected in group_by
1036 // (if any) should only be the ones present in display/select fields criteria;
1037 // note: works if and only if any custom field selected in group_by.
1038 function customDataFormRule($fields, $ignoreFields = array( )) {
1040 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1041 foreach ($this->_columns
as $tableName => $table) {
1042 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1043 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1044 if (array_key_exists($fieldName, $fields['group_bys']) &&
1045 !array_key_exists($fieldName, $fields['fields'])
1047 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1049 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1050 foreach ($fields['fields'] as $fld => $val) {
1051 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1052 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1063 // Note: $fieldName param allows inheriting class to build operationPairs
1064 // specific to a field.
1065 function getOperationPair($type = "string", $fieldName = NULL) {
1066 // FIXME: At some point we should move these key-val pairs
1067 // to option_group and option_value table.
1069 case CRM_Report_FORM
::OP_INT
:
1070 case CRM_Report_FORM
::OP_FLOAT
:
1072 'lte' => ts('Is less than or equal to'),
1073 'gte' => ts('Is greater than or equal to'),
1074 'bw' => ts('Is between'),
1075 'eq' => ts('Is equal to'),
1076 'lt' => ts('Is less than'),
1077 'gt' => ts('Is greater than'),
1078 'neq' => ts('Is not equal to'),
1079 'nbw' => ts('Is not between'),
1080 'nll' => ts('Is empty (Null)'),
1081 'nnll' => ts('Is not empty (Null)'),
1085 case CRM_Report_FORM
::OP_SELECT
:
1087 'eq' => ts('Is equal to'),
1090 case CRM_Report_FORM
::OP_MONTH
:
1091 case CRM_Report_FORM
::OP_MULTISELECT
:
1093 'in' => ts('Is one of'),
1094 'notin' => ts('Is not one of'),
1098 case CRM_Report_FORM
::OP_DATE
:
1100 'nll' => ts('Is empty (Null)'),
1101 'nnll' => ts('Is not empty (Null)'),
1105 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1106 // use this operator for the values, concatenated with separator. For e.g if
1107 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1109 'mhas' => ts('Is one of'),
1115 'has' => ts('Contains'),
1116 'sw' => ts('Starts with'),
1117 'ew' => ts('Ends with'),
1118 'nhas' => ts('Does not contain'),
1119 'eq' => ts('Is equal to'),
1120 'neq' => ts('Is not equal to'),
1121 'nll' => ts('Is empty (Null)'),
1122 'nnll' => ts('Is not empty (Null)'),
1127 function buildTagFilter() {
1128 $contactTags = CRM_Core_BAO_Tag
::getTags();
1129 if (!empty($contactTags)) {
1130 $this->_columns
['civicrm_tag'] = array(
1131 'dao' => 'CRM_Core_DAO_Tag',
1137 'title' => ts('Tag'),
1139 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1140 'options' => $contactTags,
1148 * Adds group filters to _columns (called from _Constuct
1150 function buildGroupFilter() {
1151 $this->_columns
['civicrm_group']['filters'] = array(
1154 'name' => 'group_id',
1155 'title' => ts('Group'),
1156 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1158 'options' => CRM_Core_PseudoConstant
::group(),
1161 if (empty($this->_columns
['civicrm_group']['dao'])) {
1162 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1164 if (empty($this->_columns
['civicrm_group']['alias'])) {
1165 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1169 function getSQLOperator($operator = "like") {
1170 switch ($operator) {
1203 return 'IS NOT NULL';
1211 function whereClause(&$field, $op,
1215 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1221 if (($min !== NULL && strlen($min) > 0) ||
1222 ($max !== NULL && strlen($max) > 0)
1224 $min = CRM_Utils_Type
::escape($min, $type);
1225 $max = CRM_Utils_Type
::escape($max, $type);
1229 $clauses[] = "( {$field['dbAlias']} >= $min )";
1232 $clauses[] = "( {$field['dbAlias']} < $min )";
1237 $clauses[] = "( {$field['dbAlias']} <= $max )";
1240 $clauses[] = "( {$field['dbAlias']} > $max )";
1244 if (!empty($clauses)) {
1246 $clause = implode(' AND ', $clauses);
1249 $clause = implode(' OR ', $clauses);
1257 if ($value !== NULL && strlen($value) > 0) {
1258 $value = CRM_Utils_Type
::escape($value, $type);
1259 if (strpos($value, '%') === FALSE) {
1260 $value = "'%{$value}%'";
1263 $value = "'{$value}'";
1265 $sqlOP = $this->getSQLOperator($op);
1266 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1272 if ($value !== NULL && is_array($value) && count($value) > 0) {
1273 $sqlOP = $this->getSQLOperator($op);
1274 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1275 //cycle through selections and esacape values
1276 foreach ($value as $key => $selection) {
1277 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1279 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1282 // for numerical values
1283 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1285 if ($op == 'notin') {
1286 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1289 $clause = "( " . $clause . " )";
1295 // mhas == multiple has
1296 if ($value !== NULL && count($value) > 0) {
1297 $sqlOP = $this->getSQLOperator($op);
1298 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1304 if ($value !== NULL && strlen($value) > 0) {
1305 $value = CRM_Utils_Type
::escape($value, $type);
1306 if (strpos($value, '%') === FALSE) {
1308 $value = "'{$value}%'";
1311 $value = "'%{$value}'";
1315 $value = "'{$value}'";
1317 $sqlOP = $this->getSQLOperator($op);
1318 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1324 $sqlOP = $this->getSQLOperator($op);
1325 $clause = "( {$field['dbAlias']} $sqlOP )";
1329 if ($value !== NULL && strlen($value) > 0) {
1330 if (isset($field['clause'])) {
1331 // FIXME: we not doing escape here. Better solution is to use two
1332 // different types - data-type and filter-type
1333 $clause = $field['clause'];
1336 $value = CRM_Utils_Type
::escape($value, $type);
1337 $sqlOP = $this->getSQLOperator($op);
1338 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1339 $value = "'{$value}'";
1341 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1347 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1348 $clause = $this->whereGroupClause($field, $value, $op);
1350 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1351 // not using left join in query because if any contact
1352 // belongs to more than one tag, results duplicate
1354 $clause = $this->whereTagClause($field, $value, $op);
1360 function dateClause($fieldName,
1361 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1364 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1365 $sqlOP = $this->getSQLOperator($relative);
1366 return "( {$fieldName} {$sqlOP} )";
1369 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1372 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1373 $clauses[] = "( {$fieldName} >= $from )";
1377 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1378 $clauses[] = "( {$fieldName} <= {$to} )";
1381 if (!empty($clauses)) {
1382 return implode(' AND ', $clauses);
1388 * @todo - could not find any instances where this is called
1389 * @param unknown_type $relative
1390 * @param String $from
1391 * @param String_type $to
1392 * @return string|NULL
1394 function dateDisplay($relative, $from, $to) {
1395 list($from, $to) = $this->getFromTo($relative, $from, $to);
1398 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1401 $clauses[] = 'Past';
1405 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1408 $clauses[] = 'Today';
1411 if (!empty($clauses)) {
1412 return implode(' - ', $clauses);
1418 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1419 if (empty($totime)) {
1422 //FIX ME not working for relative
1424 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1425 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1426 $from = substr($dateRange['from'], 0, 8);
1427 //Take only Date Part, Sometime Time part is also present in 'to'
1428 $to = substr($dateRange['to'], 0, 8);
1430 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1431 $to = CRM_Utils_Date
::processDate($to, $totime);
1432 return array($from, $to);
1435 function alterDisplay(&$rows) {
1436 // custom code to alter rows
1439 function alterCustomDataDisplay(&$rows) {
1440 // custom code to alter rows having custom values
1441 if (empty($this->_customGroupExtends
)) {
1445 $customFieldIds = array();
1446 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1447 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1448 $customFieldIds[$fieldAlias] = $fieldId;
1451 if (empty($customFieldIds)) {
1455 $customFields = $fieldValueMap = array();
1456 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1458 // skip for type date and ContactReference since date format is already handled
1460 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1461 FROM civicrm_custom_field cf
1462 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1463 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1464 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1465 cg.is_active = 1 AND
1466 cf.is_active = 1 AND
1467 cf.is_searchable = 1 AND
1468 cf.data_type NOT IN ('ContactReference', 'Date') AND
1469 cf.id IN (" . implode(",", $customFieldIds) . ")";
1471 $dao = CRM_Core_DAO
::executeQuery($query);
1472 while ($dao->fetch()) {
1473 foreach ($customFieldCols as $key) {
1474 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1476 if ($dao->option_group_id
) {
1477 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1482 $entryFound = FALSE;
1483 foreach ($rows as $rowNum => $row) {
1484 foreach ($row as $tableCol => $val) {
1485 if (array_key_exists($tableCol, $customFields)) {
1486 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1491 // skip looking further in rows, if first row itself doesn't
1492 // have the column we need
1499 function formatCustomValues($value, $customField, $fieldValueMap) {
1500 if (CRM_Utils_System
::isNull($value)) {
1504 $htmlType = $customField['html_type'];
1506 switch ($customField['data_type']) {
1508 if ($value == '1') {
1509 $retValue = ts('Yes');
1512 $retValue = ts('No');
1517 $retValue = CRM_Utils_System
::formatWikiURL($value);
1529 if ($htmlType == 'Text') {
1530 $retValue = (float)$value;
1534 if ($htmlType == 'Text') {
1544 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1549 if (in_array($htmlType, array(
1550 'Text', 'TextArea'))) {
1554 case 'StateProvince':
1557 switch ($htmlType) {
1558 case 'Multi-Select Country':
1559 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1560 $customData = array();
1561 foreach ($value as $val) {
1563 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1566 $retValue = implode(', ', $customData);
1569 case 'Select Country':
1570 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1573 case 'Select State/Province':
1574 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1577 case 'Multi-Select State/Province':
1578 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1579 $customData = array();
1580 foreach ($value as $val) {
1582 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1585 $retValue = implode(', ', $customData);
1590 case 'Autocomplete-Select':
1591 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1595 case 'AdvMulti-Select':
1596 case 'Multi-Select':
1597 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1598 $customData = array();
1599 foreach ($value as $val) {
1601 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1604 $retValue = implode(', ', $customData);
1619 function removeDuplicates(&$rows) {
1620 if (empty($this->_noRepeats
)) {
1623 $checkList = array();
1625 foreach ($rows as $key => $list) {
1626 foreach ($list as $colName => $colVal) {
1627 if (array_key_exists($colName, $checkList) &&
1628 $checkList[$colName] == $colVal) {
1629 $rows[$key][$colName] = "";
1631 if (in_array($colName, $this->_noRepeats
)) {
1632 $checkList[$colName] = $colVal;
1638 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1639 foreach ($row as $colName => $colVal) {
1640 if (in_array($colName, $fields)) {
1641 $row[$colName] = $row[$colName];
1643 elseif (isset($this->_columnHeaders
[$colName])) {
1645 $row[$colName] = "Subtotal";
1649 unset($row[$colName]);
1655 function grandTotal(&$rows) {
1656 if (!$this->_rollup ||
($this->_rollup
== '') ||
1657 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1661 $lastRow = array_pop($rows);
1663 foreach ($this->_columnHeaders
as $fld => $val) {
1664 if (!in_array($fld, $this->_statFields
)) {
1665 if (!$this->_grandFlag
) {
1666 $lastRow[$fld] = "Grand Total";
1667 $this->_grandFlag
= TRUE;
1670 $lastRow[$fld] = "";
1675 $this->assign('grandStat', $lastRow);
1679 function formatDisplay(&$rows, $pager = TRUE) {
1680 // set pager based on if any limit was applied in the query.
1685 // allow building charts if any
1686 if (!empty($this->_params
['charts']) && !empty($rows)) {
1687 $this->buildChart($rows);
1688 $this->assign('chartEnabled', TRUE);
1689 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1690 $this->assign('chartId', $this->_chartId
);
1693 // unset columns not to be displayed.
1694 foreach ($this->_columnHeaders
as $key => $value) {
1695 if (CRM_Utils_Array
::value('no_display', $value)) {
1696 unset($this->_columnHeaders
[$key]);
1700 // unset columns not to be displayed.
1701 if (!empty($rows)) {
1702 foreach ($this->_noDisplay
as $noDisplayField) {
1703 foreach ($rows as $rowNum => $row) {
1704 unset($this->_columnHeaders
[$noDisplayField]);
1709 // build array of section totals
1710 $this->sectionTotals();
1712 // process grand-total row
1713 $this->grandTotal($rows);
1715 // use this method for formatting rows for display purpose.
1716 $this->alterDisplay($rows);
1717 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1719 // use this method for formatting custom rows for display purpose.
1720 $this->alterCustomDataDisplay($rows);
1723 function buildChart(&$rows) {
1724 // override this method for building charts.
1727 // select() method below has been added recently (v3.3), and many of the report templates might
1728 // still be having their own select() method. We should fix them as and when encountered and move
1729 // towards generalizing the select() method below.
1731 $select = $this->_selectAliases
= array();
1733 foreach ($this->_columns
as $tableName => $table) {
1734 if (array_key_exists('fields', $table)) {
1735 foreach ($table['fields'] as $fieldName => $field) {
1736 if ($tableName == 'civicrm_address') {
1737 $this->_addressField
= TRUE;
1739 if ($tableName == 'civicrm_email') {
1740 $this->_emailField
= TRUE;
1742 if ($tableName == 'civicrm_phone') {
1743 $this->_phoneField
= TRUE;
1746 if (CRM_Utils_Array
::value('required', $field) ||
1747 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1750 // 1. In many cases we want select clause to be built in slightly different way
1751 // for a particular field of a particular type.
1752 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1754 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1755 if ($selectClause) {
1756 $select[] = $selectClause;
1760 // include statistics columns only if set
1761 if (CRM_Utils_Array
::value('statistics', $field)) {
1762 foreach ($field['statistics'] as $stat => $label) {
1763 $alias = "{$tableName}_{$fieldName}_{$stat}";
1764 switch (strtolower($stat)) {
1767 $select[] = "$stat({$field['dbAlias']}) as $alias";
1768 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1769 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1770 $this->_statFields
[$label] = $alias;
1771 $this->_selectAliases
[] = $alias;
1775 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1776 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1777 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1778 $this->_statFields
[$label] = $alias;
1779 $this->_selectAliases
[] = $alias;
1782 case 'count_distinct':
1783 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1784 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1785 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1786 $this->_statFields
[$label] = $alias;
1787 $this->_selectAliases
[] = $alias;
1791 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1792 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1793 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1794 $this->_statFields
[$label] = $alias;
1795 $this->_selectAliases
[] = $alias;
1801 $alias = "{$tableName}_{$fieldName}";
1802 $select[] = "{$field['dbAlias']} as $alias";
1803 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1804 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1805 $this->_selectAliases
[] = $alias;
1811 // select for group bys
1812 if (array_key_exists('group_bys', $table)) {
1813 foreach ($table['group_bys'] as $fieldName => $field) {
1815 if ($tableName == 'civicrm_address') {
1816 $this->_addressField
= TRUE;
1818 if ($tableName == 'civicrm_email') {
1819 $this->_emailField
= TRUE;
1821 if ($tableName == 'civicrm_phone') {
1822 $this->_phoneField
= TRUE;
1824 // 1. In many cases we want select clause to be built in slightly different way
1825 // for a particular field of a particular type.
1826 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1828 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1829 if ($selectClause) {
1830 $select[] = $selectClause;
1834 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1835 && !empty($this->_params
['group_bys_freq'])) {
1836 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1838 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1839 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1840 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1841 $field['title'] = 'Week';
1845 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1846 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1847 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1848 $field['title'] = 'Year';
1852 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1853 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1854 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1855 $field['title'] = 'Month';
1859 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1860 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1861 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1862 $field['title'] = 'Quarter';
1865 // for graphs and charts -
1866 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1867 $this->_interval
= $field['title'];
1868 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1869 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1870 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1872 // just to make sure these values are transfered to rows.
1873 // since we 'll need them for calculation purpose,
1874 // e.g making subtotals look nicer or graphs
1875 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1876 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1883 $this->_selectClauses
= $select;
1884 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1887 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1892 $this->storeWhereHavingClauseArray();
1894 if (empty($this->_whereClauses
)) {
1895 $this->_where
= "WHERE ( 1 ) ";
1896 $this->_having
= "";
1899 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1902 if ($this->_aclWhere
) {
1903 $this->_where
.= " AND {$this->_aclWhere} ";
1906 if (!empty($this->_havingClauses
)) {
1907 // use this clause to construct group by clause.
1908 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1913 * Store Where clauses into an array - breaking out this step makes
1914 * over-riding more flexible as the clauses can be used in constructing a
1915 * temp table that may not be part of the final where clause or added
1916 * in other functions
1918 function storeWhereHavingClauseArray(){
1919 foreach ($this->_columns
as $tableName => $table) {
1920 if (array_key_exists('filters', $table)) {
1921 foreach ($table['filters'] as $fieldName => $field) {
1922 // respect pseudofield to filter spec so fields can be marked as
1923 // not to be handled here
1924 if(!empty($field['pseudofield'])){
1928 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1929 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1930 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1931 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1932 if (is_array($value) && !empty($value)) {
1933 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1937 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1938 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1939 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1940 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1941 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1942 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1946 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1948 $clause = $this->whereClause($field,
1950 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1951 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1952 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1957 if (!empty($clause)) {
1958 if (CRM_Utils_Array
::value('having', $field)) {
1959 $this->_havingClauses
[] = $clause;
1962 $this->_whereClauses
[] = $clause;
1970 function processReportMode() {
1971 $buttonName = $this->controller
->getButtonName();
1973 $output = CRM_Utils_Request
::retrieve(
1976 CRM_Core_DAO
::$_nullObject
1980 CRM_Utils_Request
::retrieve(
1983 CRM_Core_DAO
::$_nullObject
1986 $this->_absoluteUrl
= FALSE;
1988 $this->assign('printOnly', FALSE);
1990 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1991 $this->assign('printOnly', TRUE);
1993 $this->assign('outputMode', 'print');
1994 $this->_outputMode
= 'print';
1995 if ($this->_sendmail
) {
1996 $this->_absoluteUrl
= TRUE;
1999 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2000 $this->assign('printOnly', TRUE);
2002 $this->assign('outputMode', 'pdf');
2003 $this->_outputMode
= 'pdf';
2004 $this->_absoluteUrl
= TRUE;
2006 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2007 $this->assign('printOnly', TRUE);
2009 $this->assign('outputMode', 'csv');
2010 $this->_outputMode
= 'csv';
2011 $this->_absoluteUrl
= TRUE;
2013 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2014 $this->assign('outputMode', 'group');
2015 $this->_outputMode
= 'group';
2017 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2018 $this->assign('outputMode', 'create_report');
2019 $this->_outputMode
= 'create_report';
2022 $this->assign('outputMode', 'html');
2023 $this->_outputMode
= 'html';
2026 // Get today's date to include in printed reports
2028 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2029 $this->assign('reportDate', $reportDate);
2033 function beginPostProcess() {
2034 $this->_params
= $this->controller
->exportValues($this->_name
);
2036 if (empty($this->_params
) &&
2039 $this->_params
= $this->_formValues
;
2042 // hack to fix params when submitted from dashboard, CRM-8532
2043 // fields array is missing because form building etc is skipped
2044 // in dashboard mode for report
2045 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2046 $this->_params
= $this->_formValues
;
2049 $this->_formValues
= $this->_params
;
2050 if (CRM_Core_Permission
::check('administer Reports') &&
2051 isset($this->_id
) &&
2052 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2053 $this->_chartButtonName
== $this->controller
->getButtonName()
2056 $this->assign('updateReportButton', TRUE);
2058 $this->processReportMode();
2061 function buildQuery($applyLimit = TRUE) {
2064 $this->customDataFrom();
2069 // order_by columns not selected for display need to be included in SELECT
2070 $unselectedSectionColumns = $this->unselectedSectionColumns();
2071 foreach ($unselectedSectionColumns as $alias => $section) {
2072 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2075 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2078 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2080 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2084 function groupBy() {
2085 $groupBys = array();
2086 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2087 is_array($this->_params
['group_bys']) &&
2088 !empty($this->_params
['group_bys'])
2090 foreach ($this->_columns
as $tableName => $table) {
2091 if (array_key_exists('group_bys', $table)) {
2092 foreach ($table['group_bys'] as $fieldName => $field) {
2093 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2094 $groupBys[] = $field['dbAlias'];
2101 if (!empty($groupBys)) {
2102 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2106 function orderBy() {
2107 $this->_orderBy
= "";
2108 $this->_sections
= array();
2109 $this->storeOrderByArray();
2110 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2111 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2113 $this->assign('sections', $this->_sections
);
2117 * In some cases other functions want to know which fields are selected for ordering by
2118 * Separating this into a separate function allows it to be called separately from constructing
2119 * the order by clause
2121 function storeOrderByArray() {
2122 $orderBys = array();
2124 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2125 is_array($this->_params
['order_bys']) &&
2126 !empty($this->_params
['order_bys'])
2129 // Proces order_bys in user-specified order
2130 foreach ($this->_params
['order_bys'] as $orderBy) {
2131 $orderByField = array();
2132 foreach ($this->_columns
as $tableName => $table) {
2133 if (array_key_exists('order_bys', $table)) {
2134 // For DAO columns defined in $this->_columns
2135 $fields = $table['order_bys'];
2137 elseif (array_key_exists('extends', $table)) {
2138 // For custom fields referenced in $this->_customGroupExtends
2139 $fields = $table['fields'];
2141 if (!empty($fields) && is_array($fields)) {
2142 foreach ($fields as $fieldName => $field) {
2143 if ($fieldName == $orderBy['column']) {
2144 $orderByField = array_merge($field, $orderBy);
2145 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2152 if (!empty($orderByField)) {
2153 $this->_orderByFields
[] = $orderByField;
2154 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2156 // Record any section headers for assignment to the template
2157 if (CRM_Utils_Array
::value('section', $orderBy)) {
2158 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2159 $this->_sections
[$orderByField['tplField']] = $orderByField;
2165 $this->_orderByArray
= $orderBys;
2167 $this->assign('sections', $this->_sections
);
2170 function unselectedSectionColumns() {
2171 $selectColumns = array();
2172 foreach ($this->_columns
as $tableName => $table) {
2173 if (array_key_exists('fields', $table)) {
2174 foreach ($table['fields'] as $fieldName => $field) {
2175 if (CRM_Utils_Array
::value('required', $field) ||
2176 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2179 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2185 if (is_array($this->_sections
)) {
2186 return array_diff_key($this->_sections
, $selectColumns);
2193 function buildRows($sql, &$rows) {
2194 $dao = CRM_Core_DAO
::executeQuery($sql);
2195 if (!is_array($rows)) {
2199 // use this method to modify $this->_columnHeaders
2200 $this->modifyColumnHeaders();
2202 $unselectedSectionColumns = $this->unselectedSectionColumns();
2204 while ($dao->fetch()) {
2206 foreach ($this->_columnHeaders
as $key => $value) {
2207 if (property_exists($dao, $key)) {
2208 $row[$key] = $dao->$key;
2212 // section headers not selected for display need to be added to row
2213 foreach ($unselectedSectionColumns as $key => $values) {
2214 if (property_exists($dao, $key)) {
2215 $row[$key] = $dao->$key;
2224 * When "order by" fields are marked as sections, this assigns to the template
2225 * an array of total counts for each section. This data is used by the Smarty
2226 * plugin {sectionTotal}
2228 function sectionTotals() {
2230 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2231 if (empty($this->_selectAliases
)) {
2235 if (!empty($this->_sections
)) {
2236 // build the query with no LIMIT clause
2237 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2238 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2240 // pull section aliases out of $this->_sections
2241 $sectionAliases = array_keys($this->_sections
);
2244 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2245 $ifnulls[] = "ifnull($alias, '') as $alias";
2248 /* Group (un-limited) report by all aliases and get counts. This might
2249 * be done more efficiently when the contents of $sql are known, ie. by
2250 * overriding this method in the report class.
2254 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2256 // initialize array of total counts
2258 $dao = CRM_Core_DAO
::executeQuery($query);
2259 while ($dao->fetch()) {
2261 // let $this->_alterDisplay translate any integer ids to human-readable values.
2262 $rows[0] = $dao->toArray();
2263 $this->alterDisplay($rows);
2266 // add totals for all permutations of section values
2269 $aliasCount = count($sectionAliases);
2270 foreach ($sectionAliases as $alias) {
2271 $values[] = $row[$alias];
2272 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2273 if ($i == $aliasCount) {
2274 // the last alias is the lowest-level section header; use count as-is
2275 $totals[$key] = $dao->ct
;
2278 // other aliases are higher level; roll count into their total
2279 $totals[$key] +
= $dao->ct
;
2283 $this->assign('sectionTotals', $totals);
2287 function modifyColumnHeaders() {
2288 // use this method to modify $this->_columnHeaders
2291 function doTemplateAssignment(&$rows) {
2292 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2293 $this->assign_by_ref('rows', $rows);
2294 $this->assign('statistics', $this->statistics($rows));
2297 // override this method to build your own statistics
2298 function statistics(&$rows) {
2299 $statistics = array();
2301 $count = count($rows);
2303 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2307 $this->countStat($statistics, $count);
2309 $this->groupByStat($statistics);
2311 $this->filterStat($statistics);
2316 function countStat(&$statistics, $count) {
2317 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2321 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2322 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2323 'value' => $this->_rowsFound
,
2328 function groupByStat(&$statistics) {
2329 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2330 is_array($this->_params
['group_bys']) &&
2331 !empty($this->_params
['group_bys'])
2333 foreach ($this->_columns
as $tableName => $table) {
2334 if (array_key_exists('group_bys', $table)) {
2335 foreach ($table['group_bys'] as $fieldName => $field) {
2336 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2337 $combinations[] = $field['title'];
2342 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2343 'value' => implode(' & ', $combinations),
2348 function filterStat(&$statistics) {
2349 foreach ($this->_columns
as $tableName => $table) {
2350 if (array_key_exists('filters', $table)) {
2351 foreach ($table['filters'] as $fieldName => $field) {
2352 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2355 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2356 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2357 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2358 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2359 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2361 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2362 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2364 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2365 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2368 $statistics['filters'][] = array(
2369 'title' => $field['title'],
2370 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2373 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2374 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2376 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2377 $statistics['filters'][] = array(
2378 'title' => $field['title'],
2379 'value' => $pair[$rel],
2384 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2387 $pair = $this->getOperationPair(
2388 CRM_Utils_Array
::value('operatorType', $field),
2391 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2392 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2393 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2394 if (in_array($op, array(
2395 'bw', 'nbw')) && ($min ||
$max)) {
2396 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2398 elseif ($op == 'nll' ||
$op == 'nnll') {
2399 $value = $pair[$op];
2401 elseif (is_array($val) && (!empty($val))) {
2402 $options = CRM_Utils_Array
::value('options', $field, array());
2403 foreach ($val as $key => $valIds) {
2404 if (isset($options[$valIds])) {
2405 $val[$key] = $options[$valIds];
2408 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2409 $val = implode(', ', $val);
2410 $value = "{$pair[$op]} " . $val;
2412 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2413 is_array($field['options']) && !empty($field['options'])
2415 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2418 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2422 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2432 function endPostProcess(&$rows = NULL) {
2433 if ( $this->_storeResultSet
) {
2434 $this->_resultSet
= $rows;
2437 if ($this->_outputMode
== 'print' ||
2438 $this->_outputMode
== 'pdf' ||
2442 $content = $this->compileContent();
2443 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2447 if ($this->_sendmail
) {
2448 $config = CRM_Core_Config
::singleton();
2449 $attachments = array();
2451 if ($this->_outputMode
== 'csv') {
2452 $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'];
2454 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2455 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2456 file_put_contents($csvFullFilename, $csvContent);
2457 $attachments[] = array(
2458 'fullPath' => $csvFullFilename,
2459 'mime_type' => 'text/csv',
2460 'cleanName' => 'CiviReport.csv',
2463 if ($this->_outputMode
== 'pdf') {
2464 // generate PDF content
2465 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2466 file_put_contents($pdfFullFilename,
2467 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2468 TRUE, array('orientation' => 'landscape')
2471 // generate Email Content
2472 $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'];
2474 $attachments[] = array(
2475 'fullPath' => $pdfFullFilename,
2476 'mime_type' => 'application/pdf',
2477 'cleanName' => 'CiviReport.pdf',
2481 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2482 $this->_outputMode
, $attachments
2484 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2487 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2490 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2492 elseif ($this->_outputMode
== 'print') {
2496 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2497 $config = CRM_Core_Config
::singleton();
2498 //get chart image name
2499 $chartImg = $this->_chartId
. '.png';
2500 //get image url path
2501 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2502 $uploadUrl .= $chartImg;
2503 //get image doc path to overwrite
2504 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2506 $chart = imagecreatefrompng($uploadUrl);
2507 //convert it into formattd png
2508 header('Content-type: image/png');
2509 //overwrite with same image
2510 imagepng($chart, $uploadImg);
2512 imagedestroy($chart);
2514 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2516 CRM_Utils_System
::civiExit();
2518 elseif ($this->_outputMode
== 'csv') {
2519 CRM_Report_Utils_Report
::export2csv($this, $rows);
2521 elseif ($this->_outputMode
== 'group') {
2522 $group = $this->_params
['groups'];
2523 $this->add2group($group);
2525 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2526 CRM_Report_Form_Instance
::postProcess($this);
2528 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2529 $this->_outputMode
== 'create_report' ) {
2530 $this->_createNew
= TRUE;
2531 CRM_Report_Form_Instance
::postProcess($this);
2535 function storeResultSet() {
2536 $this->_storeResultSet
= TRUE;
2539 function getResultSet() {
2540 return $this->_resultSet
;
2544 * Get Template file name - use default form template if a specific one has not been set up for this report
2547 function getTemplateFileName(){
2548 $defaultTpl = parent
::getTemplateFileName();
2549 $template = CRM_Core_Smarty
::singleton();
2550 if (!$template->template_exists($defaultTpl)) {
2551 $defaultTpl = 'CRM/Report/Form.tpl';
2557 * Compile the report content
2559 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2561 function compileContent(){
2562 $templateFile = $this->getHookedTemplateFileName();
2563 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2567 function postProcess() {
2568 // get ready with post process params
2569 $this->beginPostProcess();
2572 $sql = $this->buildQuery();
2574 // build array of result based on column headers. This method also allows
2575 // modifying column headers before using it to build result set i.e $rows.
2577 $this->buildRows($sql, $rows);
2579 // format result set.
2580 $this->formatDisplay($rows);
2582 // assign variables to templates
2583 $this->doTemplateAssignment($rows);
2585 // do print / pdf / instance stuff if needed
2586 $this->endPostProcess($rows);
2589 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2590 // lets do the pager if in html mode
2591 $this->_limit
= NULL;
2592 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2593 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2595 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2597 if (!$pageId && !empty($_POST)) {
2598 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2599 $pageId = max((int)@$_POST['crmPID_B'], 1);
2601 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2602 $pageId = max((int)@$_POST['crmPID'], 1);
2604 unset($_POST['crmPID_B'], $_POST['crmPID']);
2607 $pageId = $pageId ?
$pageId : 1;
2608 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2609 $offset = ($pageId - 1) * $rowCount;
2611 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2612 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2614 $this->_limit
= " LIMIT $offset, $rowCount";
2615 return array($offset, $rowCount);
2619 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2620 if ($this->_limit
&& ($this->_limit
!= '')) {
2621 $sql = "SELECT FOUND_ROWS();";
2622 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2624 'total' => $this->_rowsFound
,
2625 'rowCount' => $rowCount,
2626 'status' => ts('Records') . ' %%StatusMessage%%',
2627 'buttonBottom' => 'PagerBottomButton',
2628 'buttonTop' => 'PagerTopButton',
2629 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2632 $pager = new CRM_Utils_Pager($params);
2633 $this->assign_by_ref('pager', $pager);
2637 function whereGroupClause($field, $value, $op) {
2639 $smartGroupQuery = "";
2641 $group = new CRM_Contact_DAO_Group();
2642 $group->is_active
= 1;
2644 $smartGroups = array();
2645 while ($group->fetch()) {
2646 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2647 $smartGroups[] = $group->id
;
2651 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2653 $smartGroupQuery = '';
2654 if (!empty($smartGroups)) {
2655 $smartGroups = implode(',', $smartGroups);
2656 $smartGroupQuery = " UNION DISTINCT
2657 SELECT DISTINCT smartgroup_contact.contact_id
2658 FROM civicrm_group_contact_cache smartgroup_contact
2659 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2662 $sqlOp = $this->getSQLOperator($op);
2663 if (!is_array($value)) {
2664 $value = array($value);
2666 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2668 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2669 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2670 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2671 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2672 {$smartGroupQuery} ) ";
2675 function whereTagClause($field, $value, $op) {
2676 // not using left join in query because if any contact
2677 // belongs to more than one tag, results duplicate
2679 $sqlOp = $this->getSQLOperator($op);
2680 if (!is_array($value)) {
2681 $value = array($value);
2683 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2685 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2686 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2687 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2688 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2691 function buildACLClause($tableAlias = 'contact_a') {
2692 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2695 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2696 if (empty($this->_customGroupExtends
)) {
2699 if (!is_array($this->_customGroupExtends
)) {
2700 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2702 $customGroupWhere = '';
2703 if (!empty($permCustomGroupIds)) {
2704 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2707 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2708 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2709 FROM civicrm_custom_group cg
2710 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2711 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2713 cg.is_active = 1 AND
2714 cf.is_active = 1 AND
2715 cf.is_searchable = 1
2716 ORDER BY cg.weight, cf.weight";
2717 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2720 while ($customDAO->fetch()) {
2721 if ($customDAO->table_name
!= $curTable) {
2722 $curTable = $customDAO->table_name
;
2723 $curFields = $curFilters = array();
2726 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2727 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2728 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2729 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2732 'fields', 'filters', 'group_bys') as $colKey) {
2733 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2734 $this->_columns
[$curTable][$colKey] = array();
2738 $fieldName = 'custom_' . $customDAO->cf_id
;
2741 // this makes aliasing work in favor
2742 $curFields[$fieldName] = array(
2743 'name' => $customDAO->column_name
,
2744 'title' => $customDAO->label
,
2745 'dataType' => $customDAO->data_type
,
2746 'htmlType' => $customDAO->html_type
,
2749 if ($this->_customGroupFilters
) {
2750 // this makes aliasing work in favor
2751 $curFilters[$fieldName] = array(
2752 'name' => $customDAO->column_name
,
2753 'title' => $customDAO->label
,
2754 'dataType' => $customDAO->data_type
,
2755 'htmlType' => $customDAO->html_type
,
2759 switch ($customDAO->data_type
) {
2762 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2763 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2764 // CRM-6946, show time part for datetime date fields
2765 if ($customDAO->time_format
) {
2766 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2771 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2772 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2776 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2780 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2781 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2785 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2786 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2790 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2791 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2795 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2797 if (!empty($customDAO->option_group_id
)) {
2798 if (in_array($customDAO->html_type
, array(
2799 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2800 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2803 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2805 if ($this->_customGroupFilters
) {
2806 $curFilters[$fieldName]['options'] = array();
2807 $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')));
2808 while ($ogDAO->fetch()) {
2809 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2815 case 'StateProvince':
2816 if (in_array($customDAO->html_type
, array(
2817 'Multi-Select State/Province'))) {
2818 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2821 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2823 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2827 if (in_array($customDAO->html_type
, array(
2828 'Multi-Select Country'))) {
2829 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2832 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2834 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2837 case 'ContactReference':
2838 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2839 $curFilters[$fieldName]['name'] = 'display_name';
2840 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2842 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2843 $curFields[$fieldName]['name'] = 'display_name';
2844 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2848 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2849 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2852 if (!array_key_exists('type', $curFields[$fieldName])) {
2853 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2857 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2859 if ($this->_customGroupFilters
) {
2860 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2862 if ($this->_customGroupGroupBy
) {
2863 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2868 function customDataFrom() {
2869 if (empty($this->_customGroupExtends
)) {
2872 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2874 foreach ($this->_columns
as $table => $prop) {
2875 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2876 $extendsTable = $mapper[$prop['extends']];
2878 // check field is in params
2879 if (!$this->isFieldSelected($prop)) {
2883 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2885 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2886 // handle for ContactReference
2887 if (array_key_exists('fields', $prop)) {
2888 foreach ($prop['fields'] as $fieldName => $field) {
2889 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2890 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2892 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2900 function isFieldSelected($prop) {
2905 if (!empty($this->_params
['fields'])) {
2906 foreach (array_keys($prop['fields']) as $fieldAlias) {
2907 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2908 if ($customFieldId) {
2909 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2913 //might be survey response field.
2914 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2915 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2923 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2924 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2925 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2931 if (!empty($this->_params
['order_bys'])) {
2932 foreach (array_keys($prop['fields']) as $fieldAlias) {
2933 foreach ($this->_params
['order_bys'] as $orderBy) {
2934 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2941 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2942 foreach ($prop['filters'] as $fieldAlias => $val) {
2944 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2945 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2946 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2947 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2953 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2954 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2965 * Check for empty order_by configurations and remove them; also set
2966 * template to hide them.
2968 function preProcessOrderBy(&$formValues) {
2969 // Object to show/hide form elements
2970 $_showHide = new CRM_Core_ShowHideBlocks('', '');
2972 $_showHide->addShow('optionField_1');
2974 // Cycle through order_by options; skip any empty ones, and hide them as well
2977 if (!empty($formValues['order_bys'])) {
2978 foreach ($formValues['order_bys'] as $order_by) {
2979 if ($order_by['column'] && $order_by['column'] != '-') {
2980 $_showHide->addShow('optionField_' . $n);
2981 $orderBys[$n] = $order_by;
2986 for ($i = $n; $i <= 5; $i++
) {
2988 $_showHide->addHide('optionField_' . $i);
2992 // overwrite order_by options with modified values
2993 if (!empty($orderBys)) {
2994 $formValues['order_bys'] = $orderBys;
2997 $formValues['order_bys'] = array(1 => array('column' => '-'));
3000 // assign show/hide data to template
3001 $_showHide->addToTemplate();
3005 * Does table name have columns in SELECT clause?
3007 * @param string $tableName Name of table (index of $this->_columns array)
3011 function isTableSelected($tableName) {
3012 return in_array($tableName, $this->selectedTables());
3016 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3017 * (building the array if it's unset)
3019 * @return Array $this->_selectedTables
3021 function selectedTables() {
3022 if (!$this->_selectedTables
) {
3023 $orderByColumns = array();
3024 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3025 foreach ($this->_params
['order_bys'] as $orderBy) {
3026 $orderByColumns[] = $orderBy['column'];
3030 foreach ($this->_columns
as $tableName => $table) {
3031 if (array_key_exists('fields', $table)) {
3032 foreach ($table['fields'] as $fieldName => $field) {
3033 if (CRM_Utils_Array
::value('required', $field) ||
3034 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3036 $this->_selectedTables
[] = $tableName;
3041 if (array_key_exists('order_bys', $table)) {
3042 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3043 if (in_array($orderByName, $orderByColumns)) {
3044 $this->_selectedTables
[] = $tableName;
3049 if (array_key_exists('filters', $table)) {
3050 foreach ($table['filters'] as $filterName => $filter) {
3051 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3052 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3053 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3055 $this->_selectedTables
[] = $tableName;
3062 return $this->_selectedTables
;
3066 * @deprecated - use getAddressColumns which is a more accurate description
3067 * and also accepts an array of options rather than a long list
3069 * function for adding address fields to construct function in reports
3070 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3071 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3072 * @return array address fields for construct clause
3074 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3075 'country_id' => TRUE)) {
3076 $addressFields = array(
3077 'civicrm_address' =>
3079 'dao' => 'CRM_Core_DAO_Address',
3083 array('title' => ts('Address Name'),
3084 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3087 array('title' => ts('Street Address'),
3088 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3090 'supplemental_address_1' =>
3091 array('title' => ts('Supplementary Address Field 1'),
3092 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3094 'supplemental_address_2' =>
3095 array('title' => ts('Supplementary Address Field 2'),
3096 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3100 'name' => 'street_number',
3101 'title' => ts('Street Number'),
3103 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3107 'name' => 'street_name',
3108 'title' => ts('Street Name'),
3110 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3114 'name' => 'street_unit',
3115 'title' => ts('Street Unit'),
3117 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3120 array('title' => ts('City'),
3121 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3124 array('title' => ts('Postal Code'),
3125 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3128 array('title' => ts('County'),
3129 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3131 'state_province_id' =>
3132 array('title' => ts('State/Province'),
3133 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3136 array('title' => ts('Country'),
3137 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3140 'grouping' => 'location-fields',
3145 $addressFields['civicrm_address']['filters'] = array(
3146 'street_number' => array('title' => ts('Street Number'),
3148 'name' => 'street_number',
3150 'street_name' => array('title' => ts('Street Name'),
3151 'name' => 'street_name',
3152 'operator' => 'like',
3154 'postal_code' => array('title' => ts('Postal Code'),
3156 'name' => 'postal_code',
3158 'city' => array('title' => ts('City'),
3159 'operator' => 'like',
3162 'county_id' => array(
3163 'name' => 'county_id',
3164 'title' => ts('County'),
3165 'type' => CRM_Utils_Type
::T_INT
,
3167 CRM_Report_Form
::OP_MULTISELECT
,
3169 CRM_Core_PseudoConstant
::county(),
3171 'state_province_id' => array(
3172 'name' => 'state_province_id',
3173 'title' => ts('State/Province'),
3174 'type' => CRM_Utils_Type
::T_INT
,
3176 CRM_Report_Form
::OP_MULTISELECT
,
3178 CRM_Core_PseudoConstant
::stateProvince(),
3180 'country_id' => array(
3181 'name' => 'country_id',
3182 'title' => ts('Country'),
3183 'type' => CRM_Utils_Type
::T_INT
,
3185 CRM_Report_Form
::OP_MULTISELECT
,
3187 CRM_Core_PseudoConstant
::country(),
3193 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3194 'street_number' => array('title' => 'Odd / Even Street Number'),
3195 'street_address' => NULL,
3197 'postal_code' => NULL,
3202 $addressFields['civicrm_address']['group_bys'] = array(
3203 'street_address' => NULL,
3205 'postal_code' => NULL,
3206 'state_province_id' =>
3207 array('title' => ts('State/Province'),
3210 array('title' => ts('Country'),
3213 array('title' => ts('County'),
3217 return $addressFields;
3221 * Do AlterDisplay processing on Address Fields
3223 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3224 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3225 $entryFound = FALSE;
3227 if (array_key_exists('civicrm_address_country_id', $row)) {
3228 if ($value = $row['civicrm_address_country_id']) {
3229 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3230 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3231 "reset=1&force=1&{$criteriaQueryParams}&" .
3232 "country_id_op=in&country_id_value={$value}",
3233 $this->_absoluteUrl
, $this->_id
3235 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3236 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3243 if (array_key_exists('civicrm_address_county_id', $row)) {
3244 if ($value = $row['civicrm_address_county_id']) {
3245 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3246 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3247 "reset=1&force=1&{$criteriaQueryParams}&" .
3248 "county_id_op=in&county_id_value={$value}",
3249 $this->_absoluteUrl
, $this->_id
3251 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3252 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3258 // handle state province
3259 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3260 if ($value = $row['civicrm_address_state_province_id']) {
3261 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3263 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3264 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3265 $this->_absoluteUrl
, $this->_id
3267 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3268 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3279 * Adjusts dates passed in to YEAR() for fiscal year.
3281 function fiscalYearOffset($fieldName) {
3282 $config = CRM_Core_Config
::singleton();
3283 $fy = $config->fiscalYearStart
;
3284 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3285 return "YEAR( $fieldName )";
3287 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3291 * Add Address into From Table if required
3293 function addAddressFromClause() {
3294 // include address field if address column is to be included
3295 if ((isset($this->_addressField
) &&
3296 $this->_addressField
3298 $this->isTableSelected('civicrm_address')
3301 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3302 ON ({$this->_aliases['civicrm_contact']}.id =
3303 {$this->_aliases['civicrm_address']}.contact_id) AND
3304 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3309 * Add Phone into From Table if required
3311 function addPhoneFromClause() {
3312 // include address field if address column is to be included
3313 if ($this->isTableSelected('civicrm_phone')
3316 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3317 ON ({$this->_aliases['civicrm_contact']}.id =
3318 {$this->_aliases['civicrm_phone']}.contact_id) AND
3319 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3324 * Get phone columns to add to array
3325 * @param array $options
3326 * - prefix Prefix to add to table (in case of more than one instance of the table)
3327 * - prefix_label Label to give columns from this phone table instance
3328 * @return array phone columns definition
3330 function getPhoneColumns($options = array()){
3331 $defaultOptions = array(
3333 'prefix_label' => '',
3336 $options = array_merge($defaultOptions,$options);
3339 $options['prefix'] . 'civicrm_phone' => array(
3340 'dao' => 'CRM_Core_DAO_Phone',
3342 $options['prefix'] . 'phone' => array(
3343 'title' => ts($options['prefix_label'] . 'Phone'),
3353 * Get address columns to add to array
3354 * @param array $options
3355 * - prefix Prefix to add to table (in case of more than one instance of the table)
3356 * - prefix_label Label to give columns from this address table instance
3357 * @return array address columns definition
3359 function getAddressColumns($options = array()){
3360 $defaultOptions = array(
3362 'prefix_label' => '',
3366 'defaults' => array(
3369 $options = array_merge($defaultOptions,$options);
3370 return $this->addAddressFields(
3371 $options['group_by'],
3372 $options['order_by'],
3373 $options['filters'],
3374 $options['defaults']
3379 function add2group($groupID) {
3380 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3381 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3382 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3384 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3385 $dao = CRM_Core_DAO
::executeQuery($sql);
3387 $contact_ids = array();
3388 // Add resulting contacts to group
3389 while ($dao->fetch()) {
3390 if ($dao->addtogroup_contact_id
) {
3391 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3395 if ( !empty($contact_ids) ) {
3396 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3397 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3400 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3405 /* function used for showing charts on print screen */
3406 static function uploadChartImage() {
3407 // upload strictly for '.png' images
3408 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3409 if (preg_match('/\.png$/', $name)) {
3411 // POST data is usually string data, but we are passing a RAW .png
3412 // so PHP is a bit confused and $_POST is empty. But it has saved
3413 // the raw bits into $HTTP_RAW_POST_DATA
3415 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3417 // prepare the directory
3418 $config = CRM_Core_Config
::singleton();
3419 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3420 if (!file_exists($defaultPath)) {
3421 mkdir($defaultPath, 0777, TRUE);
3424 // full path to the saved image including filename
3425 $destination = $defaultPath . $name;
3428 $jfh = fopen($destination, 'w') or die("can't open file");
3429 fwrite($jfh, $httpRawPostData);
3431 CRM_Utils_System
::civiExit();