3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 CONST ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
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;
202 protected $_limit = NULL;
205 * This can be set to specify a limit to the number of rows
206 * Since it is currently envisaged as part of the api usage it is only being applied
207 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
208 * of the code (see limit() fn
211 protected $_limitValue = NULL;
214 * This can be set to specify row offset
215 * See notes on _limitValue
218 protected $_offsetValue = NULL;
219 protected $_sections = NULL;
220 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
221 protected $_absoluteUrl = FALSE;
224 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
228 protected $_storeResultSet = FALSE;
231 * When _storeResultSet Flag is set use this var to store result set in form of array
235 protected $_resultSet = array();
238 * To what frequency group-by a date column
242 protected $_groupByDateFreq = array(
244 'YEARWEEK' => 'Week',
245 'QUARTER' => 'Quarter',
250 * Variables to hold the acl inner join and where clause
252 protected $_aclFrom = NULL;
253 protected $_aclWhere = NULL;
256 * Array of DAO tables having columns included in SELECT or ORDER BY clause
260 protected $_selectedTables;
263 * outputmode e.g 'print', 'csv', 'pdf'
266 protected $_outputMode;
268 public $_having = NULL;
269 public $_select = NULL;
270 public $_selectClauses = array();
271 public $_columnHeaders = array();
272 public $_orderBy = NULL;
273 public $_orderByFields = array();
274 public $_orderByArray = array();
275 public $_groupBy = NULL;
276 public $_whereClauses = array();
277 public $_havingClauses = array();
280 * dashBoardRowCount Dashboard row count
283 public $_dashBoardRowCount;
286 * Is this being called without a form controller (ie. the report is being render outside the normal form
287 * - e.g the api is retrieving the rows
290 public $noController = FALSE;
293 * Variable to hold the currency alias
295 protected $_currencyColumn = NULL;
300 function __construct() {
301 parent
::__construct();
304 if ($this->_tagFilter
) {
305 $this->buildTagFilter();
307 if ($this->_exposeContactID
) {
308 if (array_key_exists('civicrm_contact', $this->_columns
)) {
309 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
311 'title' => 'Contact ID',
317 if ($this->_groupFilter
) {
318 $this->buildGroupFilter();
321 // Get all custom groups
322 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
324 // Get the custom groupIds for which the user has VIEW permission
325 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
326 // and addCustomDataToColumns() will allow access to all custom groups.
327 $permCustomGroupIds = array();
328 if (!CRM_Core_Permission
::check('access all custom data')) {
329 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
330 // do not allow custom data for reports if user doesn't have
331 // permission to access custom data.
332 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
333 $this->_customGroupExtends
= array();
337 // merge custom data columns to _columns list, if any
338 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
340 // add / modify display columns, filters ..etc
341 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
343 //assign currencyColumn variable to tpl
344 $this->assign('currencyColumn', $this->_currencyColumn
);
347 function preProcessCommon() {
349 CRM_Utils_Request
::retrieve(
352 CRM_Core_DAO
::$_nullObject
355 $this->_dashBoardRowCount
=
356 CRM_Utils_Request
::retrieve(
359 CRM_Core_DAO
::$_nullObject
362 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
364 $this->assign('section', $this->_section
);
365 CRM_Core_Region
::instance('page-header')->add(array(
366 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
368 if(!$this->noController
) {
369 $this->setID($this->get('instanceId'));
372 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
374 $this->setID( CRM_Report_Utils_Report
::getInstanceIDForPath());
378 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
379 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
380 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
384 $this->assign('instanceId', $this->_id
);
385 $params = array('id' => $this->_id
);
386 $this->_instanceValues
= array();
387 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
389 $this->_instanceValues
391 if (empty($this->_instanceValues
)) {
392 CRM_Core_Error
::fatal("Report could not be loaded.");
394 $this->_title
= $this->_instanceValues
['title'];
395 if (!empty($this->_instanceValues
['permission']) &&
396 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
397 CRM_Core_Permission
::check('administer Reports')
400 CRM_Utils_System
::permissionDenied();
401 CRM_Utils_System
::civiExit();
404 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
406 $this->_formValues
= unserialize($formValues);
409 $this->_formValues
= NULL;
412 // lets always do a force if reset is found in the url.
413 if (!empty($_REQUEST['reset'])) {
418 $this->assign('mode', 'instance');
420 elseif (!$this->noController
) {
421 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
422 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
423 if (($instanceCount > 0) && $optionValueID) {
424 $this->assign('instanceUrl',
425 CRM_Utils_System
::url('civicrm/report/list',
426 "reset=1&ovid=$optionValueID"
430 if ($optionValueID) {
431 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
435 $this->assign('mode', 'template');
438 // lets display the Report Settings section
439 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
441 // Do not display Report Settings section if administer Reports permission is absent OR
442 // if report instance is reserved and administer reserved reports absent
443 if (!CRM_Core_Permission
::check('administer Reports') ||
444 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
445 $this->_instanceForm
= FALSE;
448 $this->assign('criteriaForm', FALSE);
449 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
450 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
451 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
452 $this->assign('criteriaForm', TRUE);
453 $this->_criteriaForm
= TRUE;
457 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
458 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
459 $this->_printButtonName
= $this->getButtonName('submit', 'print');
460 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
461 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
462 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
463 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
466 function addBreadCrumb() {
470 'title' => ts('Report Templates'),
471 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
475 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
478 function preProcess() {
479 $this->preProcessCommon();
482 $this->addBreadCrumb();
485 foreach ($this->_columns
as $tableName => $table) {
487 if (!isset($table['alias'])) {
488 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
491 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
494 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
496 $daoOrBaoName = NULL;
497 // higher preference to bao object
498 if (array_key_exists('bao', $table)) {
499 $daoOrBaoName = $table['bao'];
500 $expFields = $daoOrBaoName::exportableFields( );
502 elseif (array_key_exists('dao', $table)){
503 $daoOrBaoName = $table['dao'];
504 $expFields = $daoOrBaoName::export( );
507 $expFields = array();
510 $doNotCopy = array('required');
512 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
513 foreach ($fieldGroups as $fieldGrp) {
514 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
515 foreach ($table[$fieldGrp] as $fieldName => $field) {
516 // $name is the field name used to reference the BAO/DAO export fields array
517 $name = isset($field['name']) ?
$field['name'] : $fieldName;
519 // Sometimes the field name key in the BAO/DAO export fields array is
520 // different from the actual database field name.
521 // Unset $field['name'] so that actual database field name can be obtained
522 // from the BAO/DAO export fields array.
523 unset($field['name']);
525 if (array_key_exists($name, $expFields)) {
526 foreach ($doNotCopy as $dnc) {
527 // unset the values we don't want to be copied.
528 unset($expFields[$name][$dnc]);
531 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
534 foreach ($expFields[$name] as $property => $val) {
535 if (!array_key_exists($property, $field)) {
536 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
543 if (!empty($field['no_repeat'])) {
544 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
546 if (!empty($field['no_display'])) {
547 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
550 // set alias = table-name, unless already set
551 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
552 $this->_columns
[$tableName]['alias'] : $tableName
554 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
556 // set name = fieldName, unless already set
557 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
558 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
561 // set dbAlias = alias.name, unless already set
562 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
563 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
566 // a few auto fills for filters
567 if ($fieldGrp == 'filters') {
568 // fill operator types
569 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
570 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
571 case CRM_Utils_Type
::T_MONEY
:
572 case CRM_Utils_Type
::T_FLOAT
:
573 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
575 case CRM_Utils_Type
::T_INT
:
576 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
578 case CRM_Utils_Type
::T_DATE
:
579 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
581 case CRM_Utils_Type
::T_BOOLEAN
:
582 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
583 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
584 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
585 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
590 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
591 // with multiple options operator-type is generally multi-select
592 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
593 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
595 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
606 // copy filters to a separate handy variable
607 if (array_key_exists('filters', $table)) {
608 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
611 if (array_key_exists('group_bys', $table)) {
612 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
615 if (array_key_exists('fields', $table)) {
616 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
621 $this->setDefaultValues(FALSE);
624 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
625 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
626 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
627 CRM_Report_Utils_Get
::processChart($this->_defaults
);
630 $this->_formValues
= $this->_defaults
;
631 $this->postProcess();
635 function setDefaultValues($freeze = TRUE) {
636 $freezeGroup = array();
638 // FIXME: generalizing form field naming conventions would reduce
639 // lots of lines below.
640 foreach ($this->_columns
as $tableName => $table) {
641 if (array_key_exists('fields', $table)) {
642 foreach ($table['fields'] as $fieldName => $field) {
643 if (empty($field['no_display'])) {
644 if (isset($field['required'])) {
646 $this->_defaults
['fields'][$fieldName] = 1;
649 // find element object, so that we could use quickform's freeze method
650 // for required elements
651 $obj = $this->getElementFromGroup("fields", $fieldName);
653 $freezeGroup[] = $obj;
657 elseif (isset($field['default'])) {
658 $this->_defaults
['fields'][$fieldName] = $field['default'];
664 if (array_key_exists('group_bys', $table)) {
665 foreach ($table['group_bys'] as $fieldName => $field) {
666 if (isset($field['default'])) {
667 if (!empty($field['frequency'])) {
668 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
670 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
674 if (array_key_exists('filters', $table)) {
675 foreach ($table['filters'] as $fieldName => $field) {
676 if (isset($field['default'])) {
677 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
678 if(is_array($field['default'])){
679 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
680 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
681 $this->_defaults
["{$fieldName}_relative"] = 0;
684 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
688 $this->_defaults
["{$fieldName}_value"] = $field['default'];
691 //assign default value as "in" for multiselect
692 //operator, To freeze the select element
693 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT
) {
694 $this->_defaults
["{$fieldName}_op"] = 'in';
696 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
) {
697 $this->_defaults
["{$fieldName}_op"] = 'mhas';
699 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
700 $this->_defaults
["{$fieldName}_op"] = $op;
706 array_key_exists('order_bys', $table) &&
707 is_array($table['order_bys'])
709 if (!array_key_exists('order_bys', $this->_defaults
)) {
710 $this->_defaults
['order_bys'] = array();
712 foreach ($table['order_bys'] as $fieldName => $field) {
713 if (!empty($field['default']) ||
!empty($field['default_order']) ||
714 CRM_Utils_Array
::value('default_is_section', $field) ||
!empty($field['default_weight'])) {
716 'column' => $fieldName,
717 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
718 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
721 if (!empty($field['default_weight'])) {
722 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
725 array_unshift($this->_defaults
['order_bys'], $order_by);
731 foreach ($this->_options
as $fieldName => $field) {
732 if (isset($field['default'])) {
733 $this->_defaults
['options'][$fieldName] = $field['default'];
738 if (!empty($this->_submitValues
)) {
739 $this->preProcessOrderBy($this->_submitValues
);
742 $this->preProcessOrderBy($this->_defaults
);
745 // lets finish freezing task here itself
746 if (!empty($freezeGroup)) {
747 foreach ($freezeGroup as $elem) {
752 if ($this->_formValues
) {
753 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
756 if ($this->_instanceValues
) {
757 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
760 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
762 return $this->_defaults
;
765 function getElementFromGroup($group, $grpFieldName) {
766 $eleObj = $this->getElement($group);
767 foreach ($eleObj->_elements
as $index => $obj) {
768 if ($grpFieldName == $obj->_attributes
['name']) {
776 * Setter for $_params
777 * @param array $params
779 function setParams($params) {
780 $this->_params
= $params;
787 function setID($instanceid) {
788 $this->_id
= $instanceid;
793 * @param boolean $force
795 function setForce($isForce) {
796 $this->_force
= $isForce;
800 * Setter for $_limitValue
801 * @param number $_limitValue
803 function setLimitValue($_limitValue) {
804 $this->_limitValue
= $_limitValue;
808 * Setter for $_offsetValue
809 * @param number $_offsetValue
811 function setOffsetValue($_offsetValue) {
812 $this->_offsetValue
= $_offsetValue;
816 * Getter for $_defaultValues
817 * @return array $_defaultValues
819 function getDefaultValues() {
820 return $this->_defaults
;
823 function addColumns() {
826 foreach ($this->_columns
as $tableName => $table) {
827 if (array_key_exists('fields', $table)) {
828 foreach ($table['fields'] as $fieldName => $field) {
830 if (empty($field['no_display'])) {
831 foreach ( array('table', 'field') as $var) {
832 if (!empty($
{$var}['grouping'])) {
833 if (!is_array($
{$var}['grouping'])) {
834 $tableName = $
{$var}['grouping'];
836 $tableName = array_keys($
{$var}['grouping']);
837 $tableName = $tableName[0];
838 $groupTitle = array_values($
{$var}['grouping']);
839 $groupTitle = $groupTitle[0];
844 if (!$groupTitle && isset($table['group_title'])) {
845 $groupTitle = $table['group_title'];
848 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
849 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
850 $colGroups[$tableName]['group_title'] = $groupTitle;
853 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
859 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
860 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
862 $this->assign('colGroups', $colGroups);
865 function addFilters() {
866 $options = $filters = array();
868 foreach ($this->_filters
as $table => $attributes) {
869 foreach ($attributes as $fieldName => $field) {
870 // get ready with option value pair
871 // @ 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
873 $operations = $this->getOperationPair(
874 CRM_Utils_Array
::value('operatorType', $field),
877 $filters[$table][$fieldName] = $field;
879 switch (CRM_Utils_Array
::value('operatorType', $field)) {
880 case CRM_Report_Form
::OP_MONTH
:
881 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
882 // If there's no option list for this filter, define one.
883 $field['options'] = array(
892 9 => ts('September'),
894 11 => ts('November'),
895 12 => ts('December'),
897 // Add this option list to this column _columns. This is
898 // required so that filter statistics show properly.
899 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
901 case CRM_Report_Form
::OP_MULTISELECT
:
902 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
903 // assume a multi-select field
904 if (!empty($field['options'])) {
905 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
906 if (count($operations) <= 1) {
909 $select = $this->addElement('select', "{$fieldName}_value", NULL,
910 $field['options'], array(
912 'style' => 'min-width:250px',
915 $select->setMultiple(TRUE);
919 case CRM_Report_Form
::OP_SELECT
:
920 // assume a select field
921 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
922 if (!empty($field['options']))
923 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
926 case CRM_Report_Form
::OP_DATE
:
927 // build datetime fields
928 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
932 case CRM_Report_Form
::OP_DATETIME
:
933 // build datetime fields
934 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
938 case CRM_Report_Form
::OP_INT
:
939 case CRM_Report_Form
::OP_FLOAT
:
940 // and a min value input box
941 $this->add('text', "{$fieldName}_min", ts('Min'));
942 // and a max value input box
943 $this->add('text', "{$fieldName}_max", ts('Max'));
945 // default type is string
946 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
947 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
949 // we need text box for value input
950 $this->add('text', "{$fieldName}_value", NULL);
955 $this->assign('filters', $filters);
958 function addOptions() {
959 if (!empty($this->_options
)) {
960 // FIXME: For now lets build all elements as checkboxes.
961 // Once we clear with the format we can build elements based on type
964 foreach ($this->_options
as $fieldName => $field) {
965 if ($field['type'] == 'select') {
966 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
968 else if ($field['type'] == 'checkbox') {
969 $options[$field['title']] = $fieldName;
970 $this->addCheckBox($fieldName, NULL,
972 NULL, NULL, NULL, $this->_fourColumnAttribute
977 $this->assign('otherOptions', $this->_options
);
980 function addChartOptions() {
981 if (!empty($this->_charts
)) {
982 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
983 $this->assign('charts', $this->_charts
);
984 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
988 function addGroupBys() {
989 $options = $freqElements = array();
991 foreach ($this->_columns
as $tableName => $table) {
992 if (array_key_exists('group_bys', $table)) {
993 foreach ($table['group_bys'] as $fieldName => $field) {
994 if (!empty($field)) {
995 $options[$field['title']] = $fieldName;
996 if (!empty($field['frequency'])) {
997 $freqElements[$field['title']] = $fieldName;
1003 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1004 NULL, NULL, NULL, $this->_fourColumnAttribute
1006 $this->assign('groupByElements', $options);
1008 foreach ($freqElements as $name) {
1009 $this->addElement('select', "group_bys_freq[$name]",
1010 ts('Frequency'), $this->_groupByDateFreq
1015 function addOrderBys() {
1017 foreach ($this->_columns
as $tableName => $table) {
1019 // Report developer may define any column to order by; include these as order-by options
1020 if (array_key_exists('order_bys', $table)) {
1021 foreach ($table['order_bys'] as $fieldName => $field) {
1022 if (!empty($field)) {
1023 $options[$fieldName] = $field['title'];
1028 /* Add searchable custom fields as order-by options, if so requested
1029 * (These are already indexed, so allowing to order on them is cheap.)
1033 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1034 foreach ($table['fields'] as $fieldName => $field) {
1035 if (empty($field['no_display'])) {
1036 $options[$fieldName] = $field['title'];
1044 $this->assign('orderByOptions', $options);
1046 if (!empty($options)) {
1048 '-' => ' - none - ') +
$options;
1049 for ($i = 1; $i <= 5; $i++
) {
1050 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1051 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1052 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1053 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1058 function buildInstanceAndButtons() {
1059 CRM_Report_Form_Instance
::buildForm($this);
1061 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1063 $this->addElement('submit', $this->_instanceButtonName
, $label);
1064 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1065 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1068 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1070 if ($this->_instanceForm
) {
1071 $this->assign('instanceForm', TRUE);
1074 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1075 $this->addElement('submit', $this->_printButtonName
, $label);
1077 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1078 $this->addElement('submit', $this->_pdfButtonName
, $label);
1080 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1082 if ($this->_csvSupported
) {
1083 $this->addElement('submit', $this->_csvButtonName
, $label);
1086 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1087 $this->addElement('select', 'groups', ts('Group'),
1088 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
1090 $this->assign('group', TRUE);
1093 $label = ts('Add These Contacts to Group');
1094 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1096 $this->addChartOptions();
1097 $this->addButtons(array(
1100 'name' => ts('Preview Report'),
1101 'isDefault' => TRUE,
1107 function buildQuickForm() {
1108 $this->addColumns();
1110 $this->addFilters();
1112 $this->addOptions();
1114 $this->addGroupBys();
1116 $this->addOrderBys();
1118 $this->buildInstanceAndButtons();
1120 //add form rule for report
1121 if (is_callable(array(
1122 $this, 'formRule'))) {
1123 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1127 // a formrule function to ensure that fields selected in group_by
1128 // (if any) should only be the ones present in display/select fields criteria;
1129 // note: works if and only if any custom field selected in group_by.
1130 function customDataFormRule($fields, $ignoreFields = array( )) {
1132 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1133 foreach ($this->_columns
as $tableName => $table) {
1134 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1135 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1136 if (array_key_exists($fieldName, $fields['group_bys']) &&
1137 !array_key_exists($fieldName, $fields['fields'])
1139 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1141 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1142 foreach ($fields['fields'] as $fld => $val) {
1143 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1144 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1155 // Note: $fieldName param allows inheriting class to build operationPairs
1156 // specific to a field.
1157 function getOperationPair($type = "string", $fieldName = NULL) {
1158 // FIXME: At some point we should move these key-val pairs
1159 // to option_group and option_value table.
1161 case CRM_Report_Form
::OP_INT
:
1162 case CRM_Report_Form
::OP_FLOAT
:
1164 'lte' => ts('Is less than or equal to'),
1165 'gte' => ts('Is greater than or equal to'),
1166 'bw' => ts('Is between'),
1167 'eq' => ts('Is equal to'),
1168 'lt' => ts('Is less than'),
1169 'gt' => ts('Is greater than'),
1170 'neq' => ts('Is not equal to'),
1171 'nbw' => ts('Is not between'),
1172 'nll' => ts('Is empty (Null)'),
1173 'nnll' => ts('Is not empty (Null)'),
1177 case CRM_Report_Form
::OP_SELECT
:
1179 'eq' => ts('Is equal to'),
1182 case CRM_Report_Form
::OP_MONTH
:
1183 case CRM_Report_Form
::OP_MULTISELECT
:
1185 'in' => ts('Is one of'),
1186 'notin' => ts('Is not one of'),
1190 case CRM_Report_Form
::OP_DATE
:
1192 'nll' => ts('Is empty (Null)'),
1193 'nnll' => ts('Is not empty (Null)'),
1197 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1198 // use this operator for the values, concatenated with separator. For e.g if
1199 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1201 'mhas' => ts('Is one of'),
1202 'mnot' => ts('Is not one of'),
1208 'has' => ts('Contains'),
1209 'sw' => ts('Starts with'),
1210 'ew' => ts('Ends with'),
1211 'nhas' => ts('Does not contain'),
1212 'eq' => ts('Is equal to'),
1213 'neq' => ts('Is not equal to'),
1214 'nll' => ts('Is empty (Null)'),
1215 'nnll' => ts('Is not empty (Null)'),
1220 function buildTagFilter() {
1221 $contactTags = CRM_Core_BAO_Tag
::getTags();
1222 if (!empty($contactTags)) {
1223 $this->_columns
['civicrm_tag'] = array(
1224 'dao' => 'CRM_Core_DAO_Tag',
1230 'title' => ts('Tag'),
1232 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1233 'options' => $contactTags,
1241 * Adds group filters to _columns (called from _Constuct
1243 function buildGroupFilter() {
1244 $this->_columns
['civicrm_group']['filters'] = array(
1247 'name' => 'group_id',
1248 'title' => ts('Group'),
1249 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1251 'options' => CRM_Core_PseudoConstant
::group(),
1254 if (empty($this->_columns
['civicrm_group']['dao'])) {
1255 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1257 if (empty($this->_columns
['civicrm_group']['alias'])) {
1258 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1262 function getSQLOperator($operator = "like") {
1263 switch ($operator) {
1296 return 'IS NOT NULL';
1304 function whereClause(&$field, $op,
1308 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1314 if (($min !== NULL && strlen($min) > 0) ||
1315 ($max !== NULL && strlen($max) > 0)
1317 $min = CRM_Utils_Type
::escape($min, $type);
1318 $max = CRM_Utils_Type
::escape($max, $type);
1322 $clauses[] = "( {$field['dbAlias']} >= $min )";
1325 $clauses[] = "( {$field['dbAlias']} < $min )";
1330 $clauses[] = "( {$field['dbAlias']} <= $max )";
1333 $clauses[] = "( {$field['dbAlias']} > $max )";
1337 if (!empty($clauses)) {
1339 $clause = implode(' AND ', $clauses);
1342 $clause = implode(' OR ', $clauses);
1350 if ($value !== NULL && strlen($value) > 0) {
1351 $value = CRM_Utils_Type
::escape($value, $type);
1352 if (strpos($value, '%') === FALSE) {
1353 $value = "'%{$value}%'";
1356 $value = "'{$value}'";
1358 $sqlOP = $this->getSQLOperator($op);
1359 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1365 if ($value !== NULL && is_array($value) && count($value) > 0) {
1366 $sqlOP = $this->getSQLOperator($op);
1367 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1368 //cycle through selections and esacape values
1369 foreach ($value as $key => $selection) {
1370 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1372 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1375 // for numerical values
1376 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1378 if ($op == 'notin') {
1379 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1382 $clause = "( " . $clause . " )";
1388 // mhas == multiple has
1389 if ($value !== NULL && count($value) > 0) {
1390 $sqlOP = $this->getSQLOperator($op);
1391 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1396 // mnot == multiple is not one of
1397 if ($value !== NULL && count($value) > 0) {
1398 $sqlOP = $this->getSQLOperator($op);
1399 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1405 if ($value !== NULL && strlen($value) > 0) {
1406 $value = CRM_Utils_Type
::escape($value, $type);
1407 if (strpos($value, '%') === FALSE) {
1409 $value = "'{$value}%'";
1412 $value = "'%{$value}'";
1416 $value = "'{$value}'";
1418 $sqlOP = $this->getSQLOperator($op);
1419 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1425 $sqlOP = $this->getSQLOperator($op);
1426 $clause = "( {$field['dbAlias']} $sqlOP )";
1430 if ($value !== NULL && strlen($value) > 0) {
1431 if (isset($field['clause'])) {
1432 // FIXME: we not doing escape here. Better solution is to use two
1433 // different types - data-type and filter-type
1434 $clause = $field['clause'];
1437 $value = CRM_Utils_Type
::escape($value, $type);
1438 $sqlOP = $this->getSQLOperator($op);
1439 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1440 $value = "'{$value}'";
1442 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1448 if (!empty($field['group']) && $clause) {
1449 $clause = $this->whereGroupClause($field, $value, $op);
1451 elseif (!empty($field['tag']) && $clause) {
1452 // not using left join in query because if any contact
1453 // belongs to more than one tag, results duplicate
1455 $clause = $this->whereTagClause($field, $value, $op);
1461 function dateClause($fieldName,
1462 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1465 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1466 $sqlOP = $this->getSQLOperator($relative);
1467 return "( {$fieldName} {$sqlOP} )";
1470 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1473 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1474 $clauses[] = "( {$fieldName} >= $from )";
1478 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1479 $clauses[] = "( {$fieldName} <= {$to} )";
1482 if (!empty($clauses)) {
1483 return implode(' AND ', $clauses);
1489 * @todo - could not find any instances where this is called
1490 * @param unknown_type $relative
1491 * @param String $from
1492 * @param String_type $to
1493 * @return string|NULL
1495 function dateDisplay($relative, $from, $to) {
1496 list($from, $to) = $this->getFromTo($relative, $from, $to);
1499 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1502 $clauses[] = 'Past';
1506 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1509 $clauses[] = 'Today';
1512 if (!empty($clauses)) {
1513 return implode(' - ', $clauses);
1519 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1520 if (empty($totime)) {
1523 //FIX ME not working for relative
1525 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1526 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1527 $from = substr($dateRange['from'], 0, 8);
1528 //Take only Date Part, Sometime Time part is also present in 'to'
1529 $to = substr($dateRange['to'], 0, 8);
1531 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1532 $to = CRM_Utils_Date
::processDate($to, $totime);
1533 return array($from, $to);
1536 function alterDisplay(&$rows) {
1537 // custom code to alter rows
1540 function alterCustomDataDisplay(&$rows) {
1541 // custom code to alter rows having custom values
1542 if (empty($this->_customGroupExtends
)) {
1546 $customFieldIds = array();
1547 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1548 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1549 $customFieldIds[$fieldAlias] = $fieldId;
1552 if (empty($customFieldIds)) {
1556 $customFields = $fieldValueMap = array();
1557 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1559 // skip for type date and ContactReference since date format is already handled
1561 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1562 FROM civicrm_custom_field cf
1563 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1564 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1565 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1566 cg.is_active = 1 AND
1567 cf.is_active = 1 AND
1568 cf.is_searchable = 1 AND
1569 cf.data_type NOT IN ('ContactReference', 'Date') AND
1570 cf.id IN (" . implode(",", $customFieldIds) . ")";
1572 $dao = CRM_Core_DAO
::executeQuery($query);
1573 while ($dao->fetch()) {
1574 foreach ($customFieldCols as $key) {
1575 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1577 if ($dao->option_group_id
) {
1578 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1583 $entryFound = FALSE;
1584 foreach ($rows as $rowNum => $row) {
1585 foreach ($row as $tableCol => $val) {
1586 if (array_key_exists($tableCol, $customFields)) {
1587 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1592 // skip looking further in rows, if first row itself doesn't
1593 // have the column we need
1600 function formatCustomValues($value, $customField, $fieldValueMap) {
1601 if (CRM_Utils_System
::isNull($value)) {
1605 $htmlType = $customField['html_type'];
1607 switch ($customField['data_type']) {
1609 if ($value == '1') {
1610 $retValue = ts('Yes');
1613 $retValue = ts('No');
1618 $retValue = CRM_Utils_System
::formatWikiURL($value);
1630 if ($htmlType == 'Text') {
1631 $retValue = (float)$value;
1635 if ($htmlType == 'Text') {
1645 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1650 if (in_array($htmlType, array(
1651 'Text', 'TextArea'))) {
1655 case 'StateProvince':
1658 switch ($htmlType) {
1659 case 'Multi-Select Country':
1660 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1661 $customData = array();
1662 foreach ($value as $val) {
1664 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1667 $retValue = implode(', ', $customData);
1670 case 'Select Country':
1671 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1674 case 'Select State/Province':
1675 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1678 case 'Multi-Select State/Province':
1679 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1680 $customData = array();
1681 foreach ($value as $val) {
1683 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1686 $retValue = implode(', ', $customData);
1691 case 'Autocomplete-Select':
1692 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1696 case 'AdvMulti-Select':
1697 case 'Multi-Select':
1698 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1699 $customData = array();
1700 foreach ($value as $val) {
1702 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1705 $retValue = implode(', ', $customData);
1720 function removeDuplicates(&$rows) {
1721 if (empty($this->_noRepeats
)) {
1724 $checkList = array();
1726 foreach ($rows as $key => $list) {
1727 foreach ($list as $colName => $colVal) {
1728 if (array_key_exists($colName, $checkList) &&
1729 $checkList[$colName] == $colVal) {
1730 $rows[$key][$colName] = "";
1732 if (in_array($colName, $this->_noRepeats
)) {
1733 $checkList[$colName] = $colVal;
1739 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1740 foreach ($row as $colName => $colVal) {
1741 if (in_array($colName, $fields)) {
1742 $row[$colName] = $row[$colName];
1744 elseif (isset($this->_columnHeaders
[$colName])) {
1746 $row[$colName] = "Subtotal";
1750 unset($row[$colName]);
1756 function grandTotal(&$rows) {
1757 if (!$this->_rollup ||
($this->_rollup
== '') ||
1758 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1762 $lastRow = array_pop($rows);
1764 foreach ($this->_columnHeaders
as $fld => $val) {
1765 if (!in_array($fld, $this->_statFields
)) {
1766 if (!$this->_grandFlag
) {
1767 $lastRow[$fld] = "Grand Total";
1768 $this->_grandFlag
= TRUE;
1771 $lastRow[$fld] = "";
1776 $this->assign('grandStat', $lastRow);
1780 function formatDisplay(&$rows, $pager = TRUE) {
1781 // set pager based on if any limit was applied in the query.
1786 // allow building charts if any
1787 if (!empty($this->_params
['charts']) && !empty($rows)) {
1788 $this->buildChart($rows);
1789 $this->assign('chartEnabled', TRUE);
1790 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1791 $this->assign('chartId', $this->_chartId
);
1794 // unset columns not to be displayed.
1795 foreach ($this->_columnHeaders
as $key => $value) {
1796 if (!empty($value['no_display'])) {
1797 unset($this->_columnHeaders
[$key]);
1801 // unset columns not to be displayed.
1802 if (!empty($rows)) {
1803 foreach ($this->_noDisplay
as $noDisplayField) {
1804 foreach ($rows as $rowNum => $row) {
1805 unset($this->_columnHeaders
[$noDisplayField]);
1810 // build array of section totals
1811 $this->sectionTotals();
1813 // process grand-total row
1814 $this->grandTotal($rows);
1816 // use this method for formatting rows for display purpose.
1817 $this->alterDisplay($rows);
1818 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1820 // use this method for formatting custom rows for display purpose.
1821 $this->alterCustomDataDisplay($rows);
1824 function buildChart(&$rows) {
1825 // override this method for building charts.
1828 // select() method below has been added recently (v3.3), and many of the report templates might
1829 // still be having their own select() method. We should fix them as and when encountered and move
1830 // towards generalizing the select() method below.
1832 $select = $this->_selectAliases
= array();
1834 foreach ($this->_columns
as $tableName => $table) {
1835 if (array_key_exists('fields', $table)) {
1836 foreach ($table['fields'] as $fieldName => $field) {
1837 if ($tableName == 'civicrm_address') {
1838 $this->_addressField
= TRUE;
1840 if ($tableName == 'civicrm_email') {
1841 $this->_emailField
= TRUE;
1843 if ($tableName == 'civicrm_phone') {
1844 $this->_phoneField
= TRUE;
1847 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1849 // 1. In many cases we want select clause to be built in slightly different way
1850 // for a particular field of a particular type.
1851 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1853 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1854 if ($selectClause) {
1855 $select[] = $selectClause;
1859 // include statistics columns only if set
1860 if (!empty($field['statistics'])) {
1861 foreach ($field['statistics'] as $stat => $label) {
1862 $alias = "{$tableName}_{$fieldName}_{$stat}";
1863 switch (strtolower($stat)) {
1866 $select[] = "$stat({$field['dbAlias']}) as $alias";
1867 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1868 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1869 $this->_statFields
[$label] = $alias;
1870 $this->_selectAliases
[] = $alias;
1874 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1875 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1876 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1877 $this->_statFields
[$label] = $alias;
1878 $this->_selectAliases
[] = $alias;
1881 case 'count_distinct':
1882 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1883 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1884 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1885 $this->_statFields
[$label] = $alias;
1886 $this->_selectAliases
[] = $alias;
1890 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1891 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1892 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1893 $this->_statFields
[$label] = $alias;
1894 $this->_selectAliases
[] = $alias;
1900 $alias = "{$tableName}_{$fieldName}";
1901 $select[] = "{$field['dbAlias']} as $alias";
1902 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1903 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1904 $this->_selectAliases
[] = $alias;
1910 // select for group bys
1911 if (array_key_exists('group_bys', $table)) {
1912 foreach ($table['group_bys'] as $fieldName => $field) {
1914 if ($tableName == 'civicrm_address') {
1915 $this->_addressField
= TRUE;
1917 if ($tableName == 'civicrm_email') {
1918 $this->_emailField
= TRUE;
1920 if ($tableName == 'civicrm_phone') {
1921 $this->_phoneField
= TRUE;
1923 // 1. In many cases we want select clause to be built in slightly different way
1924 // for a particular field of a particular type.
1925 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1927 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1928 if ($selectClause) {
1929 $select[] = $selectClause;
1933 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
1934 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1936 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1937 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1938 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1939 $field['title'] = 'Week';
1943 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1944 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1945 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1946 $field['title'] = 'Year';
1950 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1951 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1952 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1953 $field['title'] = 'Month';
1957 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1958 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1959 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1960 $field['title'] = 'Quarter';
1963 // for graphs and charts -
1964 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
1965 $this->_interval
= $field['title'];
1966 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1967 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1968 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1970 // just to make sure these values are transfered to rows.
1971 // since we 'll need them for calculation purpose,
1972 // e.g making subtotals look nicer or graphs
1973 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1974 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1981 $this->_selectClauses
= $select;
1982 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1985 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1990 $this->storeWhereHavingClauseArray();
1992 if (empty($this->_whereClauses
)) {
1993 $this->_where
= "WHERE ( 1 ) ";
1994 $this->_having
= "";
1997 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2000 if ($this->_aclWhere
) {
2001 $this->_where
.= " AND {$this->_aclWhere} ";
2004 if (!empty($this->_havingClauses
)) {
2005 // use this clause to construct group by clause.
2006 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2011 * Store Where clauses into an array - breaking out this step makes
2012 * over-riding more flexible as the clauses can be used in constructing a
2013 * temp table that may not be part of the final where clause or added
2014 * in other functions
2016 function storeWhereHavingClauseArray(){
2017 foreach ($this->_columns
as $tableName => $table) {
2018 if (array_key_exists('filters', $table)) {
2019 foreach ($table['filters'] as $fieldName => $field) {
2020 // respect pseudofield to filter spec so fields can be marked as
2021 // not to be handled here
2022 if(!empty($field['pseudofield'])){
2026 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2027 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2028 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2029 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2030 if (is_array($value) && !empty($value)) {
2031 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2035 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2036 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2037 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2038 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2039 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2040 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2044 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2046 $clause = $this->whereClause($field,
2048 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2049 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2050 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2055 if (!empty($clause)) {
2056 if (!empty($field['having'])) {
2057 $this->_havingClauses
[] = $clause;
2060 $this->_whereClauses
[] = $clause;
2068 function processReportMode() {
2069 $buttonName = $this->controller
->getButtonName();
2071 $output = CRM_Utils_Request
::retrieve(
2074 CRM_Core_DAO
::$_nullObject
2078 CRM_Utils_Request
::retrieve(
2081 CRM_Core_DAO
::$_nullObject
2084 $this->_absoluteUrl
= FALSE;
2086 $this->assign('printOnly', FALSE);
2088 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2089 $this->assign('printOnly', TRUE);
2091 $this->assign('outputMode', 'print');
2092 $this->_outputMode
= 'print';
2093 if ($this->_sendmail
) {
2094 $this->_absoluteUrl
= TRUE;
2097 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2098 $this->assign('printOnly', TRUE);
2100 $this->assign('outputMode', 'pdf');
2101 $this->_outputMode
= 'pdf';
2102 $this->_absoluteUrl
= TRUE;
2104 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2105 $this->assign('printOnly', TRUE);
2107 $this->assign('outputMode', 'csv');
2108 $this->_outputMode
= 'csv';
2109 $this->_absoluteUrl
= TRUE;
2111 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2112 $this->assign('outputMode', 'group');
2113 $this->_outputMode
= 'group';
2115 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2116 $this->assign('outputMode', 'create_report');
2117 $this->_outputMode
= 'create_report';
2120 $this->assign('outputMode', 'html');
2121 $this->_outputMode
= 'html';
2124 // Get today's date to include in printed reports
2126 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2127 $this->assign('reportDate', $reportDate);
2131 function beginPostProcess() {
2132 $this->setParams($this->controller
->exportValues($this->_name
));
2134 if (empty($this->_params
) &&
2137 $this->setParams($this->_formValues
);
2140 // hack to fix params when submitted from dashboard, CRM-8532
2141 // fields array is missing because form building etc is skipped
2142 // in dashboard mode for report
2143 //@todo - this could be done in the dashboard no we have a setter
2144 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2145 $this->setParams($this->_formValues
);
2148 $this->_formValues
= $this->_params
;
2149 if (CRM_Core_Permission
::check('administer Reports') &&
2150 isset($this->_id
) &&
2151 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2152 $this->_chartButtonName
== $this->controller
->getButtonName()
2155 $this->assign('updateReportButton', TRUE);
2157 $this->processReportMode();
2158 $this->beginPostProcessCommon();
2162 * beginPostProcess function run in both report mode and non-report mode (api)
2164 function beginPostProcessCommon() {
2168 function buildQuery($applyLimit = TRUE) {
2171 $this->customDataFrom();
2176 // order_by columns not selected for display need to be included in SELECT
2177 $unselectedSectionColumns = $this->unselectedSectionColumns();
2178 foreach ($unselectedSectionColumns as $alias => $section) {
2179 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2182 if ($applyLimit && empty($this->_params
['charts'])) {
2185 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2187 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2191 function groupBy() {
2192 $groupBys = array();
2193 if (!empty($this->_params
['group_bys']) &&
2194 is_array($this->_params
['group_bys']) &&
2195 !empty($this->_params
['group_bys'])
2197 foreach ($this->_columns
as $tableName => $table) {
2198 if (array_key_exists('group_bys', $table)) {
2199 foreach ($table['group_bys'] as $fieldName => $field) {
2200 if (!empty($this->_params
['group_bys'][$fieldName])) {
2201 $groupBys[] = $field['dbAlias'];
2208 if (!empty($groupBys)) {
2209 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2213 function orderBy() {
2214 $this->_orderBy
= "";
2215 $this->_sections
= array();
2216 $this->storeOrderByArray();
2217 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2218 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2220 $this->assign('sections', $this->_sections
);
2224 * In some cases other functions want to know which fields are selected for ordering by
2225 * Separating this into a separate function allows it to be called separately from constructing
2226 * the order by clause
2228 function storeOrderByArray() {
2229 $orderBys = array();
2231 if (!empty($this->_params
['order_bys']) &&
2232 is_array($this->_params
['order_bys']) &&
2233 !empty($this->_params
['order_bys'])
2236 // Proces order_bys in user-specified order
2237 foreach ($this->_params
['order_bys'] as $orderBy) {
2238 $orderByField = array();
2239 foreach ($this->_columns
as $tableName => $table) {
2240 if (array_key_exists('order_bys', $table)) {
2241 // For DAO columns defined in $this->_columns
2242 $fields = $table['order_bys'];
2244 elseif (array_key_exists('extends', $table)) {
2245 // For custom fields referenced in $this->_customGroupExtends
2246 $fields = CRM_Utils_Array
::value('fields', $table, array());
2248 if (!empty($fields) && is_array($fields)) {
2249 foreach ($fields as $fieldName => $field) {
2250 if ($fieldName == $orderBy['column']) {
2251 $orderByField = array_merge($field, $orderBy);
2252 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2259 if (!empty($orderByField)) {
2260 $this->_orderByFields
[] = $orderByField;
2261 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2263 // Record any section headers for assignment to the template
2264 if (!empty($orderBy['section'])) {
2265 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2266 $this->_sections
[$orderByField['tplField']] = $orderByField;
2272 $this->_orderByArray
= $orderBys;
2274 $this->assign('sections', $this->_sections
);
2277 function unselectedSectionColumns() {
2278 $selectColumns = array();
2279 foreach ($this->_columns
as $tableName => $table) {
2280 if (array_key_exists('fields', $table)) {
2281 foreach ($table['fields'] as $fieldName => $field) {
2282 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2284 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2290 if (is_array($this->_sections
)) {
2291 return array_diff_key($this->_sections
, $selectColumns);
2298 function buildRows($sql, &$rows) {
2299 $dao = CRM_Core_DAO
::executeQuery($sql);
2300 if (!is_array($rows)) {
2304 // use this method to modify $this->_columnHeaders
2305 $this->modifyColumnHeaders();
2307 $unselectedSectionColumns = $this->unselectedSectionColumns();
2309 while ($dao->fetch()) {
2311 foreach ($this->_columnHeaders
as $key => $value) {
2312 if (property_exists($dao, $key)) {
2313 $row[$key] = $dao->$key;
2317 // section headers not selected for display need to be added to row
2318 foreach ($unselectedSectionColumns as $key => $values) {
2319 if (property_exists($dao, $key)) {
2320 $row[$key] = $dao->$key;
2329 * When "order by" fields are marked as sections, this assigns to the template
2330 * an array of total counts for each section. This data is used by the Smarty
2331 * plugin {sectionTotal}
2333 function sectionTotals() {
2335 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2336 if (empty($this->_selectAliases
)) {
2340 if (!empty($this->_sections
)) {
2341 // build the query with no LIMIT clause
2342 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2343 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2345 // pull section aliases out of $this->_sections
2346 $sectionAliases = array_keys($this->_sections
);
2349 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2350 $ifnulls[] = "ifnull($alias, '') as $alias";
2353 /* Group (un-limited) report by all aliases and get counts. This might
2354 * be done more efficiently when the contents of $sql are known, ie. by
2355 * overriding this method in the report class.
2359 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2361 // initialize array of total counts
2363 $dao = CRM_Core_DAO
::executeQuery($query);
2364 while ($dao->fetch()) {
2366 // let $this->_alterDisplay translate any integer ids to human-readable values.
2367 $rows[0] = $dao->toArray();
2368 $this->alterDisplay($rows);
2371 // add totals for all permutations of section values
2374 $aliasCount = count($sectionAliases);
2375 foreach ($sectionAliases as $alias) {
2376 $values[] = $row[$alias];
2377 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2378 if ($i == $aliasCount) {
2379 // the last alias is the lowest-level section header; use count as-is
2380 $totals[$key] = $dao->ct
;
2383 // other aliases are higher level; roll count into their total
2384 $totals[$key] +
= $dao->ct
;
2388 $this->assign('sectionTotals', $totals);
2392 function modifyColumnHeaders() {
2393 // use this method to modify $this->_columnHeaders
2396 function doTemplateAssignment(&$rows) {
2397 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2398 $this->assign_by_ref('rows', $rows);
2399 $this->assign('statistics', $this->statistics($rows));
2402 // override this method to build your own statistics
2403 function statistics(&$rows) {
2404 $statistics = array();
2406 $count = count($rows);
2408 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2412 $this->countStat($statistics, $count);
2414 $this->groupByStat($statistics);
2416 $this->filterStat($statistics);
2421 function countStat(&$statistics, $count) {
2422 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2426 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2427 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2428 'value' => $this->_rowsFound
,
2433 function groupByStat(&$statistics) {
2434 if (!empty($this->_params
['group_bys']) &&
2435 is_array($this->_params
['group_bys']) &&
2436 !empty($this->_params
['group_bys'])
2438 foreach ($this->_columns
as $tableName => $table) {
2439 if (array_key_exists('group_bys', $table)) {
2440 foreach ($table['group_bys'] as $fieldName => $field) {
2441 if (!empty($this->_params
['group_bys'][$fieldName])) {
2442 $combinations[] = $field['title'];
2447 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2448 'value' => implode(' & ', $combinations),
2453 function filterStat(&$statistics) {
2454 foreach ($this->_columns
as $tableName => $table) {
2455 if (array_key_exists('filters', $table)) {
2456 foreach ($table['filters'] as $fieldName => $field) {
2457 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2460 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2461 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2462 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2463 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2464 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2466 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2467 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2469 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2470 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2473 $statistics['filters'][] = array(
2474 'title' => $field['title'],
2475 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2478 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2479 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2481 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2482 $statistics['filters'][] = array(
2483 'title' => $field['title'],
2484 'value' => $pair[$rel],
2489 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2492 $pair = $this->getOperationPair(
2493 CRM_Utils_Array
::value('operatorType', $field),
2496 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2497 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2498 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2499 if (in_array($op, array(
2500 'bw', 'nbw')) && ($min ||
$max)) {
2501 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2503 elseif ($op == 'nll' ||
$op == 'nnll') {
2504 $value = $pair[$op];
2506 elseif (is_array($val) && (!empty($val))) {
2507 $options = CRM_Utils_Array
::value('options', $field, array());
2508 foreach ($val as $key => $valIds) {
2509 if (isset($options[$valIds])) {
2510 $val[$key] = $options[$valIds];
2513 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2514 $val = implode(', ', $val);
2515 $value = "{$pair[$op]} " . $val;
2517 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2518 is_array($field['options']) && !empty($field['options'])
2520 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2523 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2527 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2537 function endPostProcess(&$rows = NULL) {
2538 if ( $this->_storeResultSet
) {
2539 $this->_resultSet
= $rows;
2542 if ($this->_outputMode
== 'print' ||
2543 $this->_outputMode
== 'pdf' ||
2547 $content = $this->compileContent();
2548 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2552 if ($this->_sendmail
) {
2553 $config = CRM_Core_Config
::singleton();
2554 $attachments = array();
2556 if ($this->_outputMode
== 'csv') {
2557 $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'];
2559 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2560 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2561 file_put_contents($csvFullFilename, $csvContent);
2562 $attachments[] = array(
2563 'fullPath' => $csvFullFilename,
2564 'mime_type' => 'text/csv',
2565 'cleanName' => 'CiviReport.csv',
2568 if ($this->_outputMode
== 'pdf') {
2569 // generate PDF content
2570 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2571 file_put_contents($pdfFullFilename,
2572 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2573 TRUE, array('orientation' => 'landscape')
2576 // generate Email Content
2577 $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'];
2579 $attachments[] = array(
2580 'fullPath' => $pdfFullFilename,
2581 'mime_type' => 'application/pdf',
2582 'cleanName' => 'CiviReport.pdf',
2586 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2587 $this->_outputMode
, $attachments
2589 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2592 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2596 elseif ($this->_outputMode
== 'print') {
2600 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2601 $config = CRM_Core_Config
::singleton();
2602 //get chart image name
2603 $chartImg = $this->_chartId
. '.png';
2604 //get image url path
2605 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2606 $uploadUrl .= $chartImg;
2607 //get image doc path to overwrite
2608 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2610 $chart = imagecreatefrompng($uploadUrl);
2611 //convert it into formattd png
2612 header('Content-type: image/png');
2613 //overwrite with same image
2614 imagepng($chart, $uploadImg);
2616 imagedestroy($chart);
2618 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2620 CRM_Utils_System
::civiExit();
2622 elseif ($this->_outputMode
== 'csv') {
2623 CRM_Report_Utils_Report
::export2csv($this, $rows);
2625 elseif ($this->_outputMode
== 'group') {
2626 $group = $this->_params
['groups'];
2627 $this->add2group($group);
2629 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2630 CRM_Report_Form_Instance
::postProcess($this);
2632 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2633 $this->_outputMode
== 'create_report' ) {
2634 $this->_createNew
= TRUE;
2635 CRM_Report_Form_Instance
::postProcess($this);
2639 function storeResultSet() {
2640 $this->_storeResultSet
= TRUE;
2643 function getResultSet() {
2644 return $this->_resultSet
;
2648 * Get Template file name - use default form template if a specific one has not been set up for this report
2651 function getTemplateFileName(){
2652 $defaultTpl = parent
::getTemplateFileName();
2653 $template = CRM_Core_Smarty
::singleton();
2654 if (!$template->template_exists($defaultTpl)) {
2655 $defaultTpl = 'CRM/Report/Form.tpl';
2661 * Compile the report content
2663 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2665 function compileContent(){
2666 $templateFile = $this->getHookedTemplateFileName();
2667 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2671 function postProcess() {
2672 // get ready with post process params
2673 $this->beginPostProcess();
2676 $sql = $this->buildQuery();
2678 // build array of result based on column headers. This method also allows
2679 // modifying column headers before using it to build result set i.e $rows.
2681 $this->buildRows($sql, $rows);
2683 // format result set.
2684 $this->formatDisplay($rows);
2686 // assign variables to templates
2687 $this->doTemplateAssignment($rows);
2689 // do print / pdf / instance stuff if needed
2690 $this->endPostProcess($rows);
2693 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2694 // lets do the pager if in html mode
2695 $this->_limit
= NULL;
2697 // CRM-14115, over-ride row count if rowCount is specified in URL
2698 if ($this->_dashBoardRowCount
) {
2699 $rowCount = $this->_dashBoardRowCount
;
2701 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2702 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2704 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2706 if (!$pageId && !empty($_POST)) {
2707 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2708 $pageId = max((int)@$_POST['crmPID_B'], 1);
2710 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2711 $pageId = max((int)@$_POST['crmPID'], 1);
2713 unset($_POST['crmPID_B'], $_POST['crmPID']);
2716 $pageId = $pageId ?
$pageId : 1;
2717 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2718 $offset = ($pageId - 1) * $rowCount;
2720 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2721 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2723 $this->_limit
= " LIMIT $offset, $rowCount";
2724 return array($offset, $rowCount);
2726 if($this->_limitValue
) {
2727 if($this->_offsetValue
) {
2728 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2731 $this->_limit
= " LIMIT " . $this->_limitValue
;
2736 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2738 // CRM-14115, over-ride row count if rowCount is specified in URL
2739 if ($this->_dashBoardRowCount
) {
2740 $rowCount = $this->_dashBoardRowCount
;
2743 if ($this->_limit
&& ($this->_limit
!= '')) {
2744 $sql = "SELECT FOUND_ROWS();";
2745 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2747 'total' => $this->_rowsFound
,
2748 'rowCount' => $rowCount,
2749 'status' => ts('Records') . ' %%StatusMessage%%',
2750 'buttonBottom' => 'PagerBottomButton',
2751 'buttonTop' => 'PagerTopButton',
2752 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2755 $pager = new CRM_Utils_Pager($params);
2756 $this->assign_by_ref('pager', $pager);
2757 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2761 function whereGroupClause($field, $value, $op) {
2763 $smartGroupQuery = "";
2765 $group = new CRM_Contact_DAO_Group();
2766 $group->is_active
= 1;
2768 $smartGroups = array();
2769 while ($group->fetch()) {
2770 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2771 $smartGroups[] = $group->id
;
2775 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2777 $smartGroupQuery = '';
2778 if (!empty($smartGroups)) {
2779 $smartGroups = implode(',', $smartGroups);
2780 $smartGroupQuery = " UNION DISTINCT
2781 SELECT DISTINCT smartgroup_contact.contact_id
2782 FROM civicrm_group_contact_cache smartgroup_contact
2783 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2786 $sqlOp = $this->getSQLOperator($op);
2787 if (!is_array($value)) {
2788 $value = array($value);
2790 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2792 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2793 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2794 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2795 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2796 {$smartGroupQuery} ) ";
2799 function whereTagClause($field, $value, $op) {
2800 // not using left join in query because if any contact
2801 // belongs to more than one tag, results duplicate
2803 $sqlOp = $this->getSQLOperator($op);
2804 if (!is_array($value)) {
2805 $value = array($value);
2807 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2809 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2810 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2811 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2812 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2815 function buildACLClause($tableAlias = 'contact_a') {
2816 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2819 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2820 if (empty($this->_customGroupExtends
)) {
2823 if (!is_array($this->_customGroupExtends
)) {
2824 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2826 $customGroupWhere = '';
2827 if (!empty($permCustomGroupIds)) {
2828 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2831 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2832 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2833 FROM civicrm_custom_group cg
2834 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2835 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2837 cg.is_active = 1 AND
2838 cf.is_active = 1 AND
2839 cf.is_searchable = 1
2840 ORDER BY cg.weight, cf.weight";
2841 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2844 while ($customDAO->fetch()) {
2845 if ($customDAO->table_name
!= $curTable) {
2846 $curTable = $customDAO->table_name
;
2847 $curFields = $curFilters = array();
2850 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2851 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2852 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2853 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2856 'fields', 'filters', 'group_bys') as $colKey) {
2857 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2858 $this->_columns
[$curTable][$colKey] = array();
2862 $fieldName = 'custom_' . $customDAO->cf_id
;
2865 // this makes aliasing work in favor
2866 $curFields[$fieldName] = array(
2867 'name' => $customDAO->column_name
,
2868 'title' => $customDAO->label
,
2869 'dataType' => $customDAO->data_type
,
2870 'htmlType' => $customDAO->html_type
,
2873 if ($this->_customGroupFilters
) {
2874 // this makes aliasing work in favor
2875 $curFilters[$fieldName] = array(
2876 'name' => $customDAO->column_name
,
2877 'title' => $customDAO->label
,
2878 'dataType' => $customDAO->data_type
,
2879 'htmlType' => $customDAO->html_type
,
2883 switch ($customDAO->data_type
) {
2886 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2887 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2888 // CRM-6946, show time part for datetime date fields
2889 if ($customDAO->time_format
) {
2890 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2895 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2896 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2900 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2904 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2905 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2909 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2910 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2914 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2915 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2919 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2921 if (!empty($customDAO->option_group_id
)) {
2922 if (in_array($customDAO->html_type
, array(
2923 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2924 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2927 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2929 if ($this->_customGroupFilters
) {
2930 $curFilters[$fieldName]['options'] = array();
2931 $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')));
2932 while ($ogDAO->fetch()) {
2933 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2939 case 'StateProvince':
2940 if (in_array($customDAO->html_type
, array(
2941 'Multi-Select State/Province'))) {
2942 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2945 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2947 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2951 if (in_array($customDAO->html_type
, array(
2952 'Multi-Select Country'))) {
2953 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2956 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2958 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2961 case 'ContactReference':
2962 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2963 $curFilters[$fieldName]['name'] = 'display_name';
2964 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2966 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2967 $curFields[$fieldName]['name'] = 'display_name';
2968 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2972 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2973 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2976 if (!array_key_exists('type', $curFields[$fieldName])) {
2977 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2981 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2983 if ($this->_customGroupFilters
) {
2984 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2986 if ($this->_customGroupGroupBy
) {
2987 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2992 function customDataFrom() {
2993 if (empty($this->_customGroupExtends
)) {
2996 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2998 foreach ($this->_columns
as $table => $prop) {
2999 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
3000 $extendsTable = $mapper[$prop['extends']];
3002 // check field is in params
3003 if (!$this->isFieldSelected($prop)) {
3006 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3008 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3010 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3011 // handle for ContactReference
3012 if (array_key_exists('fields', $prop)) {
3013 foreach ($prop['fields'] as $fieldName => $field) {
3014 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
3015 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3017 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3025 function isFieldSelected($prop) {
3030 if (!empty($this->_params
['fields'])) {
3031 foreach (array_keys($prop['fields']) as $fieldAlias) {
3032 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3033 if ($customFieldId) {
3034 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3038 //might be survey response field.
3039 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3046 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3047 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3048 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3054 if (!empty($this->_params
['order_bys'])) {
3055 foreach (array_keys($prop['fields']) as $fieldAlias) {
3056 foreach ($this->_params
['order_bys'] as $orderBy) {
3057 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3064 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3065 foreach ($prop['filters'] as $fieldAlias => $val) {
3067 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3068 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3069 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3070 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3076 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3077 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3088 * Check for empty order_by configurations and remove them; also set
3089 * template to hide them.
3091 function preProcessOrderBy(&$formValues) {
3092 // Object to show/hide form elements
3093 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3095 $_showHide->addShow('optionField_1');
3097 // Cycle through order_by options; skip any empty ones, and hide them as well
3100 if (!empty($formValues['order_bys'])) {
3101 foreach ($formValues['order_bys'] as $order_by) {
3102 if ($order_by['column'] && $order_by['column'] != '-') {
3103 $_showHide->addShow('optionField_' . $n);
3104 $orderBys[$n] = $order_by;
3109 for ($i = $n; $i <= 5; $i++
) {
3111 $_showHide->addHide('optionField_' . $i);
3115 // overwrite order_by options with modified values
3116 if (!empty($orderBys)) {
3117 $formValues['order_bys'] = $orderBys;
3120 $formValues['order_bys'] = array(1 => array('column' => '-'));
3123 // assign show/hide data to template
3124 $_showHide->addToTemplate();
3128 * Does table name have columns in SELECT clause?
3130 * @param string $tableName Name of table (index of $this->_columns array)
3134 function isTableSelected($tableName) {
3135 return in_array($tableName, $this->selectedTables());
3139 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3140 * (building the array if it's unset)
3142 * @return Array $this->_selectedTables
3144 function selectedTables() {
3145 if (!$this->_selectedTables
) {
3146 $orderByColumns = array();
3147 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3148 foreach ($this->_params
['order_bys'] as $orderBy) {
3149 $orderByColumns[] = $orderBy['column'];
3153 foreach ($this->_columns
as $tableName => $table) {
3154 if (array_key_exists('fields', $table)) {
3155 foreach ($table['fields'] as $fieldName => $field) {
3156 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3157 $this->_selectedTables
[] = $tableName;
3162 if (array_key_exists('order_bys', $table)) {
3163 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3164 if (in_array($orderByName, $orderByColumns)) {
3165 $this->_selectedTables
[] = $tableName;
3170 if (array_key_exists('filters', $table)) {
3171 foreach ($table['filters'] as $filterName => $filter) {
3172 if (!empty($this->_params
["{$filterName}_value"]) ||
3173 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3174 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3176 $this->_selectedTables
[] = $tableName;
3183 return $this->_selectedTables
;
3187 * @deprecated - use getAddressColumns which is a more accurate description
3188 * and also accepts an array of options rather than a long list
3190 * function for adding address fields to construct function in reports
3191 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3192 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3193 * @return array address fields for construct clause
3195 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3196 'country_id' => TRUE)) {
3197 $addressFields = array(
3198 'civicrm_address' =>
3200 'dao' => 'CRM_Core_DAO_Address',
3204 array('title' => ts('Address Name'),
3205 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3208 array('title' => ts('Street Address'),
3209 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3211 'supplemental_address_1' =>
3212 array('title' => ts('Supplementary Address Field 1'),
3213 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3215 'supplemental_address_2' =>
3216 array('title' => ts('Supplementary Address Field 2'),
3217 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3221 'name' => 'street_number',
3222 'title' => ts('Street Number'),
3224 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3228 'name' => 'street_name',
3229 'title' => ts('Street Name'),
3231 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3235 'name' => 'street_unit',
3236 'title' => ts('Street Unit'),
3238 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3241 array('title' => ts('City'),
3242 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3245 array('title' => ts('Postal Code'),
3246 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3248 'postal_code_suffix' =>
3249 array('title' => ts('Postal Code Suffix'),
3250 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3253 array('title' => ts('County'),
3254 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3256 'state_province_id' =>
3257 array('title' => ts('State/Province'),
3258 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3261 array('title' => ts('Country'),
3262 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3265 'grouping' => 'location-fields',
3270 $addressFields['civicrm_address']['filters'] = array(
3271 'street_number' => array('title' => ts('Street Number'),
3273 'name' => 'street_number',
3275 'street_name' => array('title' => ts('Street Name'),
3276 'name' => 'street_name',
3277 'operator' => 'like',
3279 'postal_code' => array('title' => ts('Postal Code'),
3281 'name' => 'postal_code',
3283 'city' => array('title' => ts('City'),
3284 'operator' => 'like',
3287 'county_id' => array(
3288 'name' => 'county_id',
3289 'title' => ts('County'),
3290 'type' => CRM_Utils_Type
::T_INT
,
3292 CRM_Report_Form
::OP_MULTISELECT
,
3294 CRM_Core_PseudoConstant
::county(),
3296 'state_province_id' => array(
3297 'name' => 'state_province_id',
3298 'title' => ts('State/Province'),
3299 'type' => CRM_Utils_Type
::T_INT
,
3301 CRM_Report_Form
::OP_MULTISELECT
,
3303 CRM_Core_PseudoConstant
::stateProvince(),
3305 'country_id' => array(
3306 'name' => 'country_id',
3307 'title' => ts('Country'),
3308 'type' => CRM_Utils_Type
::T_INT
,
3310 CRM_Report_Form
::OP_MULTISELECT
,
3312 CRM_Core_PseudoConstant
::country(),
3318 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3319 'street_number' => array('title' => 'Odd / Even Street Number'),
3320 'street_address' => NULL,
3322 'postal_code' => NULL,
3327 $addressFields['civicrm_address']['group_bys'] = array(
3328 'street_address' => NULL,
3330 'postal_code' => NULL,
3331 'state_province_id' =>
3332 array('title' => ts('State/Province'),
3335 array('title' => ts('Country'),
3338 array('title' => ts('County'),
3342 return $addressFields;
3346 * Do AlterDisplay processing on Address Fields
3348 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3349 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3350 $entryFound = FALSE;
3352 if (array_key_exists('civicrm_address_country_id', $row)) {
3353 if ($value = $row['civicrm_address_country_id']) {
3354 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3355 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3356 "reset=1&force=1&{$criteriaQueryParams}&" .
3357 "country_id_op=in&country_id_value={$value}",
3358 $this->_absoluteUrl
, $this->_id
3360 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3361 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3368 if (array_key_exists('civicrm_address_county_id', $row)) {
3369 if ($value = $row['civicrm_address_county_id']) {
3370 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3371 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3372 "reset=1&force=1&{$criteriaQueryParams}&" .
3373 "county_id_op=in&county_id_value={$value}",
3374 $this->_absoluteUrl
, $this->_id
3376 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3377 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3383 // handle state province
3384 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3385 if ($value = $row['civicrm_address_state_province_id']) {
3386 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3388 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3389 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3390 $this->_absoluteUrl
, $this->_id
3392 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3393 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3404 * Adjusts dates passed in to YEAR() for fiscal year.
3406 function fiscalYearOffset($fieldName) {
3407 $config = CRM_Core_Config
::singleton();
3408 $fy = $config->fiscalYearStart
;
3409 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3410 return "YEAR( $fieldName )";
3412 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3416 * Add Address into From Table if required
3418 function addAddressFromClause() {
3419 // include address field if address column is to be included
3420 if ((isset($this->_addressField
) &&
3421 $this->_addressField
3423 $this->isTableSelected('civicrm_address')
3426 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3427 ON ({$this->_aliases['civicrm_contact']}.id =
3428 {$this->_aliases['civicrm_address']}.contact_id) AND
3429 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3434 * Add Phone into From Table if required
3436 function addPhoneFromClause() {
3437 // include address field if address column is to be included
3438 if ($this->isTableSelected('civicrm_phone')
3441 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3442 ON ({$this->_aliases['civicrm_contact']}.id =
3443 {$this->_aliases['civicrm_phone']}.contact_id) AND
3444 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3449 * Get phone columns to add to array
3450 * @param array $options
3451 * - prefix Prefix to add to table (in case of more than one instance of the table)
3452 * - prefix_label Label to give columns from this phone table instance
3453 * @return array phone columns definition
3455 function getPhoneColumns($options = array()){
3456 $defaultOptions = array(
3458 'prefix_label' => '',
3461 $options = array_merge($defaultOptions,$options);
3464 $options['prefix'] . 'civicrm_phone' => array(
3465 'dao' => 'CRM_Core_DAO_Phone',
3467 $options['prefix'] . 'phone' => array(
3468 'title' => ts($options['prefix_label'] . 'Phone'),
3478 * Get address columns to add to array
3479 * @param array $options
3480 * - prefix Prefix to add to table (in case of more than one instance of the table)
3481 * - prefix_label Label to give columns from this address table instance
3482 * @return array address columns definition
3484 function getAddressColumns($options = array()){
3485 $defaultOptions = array(
3487 'prefix_label' => '',
3491 'defaults' => array(
3494 $options = array_merge($defaultOptions,$options);
3495 return $this->addAddressFields(
3496 $options['group_by'],
3497 $options['order_by'],
3498 $options['filters'],
3499 $options['defaults']
3504 function add2group($groupID) {
3505 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3506 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3507 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3509 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3510 $dao = CRM_Core_DAO
::executeQuery($sql);
3512 $contact_ids = array();
3513 // Add resulting contacts to group
3514 while ($dao->fetch()) {
3515 if ($dao->addtogroup_contact_id
) {
3516 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3520 if ( !empty($contact_ids) ) {
3521 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3522 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3525 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3530 /* function used for showing charts on print screen */
3531 static function uploadChartImage() {
3532 // upload strictly for '.png' images
3533 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3534 if (preg_match('/\.png$/', $name)) {
3536 // POST data is usually string data, but we are passing a RAW .png
3537 // so PHP is a bit confused and $_POST is empty. But it has saved
3538 // the raw bits into $HTTP_RAW_POST_DATA
3540 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3542 // prepare the directory
3543 $config = CRM_Core_Config
::singleton();
3544 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3545 if (!file_exists($defaultPath)) {
3546 mkdir($defaultPath, 0777, TRUE);
3549 // full path to the saved image including filename
3550 $destination = $defaultPath . $name;
3553 $jfh = fopen($destination, 'w') or die("can't open file");
3554 fwrite($jfh, $httpRawPostData);
3556 CRM_Utils_System
::civiExit();