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 $_customGroupExtendsJoin = array();
139 protected $_customGroupFilters = TRUE;
140 protected $_customGroupGroupBy = FALSE;
141 protected $_customGroupJoin = 'LEFT JOIN';
147 protected $_tagFilter = FALSE;
150 * build groups filter
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * An attribute for checkbox/radio form field layout
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
174 protected $_force = 1;
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_grandFlag = FALSE;
194 protected $_rowsFound = NULL;
195 protected $_selectAliases = array();
196 protected $_rollup = NULL;
197 protected $_limit = NULL;
198 protected $_sections = NULL;
199 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
200 protected $_absoluteUrl = FALSE;
203 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
207 protected $_storeResultSet = FALSE;
210 * When _storeResultSet Flag is set use this var to store result set in form of array
214 protected $_resultSet = array();
217 * To what frequency group-by a date column
221 protected $_groupByDateFreq = array(
223 'YEARWEEK' => 'Week',
224 'QUARTER' => 'Quarter',
229 * Variables to hold the acl inner join and where clause
231 protected $_aclFrom = NULL;
232 protected $_aclWhere = NULL;
235 * Array of DAO tables having columns included in SELECT or ORDER BY clause
239 protected $_selectedTables;
242 * outputmode e.g 'print', 'csv', 'pdf'
243 * @todo have declared this as public as fixing an e-Notice in a point release - would
244 * be better converted to protected in 4.5
249 public $_having = NULL;
250 public $_select = NULL;
251 public $_selectClauses = array();
252 public $_columnHeaders = array();
253 public $_orderBy = NULL;
254 public $_orderByFields = array();
255 public $_orderByArray = array();
256 public $_groupBy = NULL;
257 public $_whereClauses = array();
258 public $_havingClauses = array();
261 * Is this being called without a form controller (ie. the report is being render outside the normal form
262 * - e.g the api is retrieving the rows
265 public $noController = FALSE;
268 * Variable to hold the currency alias
270 protected $_currencyColumn = NULL;
275 function __construct() {
276 parent
::__construct();
279 if ($this->_tagFilter
) {
280 $this->buildTagFilter();
282 if ($this->_exposeContactID
) {
283 if (array_key_exists('civicrm_contact', $this->_columns
)) {
284 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
286 'title' => 'Contact ID',
292 if ($this->_groupFilter
) {
293 $this->buildGroupFilter();
296 // Get all custom groups
297 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
299 // Get the custom groupIds for which the user has VIEW permission
300 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
301 // and addCustomDataToColumns() will allow access to all custom groups.
302 $permCustomGroupIds = array();
303 if (!CRM_Core_Permission
::check('access all custom data')) {
304 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
305 // do not allow custom data for reports if user doesn't have
306 // permission to access custom data.
307 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
308 $this->_customGroupExtends
= array();
312 // merge custom data columns to _columns list, if any
313 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
315 // add / modify display columns, filters ..etc
316 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
318 //assign currencyColumn variable to tpl
319 $this->assign('currencyColumn', $this->_currencyColumn
);
322 function preProcessCommon() {
324 CRM_Utils_Request
::retrieve(
327 CRM_Core_DAO
::$_nullObject
330 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
332 $this->assign('section', $this->_section
);
333 CRM_Core_Region
::instance('page-header')->add(array(
334 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
336 if(!$this->noController
) {
337 $this->setID($this->get('instanceId'));
340 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
342 $this->setID( CRM_Report_Utils_Report
::getInstanceIDForPath());
346 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
347 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
348 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
352 $this->assign('instanceId', $this->_id
);
353 $params = array('id' => $this->_id
);
354 $this->_instanceValues
= array();
355 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
357 $this->_instanceValues
359 if (empty($this->_instanceValues
)) {
360 CRM_Core_Error
::fatal("Report could not be loaded.");
363 if (!empty($this->_instanceValues
['permission']) &&
364 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
365 CRM_Core_Permission
::check('administer Reports')
368 CRM_Utils_System
::permissionDenied();
369 CRM_Utils_System
::civiExit();
372 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
374 $this->_formValues
= unserialize($formValues);
377 $this->_formValues
= NULL;
380 // lets always do a force if reset is found in the url.
381 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
386 $this->assign('mode', 'instance');
388 elseif (!$this->noController
) {
389 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
390 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
391 if (($instanceCount > 0) && $optionValueID) {
392 $this->assign('instanceUrl',
393 CRM_Utils_System
::url('civicrm/report/list',
394 "reset=1&ovid=$optionValueID"
398 if ($optionValueID) {
399 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
403 $this->assign('mode', 'template');
406 // lets display the Report Settings section
407 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
409 // Do not display Report Settings section if administer Reports permission is absent OR
410 // if report instance is reserved and administer reserved reports absent
411 if (!CRM_Core_Permission
::check('administer Reports') ||
412 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
413 $this->_instanceForm
= FALSE;
416 $this->assign('criteriaForm', FALSE);
417 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
418 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
419 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
420 $this->assign('criteriaForm', TRUE);
421 $this->_criteriaForm
= TRUE;
425 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
426 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
427 $this->_printButtonName
= $this->getButtonName('submit', 'print');
428 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
429 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
430 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
431 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
434 function addBreadCrumb() {
438 'title' => ts('Report Templates'),
439 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
443 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
446 function preProcess() {
447 $this->preProcessCommon();
450 $this->addBreadCrumb();
453 foreach ($this->_columns
as $tableName => $table) {
455 if (!isset($table['alias'])) {
456 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
459 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
462 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
464 $daoOrBaoName = NULL;
465 // higher preference to bao object
466 if (array_key_exists('bao', $table)) {
467 $daoOrBaoName = $table['bao'];
468 $expFields = $daoOrBaoName::exportableFields( );
470 elseif (array_key_exists('dao', $table)){
471 $daoOrBaoName = $table['dao'];
472 $expFields = $daoOrBaoName::export( );
475 $expFields = array();
478 $doNotCopy = array('required');
480 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
481 foreach ($fieldGroups as $fieldGrp) {
482 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
483 foreach ($table[$fieldGrp] as $fieldName => $field) {
484 // $name is the field name used to reference the BAO/DAO export fields array
485 $name = isset($field['name']) ?
$field['name'] : $fieldName;
487 // Sometimes the field name key in the BAO/DAO export fields array is
488 // different from the actual database field name.
489 // Unset $field['name'] so that actual database field name can be obtained
490 // from the BAO/DAO export fields array.
491 unset($field['name']);
493 if (array_key_exists($name, $expFields)) {
494 foreach ($doNotCopy as $dnc) {
495 // unset the values we don't want to be copied.
496 unset($expFields[$name][$dnc]);
499 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
502 foreach ($expFields[$name] as $property => $val) {
503 if (!array_key_exists($property, $field)) {
504 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
511 if (CRM_Utils_Array
::value('no_repeat', $field)) {
512 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
514 if (CRM_Utils_Array
::value('no_display', $field)) {
515 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
518 // set alias = table-name, unless already set
519 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
520 $this->_columns
[$tableName]['alias'] : $tableName
522 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
524 // set name = fieldName, unless already set
525 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
526 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
529 // set dbAlias = alias.name, unless already set
530 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
531 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
534 // a few auto fills for filters
535 if ($fieldGrp == 'filters') {
536 // fill operator types
537 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
538 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
539 case CRM_Utils_Type
::T_MONEY
:
540 case CRM_Utils_Type
::T_FLOAT
:
541 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
543 case CRM_Utils_Type
::T_INT
:
544 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
546 case CRM_Utils_Type
::T_DATE
:
547 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
549 case CRM_Utils_Type
::T_BOOLEAN
:
550 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
551 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
552 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
553 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
558 (array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
559 ||
array_key_exists('enumValues', $this->_columns
[$tableName][$fieldGrp][$fieldName]))
561 // with multiple options operator-type is generally multi-select
562 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
563 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
565 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
576 // copy filters to a separate handy variable
577 if (array_key_exists('filters', $table)) {
578 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
581 if (array_key_exists('group_bys', $table)) {
582 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
585 if (array_key_exists('fields', $table)) {
586 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
591 $this->setDefaultValues(FALSE);
594 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
595 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
596 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
597 CRM_Report_Utils_Get
::processChart($this->_defaults
);
600 $this->_formValues
= $this->_defaults
;
601 $this->postProcess();
605 function setDefaultValues($freeze = TRUE) {
606 $freezeGroup = array();
608 // FIXME: generalizing form field naming conventions would reduce
609 // lots of lines below.
610 foreach ($this->_columns
as $tableName => $table) {
611 if (array_key_exists('fields', $table)) {
612 foreach ($table['fields'] as $fieldName => $field) {
613 if (!CRM_Utils_Array
::value('no_display', $field)) {
614 if (isset($field['required'])) {
616 $this->_defaults
['fields'][$fieldName] = 1;
619 // find element object, so that we could use quickform's freeze method
620 // for required elements
621 $obj = $this->getElementFromGroup("fields", $fieldName);
623 $freezeGroup[] = $obj;
627 elseif (isset($field['default'])) {
628 $this->_defaults
['fields'][$fieldName] = $field['default'];
634 if (array_key_exists('group_bys', $table)) {
635 foreach ($table['group_bys'] as $fieldName => $field) {
636 if (isset($field['default'])) {
637 if (CRM_Utils_Array
::value('frequency', $field)) {
638 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
640 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
644 if (array_key_exists('filters', $table)) {
645 foreach ($table['filters'] as $fieldName => $field) {
646 if (isset($field['default'])) {
647 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
648 if(is_array($field['default'])){
649 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
650 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
651 $this->_defaults
["{$fieldName}_relative"] = 0;
654 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
658 $this->_defaults
["{$fieldName}_value"] = $field['default'];
661 //assign default value as "in" for multiselect
662 //operator, To freeze the select element
663 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
664 $this->_defaults
["{$fieldName}_op"] = 'in';
666 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
667 $this->_defaults
["{$fieldName}_op"] = 'mhas';
669 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
670 $this->_defaults
["{$fieldName}_op"] = $op;
676 array_key_exists('order_bys', $table) &&
677 is_array($table['order_bys'])
679 if (!array_key_exists('order_bys', $this->_defaults
)) {
680 $this->_defaults
['order_bys'] = array();
682 foreach ($table['order_bys'] as $fieldName => $field) {
684 CRM_Utils_Array
::value('default', $field) ||
685 CRM_Utils_Array
::value('default_order', $field) ||
686 CRM_Utils_Array
::value('default_is_section', $field) ||
687 CRM_Utils_Array
::value('default_weight', $field)
690 'column' => $fieldName,
691 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
692 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
695 if (CRM_Utils_Array
::value('default_weight', $field)) {
696 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
699 array_unshift($this->_defaults
['order_bys'], $order_by);
705 foreach ($this->_options
as $fieldName => $field) {
706 if (isset($field['default'])) {
707 $this->_defaults
['options'][$fieldName] = $field['default'];
712 if (!empty($this->_submitValues
)) {
713 $this->preProcessOrderBy($this->_submitValues
);
716 $this->preProcessOrderBy($this->_defaults
);
719 // lets finish freezing task here itself
720 if (!empty($freezeGroup)) {
721 foreach ($freezeGroup as $elem) {
726 if ($this->_formValues
) {
727 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
730 if ($this->_instanceValues
) {
731 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
734 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
736 return $this->_defaults
;
739 function getElementFromGroup($group, $grpFieldName) {
740 $eleObj = $this->getElement($group);
741 foreach ($eleObj->_elements
as $index => $obj) {
742 if ($grpFieldName == $obj->_attributes
['name']) {
750 * Setter for $_params
751 * @param array $params
753 function setParams($params) {
754 $this->_params
= $params;
761 function setID($instanceid) {
762 $this->_id
= $instanceid;
767 * @param boolean $force
769 function setForce($isForce) {
770 $this->_force
= $isForce;
773 * Getter for $_defaultValues
774 * @return array $_defaultValues
776 function getDefaultValues() {
777 return $this->_defaults
;
780 function addColumns() {
783 foreach ($this->_columns
as $tableName => $table) {
784 if (array_key_exists('fields', $table)) {
785 foreach ($table['fields'] as $fieldName => $field) {
787 if (!CRM_Utils_Array
::value('no_display', $field)) {
788 foreach ( array('table', 'field') as $var) {
789 if (!empty($
{$var}['grouping'])) {
790 if (!is_array($
{$var}['grouping'])) {
791 $tableName = $
{$var}['grouping'];
793 $tableName = array_keys($
{$var}['grouping']);
794 $tableName = $tableName[0];
795 $groupTitle = array_values($
{$var}['grouping']);
796 $groupTitle = $groupTitle[0];
801 if (!$groupTitle && isset($table['group_title'])) {
802 $groupTitle = $table['group_title'];
805 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
806 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
807 $colGroups[$tableName]['group_title'] = $groupTitle;
810 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
816 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
817 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
819 $this->assign('colGroups', $colGroups);
822 function addFilters() {
823 $options = $filters = array();
825 foreach ($this->_filters
as $table => $attributes) {
826 foreach ($attributes as $fieldName => $field) {
827 // get ready with option value pair
828 // @ 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
830 $operations = $this->getOperationPair(
831 CRM_Utils_Array
::value('operatorType', $field),
834 $filters[$table][$fieldName] = $field;
836 switch (CRM_Utils_Array
::value('operatorType', $field)) {
837 case CRM_Report_Form
::OP_MONTH
:
838 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
839 // If there's no option list for this filter, define one.
840 $field['options'] = array(
849 9 => ts('September'),
851 11 => ts('November'),
852 12 => ts('December'),
854 // Add this option list to this column _columns. This is
855 // required so that filter statistics show properly.
856 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
858 case CRM_Report_FORM
::OP_MULTISELECT
:
859 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
860 // assume a multi-select field
861 if (!empty($field['options'])) {
862 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
863 if (count($operations) <= 1) {
866 $select = $this->addElement('select', "{$fieldName}_value", NULL,
867 $field['options'], array(
869 'style' => 'min-width:250px',
872 $select->setMultiple(TRUE);
876 case CRM_Report_FORM
::OP_SELECT
:
877 // assume a select field
878 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
879 if (!empty($field['options']))
880 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
883 case CRM_Report_FORM
::OP_DATE
:
884 // build datetime fields
885 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
889 case CRM_Report_FORM
::OP_DATETIME
:
890 // build datetime fields
891 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
895 case CRM_Report_FORM
::OP_INT
:
896 case CRM_Report_FORM
::OP_FLOAT
:
897 // and a min value input box
898 $this->add('text', "{$fieldName}_min", ts('Min'));
899 // and a max value input box
900 $this->add('text', "{$fieldName}_max", ts('Max'));
902 // default type is string
903 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
904 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
906 // we need text box for value input
907 $this->add('text', "{$fieldName}_value", NULL);
912 $this->assign('filters', $filters);
915 function addOptions() {
916 if (!empty($this->_options
)) {
917 // FIXME: For now lets build all elements as checkboxes.
918 // Once we clear with the format we can build elements based on type
921 foreach ($this->_options
as $fieldName => $field) {
922 if ($field['type'] == 'select') {
923 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
925 else if ($field['type'] == 'checkbox') {
926 $options[$field['title']] = $fieldName;
927 $this->addCheckBox($fieldName, NULL,
929 NULL, NULL, NULL, $this->_fourColumnAttribute
934 $this->assign('otherOptions', $this->_options
);
937 function addChartOptions() {
938 if (!empty($this->_charts
)) {
939 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
940 $this->assign('charts', $this->_charts
);
941 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
945 function addGroupBys() {
946 $options = $freqElements = array();
948 foreach ($this->_columns
as $tableName => $table) {
949 if (array_key_exists('group_bys', $table)) {
950 foreach ($table['group_bys'] as $fieldName => $field) {
951 if (!empty($field)) {
952 $options[$field['title']] = $fieldName;
953 if (CRM_Utils_Array
::value('frequency', $field)) {
954 $freqElements[$field['title']] = $fieldName;
960 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
961 NULL, NULL, NULL, $this->_fourColumnAttribute
963 $this->assign('groupByElements', $options);
965 foreach ($freqElements as $name) {
966 $this->addElement('select', "group_bys_freq[$name]",
967 ts('Frequency'), $this->_groupByDateFreq
972 function addOrderBys() {
974 foreach ($this->_columns
as $tableName => $table) {
976 // Report developer may define any column to order by; include these as order-by options
977 if (array_key_exists('order_bys', $table)) {
978 foreach ($table['order_bys'] as $fieldName => $field) {
979 if (!empty($field)) {
980 $options[$fieldName] = $field['title'];
985 /* Add searchable custom fields as order-by options, if so requested
986 * (These are already indexed, so allowing to order on them is cheap.)
990 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
991 foreach ($table['fields'] as $fieldName => $field) {
992 if (!CRM_Utils_Array
::value('no_display', $field)) {
993 $options[$fieldName] = $field['title'];
1001 $this->assign('orderByOptions', $options);
1003 if (!empty($options)) {
1005 '-' => ' - none - ') +
$options;
1006 for ($i = 1; $i <= 5; $i++
) {
1007 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1008 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1009 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1014 function buildInstanceAndButtons() {
1015 CRM_Report_Form_Instance
::buildForm($this);
1017 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1019 $this->addElement('submit', $this->_instanceButtonName
, $label);
1020 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1021 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1024 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1026 if ($this->_instanceForm
) {
1027 $this->assign('instanceForm', TRUE);
1030 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1031 $this->addElement('submit', $this->_printButtonName
, $label);
1033 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1034 $this->addElement('submit', $this->_pdfButtonName
, $label);
1036 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1038 if ($this->_csvSupported
) {
1039 $this->addElement('submit', $this->_csvButtonName
, $label);
1042 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1043 $this->addElement('select', 'groups', ts('Group'),
1044 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
1046 $this->assign('group', TRUE);
1049 $label = ts('Add these Contacts to Group');
1050 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1052 $this->addChartOptions();
1053 $this->addButtons(array(
1056 'name' => ts('Preview Report'),
1057 'isDefault' => TRUE,
1063 function buildQuickForm() {
1064 $this->addColumns();
1066 $this->addFilters();
1068 $this->addOptions();
1070 $this->addGroupBys();
1072 $this->addOrderBys();
1074 $this->buildInstanceAndButtons();
1076 //add form rule for report
1077 if (is_callable(array(
1078 $this, 'formRule'))) {
1079 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1083 // a formrule function to ensure that fields selected in group_by
1084 // (if any) should only be the ones present in display/select fields criteria;
1085 // note: works if and only if any custom field selected in group_by.
1086 function customDataFormRule($fields, $ignoreFields = array( )) {
1088 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1089 foreach ($this->_columns
as $tableName => $table) {
1090 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1091 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1092 if (array_key_exists($fieldName, $fields['group_bys']) &&
1093 !array_key_exists($fieldName, $fields['fields'])
1095 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1097 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1098 foreach ($fields['fields'] as $fld => $val) {
1099 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1100 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1111 // Note: $fieldName param allows inheriting class to build operationPairs
1112 // specific to a field.
1113 function getOperationPair($type = "string", $fieldName = NULL) {
1114 // FIXME: At some point we should move these key-val pairs
1115 // to option_group and option_value table.
1117 case CRM_Report_FORM
::OP_INT
:
1118 case CRM_Report_FORM
::OP_FLOAT
:
1120 'lte' => ts('Is less than or equal to'),
1121 'gte' => ts('Is greater than or equal to'),
1122 'bw' => ts('Is between'),
1123 'eq' => ts('Is equal to'),
1124 'lt' => ts('Is less than'),
1125 'gt' => ts('Is greater than'),
1126 'neq' => ts('Is not equal to'),
1127 'nbw' => ts('Is not between'),
1128 'nll' => ts('Is empty (Null)'),
1129 'nnll' => ts('Is not empty (Null)'),
1133 case CRM_Report_FORM
::OP_SELECT
:
1135 'eq' => ts('Is equal to'),
1138 case CRM_Report_FORM
::OP_MONTH
:
1139 case CRM_Report_FORM
::OP_MULTISELECT
:
1141 'in' => ts('Is one of'),
1142 'notin' => ts('Is not one of'),
1146 case CRM_Report_FORM
::OP_DATE
:
1148 'nll' => ts('Is empty (Null)'),
1149 'nnll' => ts('Is not empty (Null)'),
1153 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1154 // use this operator for the values, concatenated with separator. For e.g if
1155 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1157 'mhas' => ts('Is one of'),
1163 'has' => ts('Contains'),
1164 'sw' => ts('Starts with'),
1165 'ew' => ts('Ends with'),
1166 'nhas' => ts('Does not contain'),
1167 'eq' => ts('Is equal to'),
1168 'neq' => ts('Is not equal to'),
1169 'nll' => ts('Is empty (Null)'),
1170 'nnll' => ts('Is not empty (Null)'),
1175 function buildTagFilter() {
1176 $contactTags = CRM_Core_BAO_Tag
::getTags();
1177 if (!empty($contactTags)) {
1178 $this->_columns
['civicrm_tag'] = array(
1179 'dao' => 'CRM_Core_DAO_Tag',
1185 'title' => ts('Tag'),
1187 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1188 'options' => $contactTags,
1196 * Adds group filters to _columns (called from _Constuct
1198 function buildGroupFilter() {
1199 $this->_columns
['civicrm_group']['filters'] = array(
1202 'name' => 'group_id',
1203 'title' => ts('Group'),
1204 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1206 'options' => CRM_Core_PseudoConstant
::group(),
1209 if (empty($this->_columns
['civicrm_group']['dao'])) {
1210 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1212 if (empty($this->_columns
['civicrm_group']['alias'])) {
1213 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1217 function getSQLOperator($operator = "like") {
1218 switch ($operator) {
1251 return 'IS NOT NULL';
1259 function whereClause(&$field, $op,
1263 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1269 if (($min !== NULL && strlen($min) > 0) ||
1270 ($max !== NULL && strlen($max) > 0)
1272 $min = CRM_Utils_Type
::escape($min, $type);
1273 $max = CRM_Utils_Type
::escape($max, $type);
1277 $clauses[] = "( {$field['dbAlias']} >= $min )";
1280 $clauses[] = "( {$field['dbAlias']} < $min )";
1285 $clauses[] = "( {$field['dbAlias']} <= $max )";
1288 $clauses[] = "( {$field['dbAlias']} > $max )";
1292 if (!empty($clauses)) {
1294 $clause = implode(' AND ', $clauses);
1297 $clause = implode(' OR ', $clauses);
1305 if ($value !== NULL && strlen($value) > 0) {
1306 $value = CRM_Utils_Type
::escape($value, $type);
1307 if (strpos($value, '%') === FALSE) {
1308 $value = "'%{$value}%'";
1311 $value = "'{$value}'";
1313 $sqlOP = $this->getSQLOperator($op);
1314 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1320 if ($value !== NULL && is_array($value) && count($value) > 0) {
1321 $sqlOP = $this->getSQLOperator($op);
1322 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1323 //cycle through selections and esacape values
1324 foreach ($value as $key => $selection) {
1325 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1327 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1330 // for numerical values
1331 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1333 if ($op == 'notin') {
1334 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1337 $clause = "( " . $clause . " )";
1343 // mhas == multiple has
1344 if ($value !== NULL && count($value) > 0) {
1345 $sqlOP = $this->getSQLOperator($op);
1346 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1352 if ($value !== NULL && strlen($value) > 0) {
1353 $value = CRM_Utils_Type
::escape($value, $type);
1354 if (strpos($value, '%') === FALSE) {
1356 $value = "'{$value}%'";
1359 $value = "'%{$value}'";
1363 $value = "'{$value}'";
1365 $sqlOP = $this->getSQLOperator($op);
1366 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1372 $sqlOP = $this->getSQLOperator($op);
1373 $clause = "( {$field['dbAlias']} $sqlOP )";
1377 if ($value !== NULL && strlen($value) > 0) {
1378 if (isset($field['clause'])) {
1379 // FIXME: we not doing escape here. Better solution is to use two
1380 // different types - data-type and filter-type
1381 $clause = $field['clause'];
1384 $value = CRM_Utils_Type
::escape($value, $type);
1385 $sqlOP = $this->getSQLOperator($op);
1386 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1387 $value = "'{$value}'";
1389 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1395 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1396 $clause = $this->whereGroupClause($field, $value, $op);
1398 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1399 // not using left join in query because if any contact
1400 // belongs to more than one tag, results duplicate
1402 $clause = $this->whereTagClause($field, $value, $op);
1408 function dateClause($fieldName,
1409 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1412 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1413 $sqlOP = $this->getSQLOperator($relative);
1414 return "( {$fieldName} {$sqlOP} )";
1417 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1420 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1421 $clauses[] = "( {$fieldName} >= $from )";
1425 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1426 $clauses[] = "( {$fieldName} <= {$to} )";
1429 if (!empty($clauses)) {
1430 return implode(' AND ', $clauses);
1436 * @todo - could not find any instances where this is called
1437 * @param unknown_type $relative
1438 * @param String $from
1439 * @param String_type $to
1440 * @return string|NULL
1442 function dateDisplay($relative, $from, $to) {
1443 list($from, $to) = $this->getFromTo($relative, $from, $to);
1446 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1449 $clauses[] = 'Past';
1453 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1456 $clauses[] = 'Today';
1459 if (!empty($clauses)) {
1460 return implode(' - ', $clauses);
1466 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1467 if (empty($totime)) {
1470 //FIX ME not working for relative
1472 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1473 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1474 $from = substr($dateRange['from'], 0, 8);
1475 //Take only Date Part, Sometime Time part is also present in 'to'
1476 $to = substr($dateRange['to'], 0, 8);
1478 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1479 $to = CRM_Utils_Date
::processDate($to, $totime);
1480 return array($from, $to);
1483 function alterDisplay(&$rows) {
1484 // custom code to alter rows
1487 function alterCustomDataDisplay(&$rows) {
1488 // custom code to alter rows having custom values
1489 if (empty($this->_customGroupExtends
)) {
1493 $customFieldIds = array();
1494 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1495 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1496 $customFieldIds[$fieldAlias] = $fieldId;
1499 if (empty($customFieldIds)) {
1503 $customFields = $fieldValueMap = array();
1504 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1506 // skip for type date and ContactReference since date format is already handled
1508 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1509 FROM civicrm_custom_field cf
1510 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1511 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1512 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1513 cg.is_active = 1 AND
1514 cf.is_active = 1 AND
1515 cf.is_searchable = 1 AND
1516 cf.data_type NOT IN ('ContactReference', 'Date') AND
1517 cf.id IN (" . implode(",", $customFieldIds) . ")";
1519 $dao = CRM_Core_DAO
::executeQuery($query);
1520 while ($dao->fetch()) {
1521 foreach ($customFieldCols as $key) {
1522 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1524 if ($dao->option_group_id
) {
1525 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1530 $entryFound = FALSE;
1531 foreach ($rows as $rowNum => $row) {
1532 foreach ($row as $tableCol => $val) {
1533 if (array_key_exists($tableCol, $customFields)) {
1534 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1539 // skip looking further in rows, if first row itself doesn't
1540 // have the column we need
1547 function formatCustomValues($value, $customField, $fieldValueMap) {
1548 if (CRM_Utils_System
::isNull($value)) {
1552 $htmlType = $customField['html_type'];
1554 switch ($customField['data_type']) {
1556 if ($value == '1') {
1557 $retValue = ts('Yes');
1560 $retValue = ts('No');
1565 $retValue = CRM_Utils_System
::formatWikiURL($value);
1577 if ($htmlType == 'Text') {
1578 $retValue = (float)$value;
1582 if ($htmlType == 'Text') {
1592 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1597 if (in_array($htmlType, array(
1598 'Text', 'TextArea'))) {
1602 case 'StateProvince':
1605 switch ($htmlType) {
1606 case 'Multi-Select Country':
1607 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1608 $customData = array();
1609 foreach ($value as $val) {
1611 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1614 $retValue = implode(', ', $customData);
1617 case 'Select Country':
1618 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1621 case 'Select State/Province':
1622 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1625 case 'Multi-Select State/Province':
1626 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1627 $customData = array();
1628 foreach ($value as $val) {
1630 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1633 $retValue = implode(', ', $customData);
1638 case 'Autocomplete-Select':
1639 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1643 case 'AdvMulti-Select':
1644 case 'Multi-Select':
1645 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1646 $customData = array();
1647 foreach ($value as $val) {
1649 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1652 $retValue = implode(', ', $customData);
1667 function removeDuplicates(&$rows) {
1668 if (empty($this->_noRepeats
)) {
1671 $checkList = array();
1673 foreach ($rows as $key => $list) {
1674 foreach ($list as $colName => $colVal) {
1675 if (array_key_exists($colName, $checkList) &&
1676 $checkList[$colName] == $colVal) {
1677 $rows[$key][$colName] = "";
1679 if (in_array($colName, $this->_noRepeats
)) {
1680 $checkList[$colName] = $colVal;
1686 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1687 foreach ($row as $colName => $colVal) {
1688 if (in_array($colName, $fields)) {
1689 $row[$colName] = $row[$colName];
1691 elseif (isset($this->_columnHeaders
[$colName])) {
1693 $row[$colName] = "Subtotal";
1697 unset($row[$colName]);
1703 function grandTotal(&$rows) {
1704 if (!$this->_rollup ||
($this->_rollup
== '') ||
1705 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1709 $lastRow = array_pop($rows);
1711 foreach ($this->_columnHeaders
as $fld => $val) {
1712 if (!in_array($fld, $this->_statFields
)) {
1713 if (!$this->_grandFlag
) {
1714 $lastRow[$fld] = "Grand Total";
1715 $this->_grandFlag
= TRUE;
1718 $lastRow[$fld] = "";
1723 $this->assign('grandStat', $lastRow);
1727 function formatDisplay(&$rows, $pager = TRUE) {
1728 // set pager based on if any limit was applied in the query.
1733 // allow building charts if any
1734 if (!empty($this->_params
['charts']) && !empty($rows)) {
1735 $this->buildChart($rows);
1736 $this->assign('chartEnabled', TRUE);
1737 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1738 $this->assign('chartId', $this->_chartId
);
1741 // unset columns not to be displayed.
1742 foreach ($this->_columnHeaders
as $key => $value) {
1743 if (CRM_Utils_Array
::value('no_display', $value)) {
1744 unset($this->_columnHeaders
[$key]);
1748 // unset columns not to be displayed.
1749 if (!empty($rows)) {
1750 foreach ($this->_noDisplay
as $noDisplayField) {
1751 foreach ($rows as $rowNum => $row) {
1752 unset($this->_columnHeaders
[$noDisplayField]);
1757 // build array of section totals
1758 $this->sectionTotals();
1760 // process grand-total row
1761 $this->grandTotal($rows);
1763 // use this method for formatting rows for display purpose.
1764 $this->alterDisplay($rows);
1765 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1767 // use this method for formatting custom rows for display purpose.
1768 $this->alterCustomDataDisplay($rows);
1771 function buildChart(&$rows) {
1772 // override this method for building charts.
1775 // select() method below has been added recently (v3.3), and many of the report templates might
1776 // still be having their own select() method. We should fix them as and when encountered and move
1777 // towards generalizing the select() method below.
1779 $select = $this->_selectAliases
= array();
1781 foreach ($this->_columns
as $tableName => $table) {
1782 if (array_key_exists('fields', $table)) {
1783 foreach ($table['fields'] as $fieldName => $field) {
1784 if ($tableName == 'civicrm_address') {
1785 $this->_addressField
= TRUE;
1787 if ($tableName == 'civicrm_email') {
1788 $this->_emailField
= TRUE;
1790 if ($tableName == 'civicrm_phone') {
1791 $this->_phoneField
= TRUE;
1794 if (CRM_Utils_Array
::value('required', $field) ||
1795 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1798 // 1. In many cases we want select clause to be built in slightly different way
1799 // for a particular field of a particular type.
1800 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1802 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1803 if ($selectClause) {
1804 $select[] = $selectClause;
1808 // include statistics columns only if set
1809 if (CRM_Utils_Array
::value('statistics', $field)) {
1810 foreach ($field['statistics'] as $stat => $label) {
1811 $alias = "{$tableName}_{$fieldName}_{$stat}";
1812 switch (strtolower($stat)) {
1815 $select[] = "$stat({$field['dbAlias']}) as $alias";
1816 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1817 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1818 $this->_statFields
[$label] = $alias;
1819 $this->_selectAliases
[] = $alias;
1823 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1824 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1825 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1826 $this->_statFields
[$label] = $alias;
1827 $this->_selectAliases
[] = $alias;
1830 case 'count_distinct':
1831 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1832 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1833 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1834 $this->_statFields
[$label] = $alias;
1835 $this->_selectAliases
[] = $alias;
1839 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1840 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1841 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1842 $this->_statFields
[$label] = $alias;
1843 $this->_selectAliases
[] = $alias;
1849 $alias = "{$tableName}_{$fieldName}";
1850 $select[] = "{$field['dbAlias']} as $alias";
1851 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1852 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1853 $this->_selectAliases
[] = $alias;
1859 // select for group bys
1860 if (array_key_exists('group_bys', $table)) {
1861 foreach ($table['group_bys'] as $fieldName => $field) {
1863 if ($tableName == 'civicrm_address') {
1864 $this->_addressField
= TRUE;
1866 if ($tableName == 'civicrm_email') {
1867 $this->_emailField
= TRUE;
1869 if ($tableName == 'civicrm_phone') {
1870 $this->_phoneField
= TRUE;
1872 // 1. In many cases we want select clause to be built in slightly different way
1873 // for a particular field of a particular type.
1874 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1876 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1877 if ($selectClause) {
1878 $select[] = $selectClause;
1882 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1883 && !empty($this->_params
['group_bys_freq'])) {
1884 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1886 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1887 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1888 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1889 $field['title'] = 'Week';
1893 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1894 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1895 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1896 $field['title'] = 'Year';
1900 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1901 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1902 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1903 $field['title'] = 'Month';
1907 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1908 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1909 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1910 $field['title'] = 'Quarter';
1913 // for graphs and charts -
1914 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1915 $this->_interval
= $field['title'];
1916 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1917 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1918 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1920 // just to make sure these values are transfered to rows.
1921 // since we 'll need them for calculation purpose,
1922 // e.g making subtotals look nicer or graphs
1923 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1924 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1931 $this->_selectClauses
= $select;
1932 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1935 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1940 $this->storeWhereHavingClauseArray();
1942 if (empty($this->_whereClauses
)) {
1943 $this->_where
= "WHERE ( 1 ) ";
1944 $this->_having
= "";
1947 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1950 if ($this->_aclWhere
) {
1951 $this->_where
.= " AND {$this->_aclWhere} ";
1954 if (!empty($this->_havingClauses
)) {
1955 // use this clause to construct group by clause.
1956 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1961 * Store Where clauses into an array - breaking out this step makes
1962 * over-riding more flexible as the clauses can be used in constructing a
1963 * temp table that may not be part of the final where clause or added
1964 * in other functions
1966 function storeWhereHavingClauseArray(){
1967 foreach ($this->_columns
as $tableName => $table) {
1968 if (array_key_exists('filters', $table)) {
1969 foreach ($table['filters'] as $fieldName => $field) {
1970 // respect pseudofield to filter spec so fields can be marked as
1971 // not to be handled here
1972 if(!empty($field['pseudofield'])){
1976 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1977 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1978 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1979 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1980 if (is_array($value) && !empty($value)) {
1981 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1985 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1986 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1987 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1988 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1989 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1990 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1994 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1996 $clause = $this->whereClause($field,
1998 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1999 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2000 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2005 if (!empty($clause)) {
2006 if (CRM_Utils_Array
::value('having', $field)) {
2007 $this->_havingClauses
[] = $clause;
2010 $this->_whereClauses
[] = $clause;
2018 function processReportMode() {
2019 $buttonName = $this->controller
->getButtonName();
2021 $output = CRM_Utils_Request
::retrieve(
2024 CRM_Core_DAO
::$_nullObject
2028 CRM_Utils_Request
::retrieve(
2031 CRM_Core_DAO
::$_nullObject
2034 $this->_absoluteUrl
= FALSE;
2036 $this->assign('printOnly', FALSE);
2038 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2039 $this->assign('printOnly', TRUE);
2041 $this->assign('outputMode', 'print');
2042 $this->_outputMode
= 'print';
2043 if ($this->_sendmail
) {
2044 $this->_absoluteUrl
= TRUE;
2047 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2048 $this->assign('printOnly', TRUE);
2050 $this->assign('outputMode', 'pdf');
2051 $this->_outputMode
= 'pdf';
2052 $this->_absoluteUrl
= TRUE;
2054 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2055 $this->assign('printOnly', TRUE);
2057 $this->assign('outputMode', 'csv');
2058 $this->_outputMode
= 'csv';
2059 $this->_absoluteUrl
= TRUE;
2061 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2062 $this->assign('outputMode', 'group');
2063 $this->_outputMode
= 'group';
2065 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2066 $this->assign('outputMode', 'create_report');
2067 $this->_outputMode
= 'create_report';
2070 $this->assign('outputMode', 'html');
2071 $this->_outputMode
= 'html';
2074 // Get today's date to include in printed reports
2076 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2077 $this->assign('reportDate', $reportDate);
2081 function beginPostProcess() {
2082 $this->setParams($this->controller
->exportValues($this->_name
));
2084 if (empty($this->_params
) &&
2087 $this->setParams($this->_formValues
);
2090 // hack to fix params when submitted from dashboard, CRM-8532
2091 // fields array is missing because form building etc is skipped
2092 // in dashboard mode for report
2093 //@todo - this could be done in the dashboard no we have a setter
2094 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2095 $this->setParams($this->_formValues
);
2098 $this->_formValues
= $this->_params
;
2099 if (CRM_Core_Permission
::check('administer Reports') &&
2100 isset($this->_id
) &&
2101 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2102 $this->_chartButtonName
== $this->controller
->getButtonName()
2105 $this->assign('updateReportButton', TRUE);
2107 $this->processReportMode();
2108 $this->beginPostProcessCommon();
2112 * beginPostProcess function run in both report mode and non-report mode (api)
2114 function beginPostProcessCommon() {
2118 function buildQuery($applyLimit = TRUE) {
2121 $this->customDataFrom();
2126 // order_by columns not selected for display need to be included in SELECT
2127 $unselectedSectionColumns = $this->unselectedSectionColumns();
2128 foreach ($unselectedSectionColumns as $alias => $section) {
2129 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2132 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2135 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2137 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2141 function groupBy() {
2142 $groupBys = array();
2143 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2144 is_array($this->_params
['group_bys']) &&
2145 !empty($this->_params
['group_bys'])
2147 foreach ($this->_columns
as $tableName => $table) {
2148 if (array_key_exists('group_bys', $table)) {
2149 foreach ($table['group_bys'] as $fieldName => $field) {
2150 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2151 $groupBys[] = $field['dbAlias'];
2158 if (!empty($groupBys)) {
2159 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2163 function orderBy() {
2164 $this->_orderBy
= "";
2165 $this->_sections
= array();
2166 $this->storeOrderByArray();
2167 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2168 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2170 $this->assign('sections', $this->_sections
);
2174 * In some cases other functions want to know which fields are selected for ordering by
2175 * Separating this into a separate function allows it to be called separately from constructing
2176 * the order by clause
2178 function storeOrderByArray() {
2179 $orderBys = array();
2181 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2182 is_array($this->_params
['order_bys']) &&
2183 !empty($this->_params
['order_bys'])
2186 // Proces order_bys in user-specified order
2187 foreach ($this->_params
['order_bys'] as $orderBy) {
2188 $orderByField = array();
2189 foreach ($this->_columns
as $tableName => $table) {
2190 if (array_key_exists('order_bys', $table)) {
2191 // For DAO columns defined in $this->_columns
2192 $fields = $table['order_bys'];
2194 elseif (array_key_exists('extends', $table)) {
2195 // For custom fields referenced in $this->_customGroupExtends
2196 $fields = $table['fields'];
2198 if (!empty($fields) && is_array($fields)) {
2199 foreach ($fields as $fieldName => $field) {
2200 if ($fieldName == $orderBy['column']) {
2201 $orderByField = array_merge($field, $orderBy);
2202 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2209 if (!empty($orderByField)) {
2210 $this->_orderByFields
[] = $orderByField;
2211 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2213 // Record any section headers for assignment to the template
2214 if (CRM_Utils_Array
::value('section', $orderBy)) {
2215 $this->_sections
[$orderByField['tplField']] = $orderByField;
2221 $this->_orderByArray
= $orderBys;
2223 $this->assign('sections', $this->_sections
);
2226 function unselectedSectionColumns() {
2227 $selectColumns = array();
2228 foreach ($this->_columns
as $tableName => $table) {
2229 if (array_key_exists('fields', $table)) {
2230 foreach ($table['fields'] as $fieldName => $field) {
2231 if (CRM_Utils_Array
::value('required', $field) ||
2232 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2235 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2241 if (is_array($this->_sections
)) {
2242 return array_diff_key($this->_sections
, $selectColumns);
2249 function buildRows($sql, &$rows) {
2250 $dao = CRM_Core_DAO
::executeQuery($sql);
2251 if (!is_array($rows)) {
2255 // use this method to modify $this->_columnHeaders
2256 $this->modifyColumnHeaders();
2258 $unselectedSectionColumns = $this->unselectedSectionColumns();
2260 while ($dao->fetch()) {
2262 foreach ($this->_columnHeaders
as $key => $value) {
2263 if (property_exists($dao, $key)) {
2264 $row[$key] = $dao->$key;
2268 // section headers not selected for display need to be added to row
2269 foreach ($unselectedSectionColumns as $key => $values) {
2270 if (property_exists($dao, $key)) {
2271 $row[$key] = $dao->$key;
2280 * When "order by" fields are marked as sections, this assigns to the template
2281 * an array of total counts for each section. This data is used by the Smarty
2282 * plugin {sectionTotal}
2284 function sectionTotals() {
2286 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2287 if (empty($this->_selectAliases
)) {
2291 if (!empty($this->_sections
)) {
2292 // build the query with no LIMIT clause
2293 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2294 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2296 // pull section aliases out of $this->_sections
2297 $sectionAliases = array_keys($this->_sections
);
2300 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2301 $ifnulls[] = "ifnull($alias, '') as $alias";
2304 /* Group (un-limited) report by all aliases and get counts. This might
2305 * be done more efficiently when the contents of $sql are known, ie. by
2306 * overriding this method in the report class.
2310 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2312 // initialize array of total counts
2314 $dao = CRM_Core_DAO
::executeQuery($query);
2315 while ($dao->fetch()) {
2317 // let $this->_alterDisplay translate any integer ids to human-readable values.
2318 $rows[0] = $dao->toArray();
2319 $this->alterDisplay($rows);
2322 // add totals for all permutations of section values
2325 $aliasCount = count($sectionAliases);
2326 foreach ($sectionAliases as $alias) {
2327 $values[] = $row[$alias];
2328 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2329 if ($i == $aliasCount) {
2330 // the last alias is the lowest-level section header; use count as-is
2331 $totals[$key] = $dao->ct
;
2334 // other aliases are higher level; roll count into their total
2335 $totals[$key] +
= $dao->ct
;
2339 $this->assign('sectionTotals', $totals);
2343 function modifyColumnHeaders() {
2344 // use this method to modify $this->_columnHeaders
2347 function doTemplateAssignment(&$rows) {
2348 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2349 $this->assign_by_ref('rows', $rows);
2350 $this->assign('statistics', $this->statistics($rows));
2353 // override this method to build your own statistics
2354 function statistics(&$rows) {
2355 $statistics = array();
2357 $count = count($rows);
2359 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2363 $this->countStat($statistics, $count);
2365 $this->groupByStat($statistics);
2367 $this->filterStat($statistics);
2372 function countStat(&$statistics, $count) {
2373 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2377 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2378 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2379 'value' => $this->_rowsFound
,
2384 function groupByStat(&$statistics) {
2385 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2386 is_array($this->_params
['group_bys']) &&
2387 !empty($this->_params
['group_bys'])
2389 foreach ($this->_columns
as $tableName => $table) {
2390 if (array_key_exists('group_bys', $table)) {
2391 foreach ($table['group_bys'] as $fieldName => $field) {
2392 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2393 $combinations[] = $field['title'];
2398 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2399 'value' => implode(' & ', $combinations),
2404 function filterStat(&$statistics) {
2405 foreach ($this->_columns
as $tableName => $table) {
2406 if (array_key_exists('filters', $table)) {
2407 foreach ($table['filters'] as $fieldName => $field) {
2408 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2411 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2412 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2413 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2414 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2415 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2417 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2418 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2420 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2421 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2424 $statistics['filters'][] = array(
2425 'title' => $field['title'],
2426 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2429 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2430 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2432 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2433 $statistics['filters'][] = array(
2434 'title' => $field['title'],
2435 'value' => $pair[$rel],
2440 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2443 $pair = $this->getOperationPair(
2444 CRM_Utils_Array
::value('operatorType', $field),
2447 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2448 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2449 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2450 if (in_array($op, array(
2451 'bw', 'nbw')) && ($min ||
$max)) {
2452 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2454 elseif ($op == 'nll' ||
$op == 'nnll') {
2455 $value = $pair[$op];
2457 elseif (is_array($val) && (!empty($val))) {
2458 $options = CRM_Utils_Array
::value('options', $field, array());
2459 foreach ($val as $key => $valIds) {
2460 if (isset($options[$valIds])) {
2461 $val[$key] = $options[$valIds];
2464 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2465 $val = implode(', ', $val);
2466 $value = "{$pair[$op]} " . $val;
2468 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2469 is_array($field['options']) && !empty($field['options'])
2471 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2474 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2478 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2488 function endPostProcess(&$rows = NULL) {
2489 if ( $this->_storeResultSet
) {
2490 $this->_resultSet
= $rows;
2493 if ($this->_outputMode
== 'print' ||
2494 $this->_outputMode
== 'pdf' ||
2498 $content = $this->compileContent();
2499 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2503 if ($this->_sendmail
) {
2504 $config = CRM_Core_Config
::singleton();
2505 $attachments = array();
2507 if ($this->_outputMode
== 'csv') {
2508 $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'];
2510 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2511 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2512 file_put_contents($csvFullFilename, $csvContent);
2513 $attachments[] = array(
2514 'fullPath' => $csvFullFilename,
2515 'mime_type' => 'text/csv',
2516 'cleanName' => 'CiviReport.csv',
2519 if ($this->_outputMode
== 'pdf') {
2520 // generate PDF content
2521 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2522 file_put_contents($pdfFullFilename,
2523 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2524 TRUE, array('orientation' => 'landscape')
2527 // generate Email Content
2528 $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'];
2530 $attachments[] = array(
2531 'fullPath' => $pdfFullFilename,
2532 'mime_type' => 'application/pdf',
2533 'cleanName' => 'CiviReport.pdf',
2537 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2538 $this->_outputMode
, $attachments
2540 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2543 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2546 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2548 elseif ($this->_outputMode
== 'print') {
2552 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2553 $config = CRM_Core_Config
::singleton();
2554 //get chart image name
2555 $chartImg = $this->_chartId
. '.png';
2556 //get image url path
2557 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2558 $uploadUrl .= $chartImg;
2559 //get image doc path to overwrite
2560 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2562 $chart = imagecreatefrompng($uploadUrl);
2563 //convert it into formattd png
2564 header('Content-type: image/png');
2565 //overwrite with same image
2566 imagepng($chart, $uploadImg);
2568 imagedestroy($chart);
2570 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2572 CRM_Utils_System
::civiExit();
2574 elseif ($this->_outputMode
== 'csv') {
2575 CRM_Report_Utils_Report
::export2csv($this, $rows);
2577 elseif ($this->_outputMode
== 'group') {
2578 $group = $this->_params
['groups'];
2579 $this->add2group($group);
2581 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2582 CRM_Report_Form_Instance
::postProcess($this);
2584 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2585 $this->_outputMode
== 'create_report' ) {
2586 $this->_createNew
= TRUE;
2587 CRM_Report_Form_Instance
::postProcess($this);
2591 function storeResultSet() {
2592 $this->_storeResultSet
= TRUE;
2595 function getResultSet() {
2596 return $this->_resultSet
;
2600 * Get Template file name - use default form template if a specific one has not been set up for this report
2603 function getTemplateFileName(){
2604 $defaultTpl = parent
::getTemplateFileName();
2605 $template = CRM_Core_Smarty
::singleton();
2606 if (!$template->template_exists($defaultTpl)) {
2607 $defaultTpl = 'CRM/Report/Form.tpl';
2613 * Compile the report content
2615 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2617 function compileContent(){
2618 $templateFile = $this->getHookedTemplateFileName();
2619 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2623 function postProcess() {
2624 // get ready with post process params
2625 $this->beginPostProcess();
2628 $sql = $this->buildQuery();
2630 // build array of result based on column headers. This method also allows
2631 // modifying column headers before using it to build result set i.e $rows.
2633 $this->buildRows($sql, $rows);
2635 // format result set.
2636 $this->formatDisplay($rows);
2638 // assign variables to templates
2639 $this->doTemplateAssignment($rows);
2641 // do print / pdf / instance stuff if needed
2642 $this->endPostProcess($rows);
2645 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2646 // lets do the pager if in html mode
2647 $this->_limit
= NULL;
2648 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2649 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2651 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2653 if (!$pageId && !empty($_POST)) {
2654 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2655 $pageId = max((int)@$_POST['crmPID_B'], 1);
2657 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2658 $pageId = max((int)@$_POST['crmPID'], 1);
2660 unset($_POST['crmPID_B'], $_POST['crmPID']);
2663 $pageId = $pageId ?
$pageId : 1;
2664 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2665 $offset = ($pageId - 1) * $rowCount;
2667 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2668 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2670 $this->_limit
= " LIMIT $offset, $rowCount";
2671 return array($offset, $rowCount);
2675 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2676 if ($this->_limit
&& ($this->_limit
!= '')) {
2677 $sql = "SELECT FOUND_ROWS();";
2678 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2680 'total' => $this->_rowsFound
,
2681 'rowCount' => $rowCount,
2682 'status' => ts('Records') . ' %%StatusMessage%%',
2683 'buttonBottom' => 'PagerBottomButton',
2684 'buttonTop' => 'PagerTopButton',
2685 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2688 $pager = new CRM_Utils_Pager($params);
2689 $this->assign_by_ref('pager', $pager);
2693 function whereGroupClause($field, $value, $op) {
2695 $smartGroupQuery = "";
2697 $group = new CRM_Contact_DAO_Group();
2698 $group->is_active
= 1;
2700 $smartGroups = array();
2701 while ($group->fetch()) {
2702 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2703 $smartGroups[] = $group->id
;
2707 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2709 $smartGroupQuery = '';
2710 if (!empty($smartGroups)) {
2711 $smartGroups = implode(',', $smartGroups);
2712 $smartGroupQuery = " UNION DISTINCT
2713 SELECT DISTINCT smartgroup_contact.contact_id
2714 FROM civicrm_group_contact_cache smartgroup_contact
2715 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2718 $sqlOp = $this->getSQLOperator($op);
2719 if (!is_array($value)) {
2720 $value = array($value);
2722 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2724 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2725 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2726 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2727 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2728 {$smartGroupQuery} ) ";
2731 function whereTagClause($field, $value, $op) {
2732 // not using left join in query because if any contact
2733 // belongs to more than one tag, results duplicate
2735 $sqlOp = $this->getSQLOperator($op);
2736 if (!is_array($value)) {
2737 $value = array($value);
2739 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2741 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2742 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2743 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2744 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2747 function buildACLClause($tableAlias = 'contact_a') {
2748 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2751 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2752 if (empty($this->_customGroupExtends
)) {
2755 if (!is_array($this->_customGroupExtends
)) {
2756 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2758 $customGroupWhere = '';
2759 if (!empty($permCustomGroupIds)) {
2760 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2763 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2764 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2765 FROM civicrm_custom_group cg
2766 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2767 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2769 cg.is_active = 1 AND
2770 cf.is_active = 1 AND
2771 cf.is_searchable = 1
2772 ORDER BY cg.weight, cf.weight";
2773 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2776 while ($customDAO->fetch()) {
2777 if ($customDAO->table_name
!= $curTable) {
2778 $curTable = $customDAO->table_name
;
2779 $curFields = $curFilters = array();
2782 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2783 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2784 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2785 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2788 'fields', 'filters', 'group_bys') as $colKey) {
2789 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2790 $this->_columns
[$curTable][$colKey] = array();
2794 $fieldName = 'custom_' . $customDAO->cf_id
;
2797 // this makes aliasing work in favor
2798 $curFields[$fieldName] = array(
2799 'name' => $customDAO->column_name
,
2800 'title' => $customDAO->label
,
2801 'dataType' => $customDAO->data_type
,
2802 'htmlType' => $customDAO->html_type
,
2805 if ($this->_customGroupFilters
) {
2806 // this makes aliasing work in favor
2807 $curFilters[$fieldName] = array(
2808 'name' => $customDAO->column_name
,
2809 'title' => $customDAO->label
,
2810 'dataType' => $customDAO->data_type
,
2811 'htmlType' => $customDAO->html_type
,
2815 switch ($customDAO->data_type
) {
2818 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2819 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2820 // CRM-6946, show time part for datetime date fields
2821 if ($customDAO->time_format
) {
2822 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2827 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2828 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2832 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2836 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2837 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2841 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2842 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2846 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2847 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2851 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2853 if (!empty($customDAO->option_group_id
)) {
2854 if (in_array($customDAO->html_type
, array(
2855 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2856 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2859 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2861 if ($this->_customGroupFilters
) {
2862 $curFilters[$fieldName]['options'] = array();
2863 $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')));
2864 while ($ogDAO->fetch()) {
2865 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2871 case 'StateProvince':
2872 if (in_array($customDAO->html_type
, array(
2873 'Multi-Select State/Province'))) {
2874 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2877 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2879 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2883 if (in_array($customDAO->html_type
, array(
2884 'Multi-Select Country'))) {
2885 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2888 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2890 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2893 case 'ContactReference':
2894 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2895 $curFilters[$fieldName]['name'] = 'display_name';
2896 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2898 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2899 $curFields[$fieldName]['name'] = 'display_name';
2900 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2904 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2905 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2908 if (!array_key_exists('type', $curFields[$fieldName])) {
2909 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2913 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2915 if ($this->_customGroupFilters
) {
2916 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2918 if ($this->_customGroupGroupBy
) {
2919 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2924 function customDataFrom() {
2925 if (empty($this->_customGroupExtends
)) {
2928 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2930 foreach ($this->_columns
as $table => $prop) {
2931 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2932 $extendsTable = $mapper[$prop['extends']];
2934 // check field is in params
2935 if (!$this->isFieldSelected($prop)) {
2938 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
2940 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2942 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
2943 // handle for ContactReference
2944 if (array_key_exists('fields', $prop)) {
2945 foreach ($prop['fields'] as $fieldName => $field) {
2946 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2947 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2949 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2957 function isFieldSelected($prop) {
2962 if (!empty($this->_params
['fields'])) {
2963 foreach (array_keys($prop['fields']) as $fieldAlias) {
2964 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2965 if ($customFieldId) {
2966 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2970 //might be survey response field.
2971 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2972 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2980 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2981 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2982 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2988 if (!empty($this->_params
['order_bys'])) {
2989 foreach (array_keys($prop['fields']) as $fieldAlias) {
2990 foreach ($this->_params
['order_bys'] as $orderBy) {
2991 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2998 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2999 foreach ($prop['filters'] as $fieldAlias => $val) {
3001 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3002 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3003 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3004 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3010 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
3011 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3022 * Check for empty order_by configurations and remove them; also set
3023 * template to hide them.
3025 function preProcessOrderBy(&$formValues) {
3026 // Object to show/hide form elements
3027 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3029 $_showHide->addShow('optionField_1');
3031 // Cycle through order_by options; skip any empty ones, and hide them as well
3034 if (!empty($formValues['order_bys'])) {
3035 foreach ($formValues['order_bys'] as $order_by) {
3036 if ($order_by['column'] && $order_by['column'] != '-') {
3037 $_showHide->addShow('optionField_' . $n);
3038 $orderBys[$n] = $order_by;
3043 for ($i = $n; $i <= 5; $i++
) {
3045 $_showHide->addHide('optionField_' . $i);
3049 // overwrite order_by options with modified values
3050 if (!empty($orderBys)) {
3051 $formValues['order_bys'] = $orderBys;
3054 $formValues['order_bys'] = array(1 => array('column' => '-'));
3057 // assign show/hide data to template
3058 $_showHide->addToTemplate();
3062 * Does table name have columns in SELECT clause?
3064 * @param string $tableName Name of table (index of $this->_columns array)
3068 function isTableSelected($tableName) {
3069 return in_array($tableName, $this->selectedTables());
3073 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3074 * (building the array if it's unset)
3076 * @return Array $this->_selectedTables
3078 function selectedTables() {
3079 if (!$this->_selectedTables
) {
3080 $orderByColumns = array();
3081 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3082 foreach ($this->_params
['order_bys'] as $orderBy) {
3083 $orderByColumns[] = $orderBy['column'];
3087 foreach ($this->_columns
as $tableName => $table) {
3088 if (array_key_exists('fields', $table)) {
3089 foreach ($table['fields'] as $fieldName => $field) {
3090 if (CRM_Utils_Array
::value('required', $field) ||
3091 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3093 $this->_selectedTables
[] = $tableName;
3098 if (array_key_exists('order_bys', $table)) {
3099 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3100 if (in_array($orderByName, $orderByColumns)) {
3101 $this->_selectedTables
[] = $tableName;
3106 if (array_key_exists('filters', $table)) {
3107 foreach ($table['filters'] as $filterName => $filter) {
3108 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3109 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3110 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3112 $this->_selectedTables
[] = $tableName;
3119 return $this->_selectedTables
;
3123 * @deprecated - use getAddressColumns which is a more accurate description
3124 * and also accepts an array of options rather than a long list
3126 * function for adding address fields to construct function in reports
3127 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3128 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3129 * @return array address fields for construct clause
3131 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3132 'country_id' => TRUE)) {
3133 $addressFields = array(
3134 'civicrm_address' =>
3136 'dao' => 'CRM_Core_DAO_Address',
3140 array('title' => ts('Address Name'),
3141 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3144 array('title' => ts('Street Address'),
3145 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3147 'supplemental_address_1' =>
3148 array('title' => ts('Supplementary Address Field 1'),
3149 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3151 'supplemental_address_2' =>
3152 array('title' => ts('Supplementary Address Field 2'),
3153 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3157 'name' => 'street_number',
3158 'title' => ts('Street Number'),
3160 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3164 'name' => 'street_name',
3165 'title' => ts('Street Name'),
3167 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3171 'name' => 'street_unit',
3172 'title' => ts('Street Unit'),
3174 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3177 array('title' => ts('City'),
3178 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3181 array('title' => ts('Postal Code'),
3182 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3184 'postal_code_suffix' =>
3185 array('title' => ts('Postal Code Suffix'),
3186 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3189 array('title' => ts('County'),
3190 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3192 'state_province_id' =>
3193 array('title' => ts('State/Province'),
3194 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3197 array('title' => ts('Country'),
3198 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3201 'grouping' => 'location-fields',
3206 $addressFields['civicrm_address']['filters'] = array(
3207 'street_number' => array('title' => ts('Street Number'),
3209 'name' => 'street_number',
3211 'street_name' => array('title' => ts('Street Name'),
3212 'name' => 'street_name',
3213 'operator' => 'like',
3215 'postal_code' => array('title' => ts('Postal Code'),
3217 'name' => 'postal_code',
3219 'city' => array('title' => ts('City'),
3220 'operator' => 'like',
3223 'county_id' => array(
3224 'name' => 'county_id',
3225 'title' => ts('County'),
3226 'type' => CRM_Utils_Type
::T_INT
,
3228 CRM_Report_Form
::OP_MULTISELECT
,
3230 CRM_Core_PseudoConstant
::county(),
3232 'state_province_id' => array(
3233 'name' => 'state_province_id',
3234 'title' => ts('State/Province'),
3235 'type' => CRM_Utils_Type
::T_INT
,
3237 CRM_Report_Form
::OP_MULTISELECT
,
3239 CRM_Core_PseudoConstant
::stateProvince(),
3241 'country_id' => array(
3242 'name' => 'country_id',
3243 'title' => ts('Country'),
3244 'type' => CRM_Utils_Type
::T_INT
,
3246 CRM_Report_Form
::OP_MULTISELECT
,
3248 CRM_Core_PseudoConstant
::country(),
3254 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3255 'street_number' => array('title' => 'Odd / Even Street Number'),
3256 'street_address' => NULL,
3258 'postal_code' => NULL,
3263 $addressFields['civicrm_address']['group_bys'] = array(
3264 'street_address' => NULL,
3266 'postal_code' => NULL,
3267 'state_province_id' =>
3268 array('title' => ts('State/Province'),
3271 array('title' => ts('Country'),
3274 array('title' => ts('County'),
3278 return $addressFields;
3282 * Do AlterDisplay processing on Address Fields
3284 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3285 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3286 $entryFound = FALSE;
3288 if (array_key_exists('civicrm_address_country_id', $row)) {
3289 if ($value = $row['civicrm_address_country_id']) {
3290 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3291 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3292 "reset=1&force=1&{$criteriaQueryParams}&" .
3293 "country_id_op=in&country_id_value={$value}",
3294 $this->_absoluteUrl
, $this->_id
3296 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3297 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3304 if (array_key_exists('civicrm_address_county_id', $row)) {
3305 if ($value = $row['civicrm_address_county_id']) {
3306 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3307 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3308 "reset=1&force=1&{$criteriaQueryParams}&" .
3309 "county_id_op=in&county_id_value={$value}",
3310 $this->_absoluteUrl
, $this->_id
3312 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3313 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3319 // handle state province
3320 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3321 if ($value = $row['civicrm_address_state_province_id']) {
3322 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3324 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3325 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3326 $this->_absoluteUrl
, $this->_id
3328 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3329 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3340 * Adjusts dates passed in to YEAR() for fiscal year.
3342 function fiscalYearOffset($fieldName) {
3343 $config = CRM_Core_Config
::singleton();
3344 $fy = $config->fiscalYearStart
;
3345 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3346 return "YEAR( $fieldName )";
3348 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3352 * Add Address into From Table if required
3354 function addAddressFromClause() {
3355 // include address field if address column is to be included
3356 if ((isset($this->_addressField
) &&
3357 $this->_addressField
3359 $this->isTableSelected('civicrm_address')
3362 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3363 ON ({$this->_aliases['civicrm_contact']}.id =
3364 {$this->_aliases['civicrm_address']}.contact_id) AND
3365 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3370 * Add Phone into From Table if required
3372 function addPhoneFromClause() {
3373 // include address field if address column is to be included
3374 if ($this->isTableSelected('civicrm_phone')
3377 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3378 ON ({$this->_aliases['civicrm_contact']}.id =
3379 {$this->_aliases['civicrm_phone']}.contact_id) AND
3380 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3385 * Get phone columns to add to array
3386 * @param array $options
3387 * - prefix Prefix to add to table (in case of more than one instance of the table)
3388 * - prefix_label Label to give columns from this phone table instance
3389 * @return array phone columns definition
3391 function getPhoneColumns($options = array()){
3392 $defaultOptions = array(
3394 'prefix_label' => '',
3397 $options = array_merge($defaultOptions,$options);
3400 $options['prefix'] . 'civicrm_phone' => array(
3401 'dao' => 'CRM_Core_DAO_Phone',
3403 $options['prefix'] . 'phone' => array(
3404 'title' => ts($options['prefix_label'] . 'Phone'),
3414 * Get address columns to add to array
3415 * @param array $options
3416 * - prefix Prefix to add to table (in case of more than one instance of the table)
3417 * - prefix_label Label to give columns from this address table instance
3418 * @return array address columns definition
3420 function getAddressColumns($options = array()){
3421 $defaultOptions = array(
3423 'prefix_label' => '',
3427 'defaults' => array(
3430 $options = array_merge($defaultOptions,$options);
3431 return $this->addAddressFields(
3432 $options['group_by'],
3433 $options['order_by'],
3434 $options['filters'],
3435 $options['defaults']
3440 function add2group($groupID) {
3441 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3442 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3443 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3445 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3446 $dao = CRM_Core_DAO
::executeQuery($sql);
3448 $contact_ids = array();
3449 // Add resulting contacts to group
3450 while ($dao->fetch()) {
3451 if ($dao->addtogroup_contact_id
) {
3452 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3456 if ( !empty($contact_ids) ) {
3457 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3458 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3461 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3466 /* function used for showing charts on print screen */
3467 static function uploadChartImage() {
3468 // upload strictly for '.png' images
3469 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3470 if (preg_match('/\.png$/', $name)) {
3472 // POST data is usually string data, but we are passing a RAW .png
3473 // so PHP is a bit confused and $_POST is empty. But it has saved
3474 // the raw bits into $HTTP_RAW_POST_DATA
3476 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3478 // prepare the directory
3479 $config = CRM_Core_Config
::singleton();
3480 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3481 if (!file_exists($defaultPath)) {
3482 mkdir($defaultPath, 0777, TRUE);
3485 // full path to the saved image including filename
3486 $destination = $defaultPath . $name;
3489 $jfh = fopen($destination, 'w') or die("can't open file");
3490 fwrite($jfh, $httpRawPostData);
3492 CRM_Utils_System
::civiExit();