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;
788 * @internal param int $id
790 function setID($instanceid) {
791 $this->_id
= $instanceid;
797 * @internal param bool $force
799 function setForce($isForce) {
800 $this->_force
= $isForce;
804 * Setter for $_limitValue
805 * @param number $_limitValue
807 function setLimitValue($_limitValue) {
808 $this->_limitValue
= $_limitValue;
812 * Setter for $_offsetValue
813 * @param number $_offsetValue
815 function setOffsetValue($_offsetValue) {
816 $this->_offsetValue
= $_offsetValue;
820 * Getter for $_defaultValues
821 * @return array $_defaultValues
823 function getDefaultValues() {
824 return $this->_defaults
;
827 function addColumns() {
830 foreach ($this->_columns
as $tableName => $table) {
831 if (array_key_exists('fields', $table)) {
832 foreach ($table['fields'] as $fieldName => $field) {
834 if (empty($field['no_display'])) {
835 foreach ( array('table', 'field') as $var) {
836 if (!empty($
{$var}['grouping'])) {
837 if (!is_array($
{$var}['grouping'])) {
838 $tableName = $
{$var}['grouping'];
840 $tableName = array_keys($
{$var}['grouping']);
841 $tableName = $tableName[0];
842 $groupTitle = array_values($
{$var}['grouping']);
843 $groupTitle = $groupTitle[0];
848 if (!$groupTitle && isset($table['group_title'])) {
849 $groupTitle = $table['group_title'];
852 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
853 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
854 $colGroups[$tableName]['group_title'] = $groupTitle;
857 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
863 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
864 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
866 $this->assign('colGroups', $colGroups);
869 function addFilters() {
870 $options = $filters = array();
872 foreach ($this->_filters
as $table => $attributes) {
873 foreach ($attributes as $fieldName => $field) {
874 // get ready with option value pair
875 // @ 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
877 $operations = $this->getOperationPair(
878 CRM_Utils_Array
::value('operatorType', $field),
881 $filters[$table][$fieldName] = $field;
883 switch (CRM_Utils_Array
::value('operatorType', $field)) {
884 case CRM_Report_Form
::OP_MONTH
:
885 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
886 // If there's no option list for this filter, define one.
887 $field['options'] = array(
896 9 => ts('September'),
898 11 => ts('November'),
899 12 => ts('December'),
901 // Add this option list to this column _columns. This is
902 // required so that filter statistics show properly.
903 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
905 case CRM_Report_Form
::OP_MULTISELECT
:
906 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
907 // assume a multi-select field
908 if (!empty($field['options'])) {
909 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
910 if (count($operations) <= 1) {
913 $select = $this->addElement('select', "{$fieldName}_value", NULL,
914 $field['options'], array(
916 'style' => 'min-width:250px',
919 $select->setMultiple(TRUE);
923 case CRM_Report_Form
::OP_SELECT
:
924 // assume a select field
925 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
926 if (!empty($field['options']))
927 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
930 case CRM_Report_Form
::OP_DATE
:
931 // build datetime fields
932 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
936 case CRM_Report_Form
::OP_DATETIME
:
937 // build datetime fields
938 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
942 case CRM_Report_Form
::OP_INT
:
943 case CRM_Report_Form
::OP_FLOAT
:
944 // and a min value input box
945 $this->add('text', "{$fieldName}_min", ts('Min'));
946 // and a max value input box
947 $this->add('text', "{$fieldName}_max", ts('Max'));
949 // default type is string
950 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
951 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
953 // we need text box for value input
954 $this->add('text', "{$fieldName}_value", NULL);
959 $this->assign('filters', $filters);
962 function addOptions() {
963 if (!empty($this->_options
)) {
964 // FIXME: For now lets build all elements as checkboxes.
965 // Once we clear with the format we can build elements based on type
968 foreach ($this->_options
as $fieldName => $field) {
969 if ($field['type'] == 'select') {
970 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
972 else if ($field['type'] == 'checkbox') {
973 $options[$field['title']] = $fieldName;
974 $this->addCheckBox($fieldName, NULL,
976 NULL, NULL, NULL, $this->_fourColumnAttribute
981 $this->assign('otherOptions', $this->_options
);
984 function addChartOptions() {
985 if (!empty($this->_charts
)) {
986 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
987 $this->assign('charts', $this->_charts
);
988 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
992 function addGroupBys() {
993 $options = $freqElements = array();
995 foreach ($this->_columns
as $tableName => $table) {
996 if (array_key_exists('group_bys', $table)) {
997 foreach ($table['group_bys'] as $fieldName => $field) {
998 if (!empty($field)) {
999 $options[$field['title']] = $fieldName;
1000 if (!empty($field['frequency'])) {
1001 $freqElements[$field['title']] = $fieldName;
1007 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1008 NULL, NULL, NULL, $this->_fourColumnAttribute
1010 $this->assign('groupByElements', $options);
1012 foreach ($freqElements as $name) {
1013 $this->addElement('select', "group_bys_freq[$name]",
1014 ts('Frequency'), $this->_groupByDateFreq
1019 function addOrderBys() {
1021 foreach ($this->_columns
as $tableName => $table) {
1023 // Report developer may define any column to order by; include these as order-by options
1024 if (array_key_exists('order_bys', $table)) {
1025 foreach ($table['order_bys'] as $fieldName => $field) {
1026 if (!empty($field)) {
1027 $options[$fieldName] = $field['title'];
1032 /* Add searchable custom fields as order-by options, if so requested
1033 * (These are already indexed, so allowing to order on them is cheap.)
1037 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1038 foreach ($table['fields'] as $fieldName => $field) {
1039 if (empty($field['no_display'])) {
1040 $options[$fieldName] = $field['title'];
1048 $this->assign('orderByOptions', $options);
1050 if (!empty($options)) {
1052 '-' => ' - none - ') +
$options;
1053 for ($i = 1; $i <= 5; $i++
) {
1054 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1055 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1056 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1057 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1062 function buildInstanceAndButtons() {
1063 CRM_Report_Form_Instance
::buildForm($this);
1065 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1067 $this->addElement('submit', $this->_instanceButtonName
, $label);
1068 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1069 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1072 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1074 if ($this->_instanceForm
) {
1075 $this->assign('instanceForm', TRUE);
1078 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1079 $this->addElement('submit', $this->_printButtonName
, $label);
1081 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1082 $this->addElement('submit', $this->_pdfButtonName
, $label);
1084 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1086 if ($this->_csvSupported
) {
1087 $this->addElement('submit', $this->_csvButtonName
, $label);
1090 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1091 $this->addElement('select', 'groups', ts('Group'),
1092 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
1094 $this->assign('group', TRUE);
1097 $label = ts('Add These Contacts to Group');
1098 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1100 $this->addChartOptions();
1101 $this->addButtons(array(
1104 'name' => ts('Preview Report'),
1105 'isDefault' => TRUE,
1111 function buildQuickForm() {
1112 $this->addColumns();
1114 $this->addFilters();
1116 $this->addOptions();
1118 $this->addGroupBys();
1120 $this->addOrderBys();
1122 $this->buildInstanceAndButtons();
1124 //add form rule for report
1125 if (is_callable(array(
1126 $this, 'formRule'))) {
1127 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1131 // a formrule function to ensure that fields selected in group_by
1132 // (if any) should only be the ones present in display/select fields criteria;
1133 // note: works if and only if any custom field selected in group_by.
1134 function customDataFormRule($fields, $ignoreFields = array( )) {
1136 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1137 foreach ($this->_columns
as $tableName => $table) {
1138 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1139 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1140 if (array_key_exists($fieldName, $fields['group_bys']) &&
1141 !array_key_exists($fieldName, $fields['fields'])
1143 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1145 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1146 foreach ($fields['fields'] as $fld => $val) {
1147 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1148 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1159 // Note: $fieldName param allows inheriting class to build operationPairs
1160 // specific to a field.
1161 function getOperationPair($type = "string", $fieldName = NULL) {
1162 // FIXME: At some point we should move these key-val pairs
1163 // to option_group and option_value table.
1165 case CRM_Report_Form
::OP_INT
:
1166 case CRM_Report_Form
::OP_FLOAT
:
1168 'lte' => ts('Is less than or equal to'),
1169 'gte' => ts('Is greater than or equal to'),
1170 'bw' => ts('Is between'),
1171 'eq' => ts('Is equal to'),
1172 'lt' => ts('Is less than'),
1173 'gt' => ts('Is greater than'),
1174 'neq' => ts('Is not equal to'),
1175 'nbw' => ts('Is not between'),
1176 'nll' => ts('Is empty (Null)'),
1177 'nnll' => ts('Is not empty (Null)'),
1181 case CRM_Report_Form
::OP_SELECT
:
1183 'eq' => ts('Is equal to'),
1186 case CRM_Report_Form
::OP_MONTH
:
1187 case CRM_Report_Form
::OP_MULTISELECT
:
1189 'in' => ts('Is one of'),
1190 'notin' => ts('Is not one of'),
1194 case CRM_Report_Form
::OP_DATE
:
1196 'nll' => ts('Is empty (Null)'),
1197 'nnll' => ts('Is not empty (Null)'),
1201 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1202 // use this operator for the values, concatenated with separator. For e.g if
1203 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1205 'mhas' => ts('Is one of'),
1206 'mnot' => ts('Is not one of'),
1212 'has' => ts('Contains'),
1213 'sw' => ts('Starts with'),
1214 'ew' => ts('Ends with'),
1215 'nhas' => ts('Does not contain'),
1216 'eq' => ts('Is equal to'),
1217 'neq' => ts('Is not equal to'),
1218 'nll' => ts('Is empty (Null)'),
1219 'nnll' => ts('Is not empty (Null)'),
1224 function buildTagFilter() {
1225 $contactTags = CRM_Core_BAO_Tag
::getTags();
1226 if (!empty($contactTags)) {
1227 $this->_columns
['civicrm_tag'] = array(
1228 'dao' => 'CRM_Core_DAO_Tag',
1234 'title' => ts('Tag'),
1236 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1237 'options' => $contactTags,
1245 * Adds group filters to _columns (called from _Constuct
1247 function buildGroupFilter() {
1248 $this->_columns
['civicrm_group']['filters'] = array(
1251 'name' => 'group_id',
1252 'title' => ts('Group'),
1253 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1255 'options' => CRM_Core_PseudoConstant
::group(),
1258 if (empty($this->_columns
['civicrm_group']['dao'])) {
1259 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1261 if (empty($this->_columns
['civicrm_group']['alias'])) {
1262 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1266 function getSQLOperator($operator = "like") {
1267 switch ($operator) {
1300 return 'IS NOT NULL';
1308 function whereClause(&$field, $op,
1312 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1318 if (($min !== NULL && strlen($min) > 0) ||
1319 ($max !== NULL && strlen($max) > 0)
1321 $min = CRM_Utils_Type
::escape($min, $type);
1322 $max = CRM_Utils_Type
::escape($max, $type);
1326 $clauses[] = "( {$field['dbAlias']} >= $min )";
1329 $clauses[] = "( {$field['dbAlias']} < $min )";
1334 $clauses[] = "( {$field['dbAlias']} <= $max )";
1337 $clauses[] = "( {$field['dbAlias']} > $max )";
1341 if (!empty($clauses)) {
1343 $clause = implode(' AND ', $clauses);
1346 $clause = implode(' OR ', $clauses);
1354 if ($value !== NULL && strlen($value) > 0) {
1355 $value = CRM_Utils_Type
::escape($value, $type);
1356 if (strpos($value, '%') === FALSE) {
1357 $value = "'%{$value}%'";
1360 $value = "'{$value}'";
1362 $sqlOP = $this->getSQLOperator($op);
1363 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1369 if ($value !== NULL && is_array($value) && count($value) > 0) {
1370 $sqlOP = $this->getSQLOperator($op);
1371 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1372 //cycle through selections and esacape values
1373 foreach ($value as $key => $selection) {
1374 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1376 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1379 // for numerical values
1380 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1382 if ($op == 'notin') {
1383 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1386 $clause = "( " . $clause . " )";
1392 // mhas == multiple has
1393 if ($value !== NULL && count($value) > 0) {
1394 $sqlOP = $this->getSQLOperator($op);
1395 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1400 // mnot == multiple is not one of
1401 if ($value !== NULL && count($value) > 0) {
1402 $sqlOP = $this->getSQLOperator($op);
1403 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1409 if ($value !== NULL && strlen($value) > 0) {
1410 $value = CRM_Utils_Type
::escape($value, $type);
1411 if (strpos($value, '%') === FALSE) {
1413 $value = "'{$value}%'";
1416 $value = "'%{$value}'";
1420 $value = "'{$value}'";
1422 $sqlOP = $this->getSQLOperator($op);
1423 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1429 $sqlOP = $this->getSQLOperator($op);
1430 $clause = "( {$field['dbAlias']} $sqlOP )";
1434 if ($value !== NULL && strlen($value) > 0) {
1435 if (isset($field['clause'])) {
1436 // FIXME: we not doing escape here. Better solution is to use two
1437 // different types - data-type and filter-type
1438 $clause = $field['clause'];
1441 $value = CRM_Utils_Type
::escape($value, $type);
1442 $sqlOP = $this->getSQLOperator($op);
1443 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1444 $value = "'{$value}'";
1446 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1452 if (!empty($field['group']) && $clause) {
1453 $clause = $this->whereGroupClause($field, $value, $op);
1455 elseif (!empty($field['tag']) && $clause) {
1456 // not using left join in query because if any contact
1457 // belongs to more than one tag, results duplicate
1459 $clause = $this->whereTagClause($field, $value, $op);
1465 function dateClause($fieldName,
1466 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1469 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1470 $sqlOP = $this->getSQLOperator($relative);
1471 return "( {$fieldName} {$sqlOP} )";
1474 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1477 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1478 $clauses[] = "( {$fieldName} >= $from )";
1482 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1483 $clauses[] = "( {$fieldName} <= {$to} )";
1486 if (!empty($clauses)) {
1487 return implode(' AND ', $clauses);
1493 * @todo - could not find any instances where this is called
1494 * @param unknown_type $relative
1495 * @param String $from
1496 * @param String_type $to
1497 * @return string|NULL
1499 function dateDisplay($relative, $from, $to) {
1500 list($from, $to) = $this->getFromTo($relative, $from, $to);
1503 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1506 $clauses[] = 'Past';
1510 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1513 $clauses[] = 'Today';
1516 if (!empty($clauses)) {
1517 return implode(' - ', $clauses);
1523 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1524 if (empty($totime)) {
1527 //FIX ME not working for relative
1529 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1530 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1531 $from = substr($dateRange['from'], 0, 8);
1532 //Take only Date Part, Sometime Time part is also present in 'to'
1533 $to = substr($dateRange['to'], 0, 8);
1535 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1536 $to = CRM_Utils_Date
::processDate($to, $totime);
1537 return array($from, $to);
1540 function alterDisplay(&$rows) {
1541 // custom code to alter rows
1544 function alterCustomDataDisplay(&$rows) {
1545 // custom code to alter rows having custom values
1546 if (empty($this->_customGroupExtends
)) {
1550 $customFieldIds = array();
1551 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1552 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1553 $customFieldIds[$fieldAlias] = $fieldId;
1556 if (empty($customFieldIds)) {
1560 $customFields = $fieldValueMap = array();
1561 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1563 // skip for type date and ContactReference since date format is already handled
1565 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1566 FROM civicrm_custom_field cf
1567 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1568 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1569 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1570 cg.is_active = 1 AND
1571 cf.is_active = 1 AND
1572 cf.is_searchable = 1 AND
1573 cf.data_type NOT IN ('ContactReference', 'Date') AND
1574 cf.id IN (" . implode(",", $customFieldIds) . ")";
1576 $dao = CRM_Core_DAO
::executeQuery($query);
1577 while ($dao->fetch()) {
1578 foreach ($customFieldCols as $key) {
1579 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1581 if ($dao->option_group_id
) {
1582 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1587 $entryFound = FALSE;
1588 foreach ($rows as $rowNum => $row) {
1589 foreach ($row as $tableCol => $val) {
1590 if (array_key_exists($tableCol, $customFields)) {
1591 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1596 // skip looking further in rows, if first row itself doesn't
1597 // have the column we need
1604 function formatCustomValues($value, $customField, $fieldValueMap) {
1605 if (CRM_Utils_System
::isNull($value)) {
1609 $htmlType = $customField['html_type'];
1611 switch ($customField['data_type']) {
1613 if ($value == '1') {
1614 $retValue = ts('Yes');
1617 $retValue = ts('No');
1622 $retValue = CRM_Utils_System
::formatWikiURL($value);
1634 if ($htmlType == 'Text') {
1635 $retValue = (float)$value;
1639 if ($htmlType == 'Text') {
1649 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1654 if (in_array($htmlType, array(
1655 'Text', 'TextArea'))) {
1659 case 'StateProvince':
1662 switch ($htmlType) {
1663 case 'Multi-Select Country':
1664 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1665 $customData = array();
1666 foreach ($value as $val) {
1668 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1671 $retValue = implode(', ', $customData);
1674 case 'Select Country':
1675 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1678 case 'Select State/Province':
1679 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1682 case 'Multi-Select State/Province':
1683 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1684 $customData = array();
1685 foreach ($value as $val) {
1687 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1690 $retValue = implode(', ', $customData);
1695 case 'Autocomplete-Select':
1696 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1700 case 'AdvMulti-Select':
1701 case 'Multi-Select':
1702 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1703 $customData = array();
1704 foreach ($value as $val) {
1706 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1709 $retValue = implode(', ', $customData);
1724 function removeDuplicates(&$rows) {
1725 if (empty($this->_noRepeats
)) {
1728 $checkList = array();
1730 foreach ($rows as $key => $list) {
1731 foreach ($list as $colName => $colVal) {
1732 if (array_key_exists($colName, $checkList) &&
1733 $checkList[$colName] == $colVal) {
1734 $rows[$key][$colName] = "";
1736 if (in_array($colName, $this->_noRepeats
)) {
1737 $checkList[$colName] = $colVal;
1743 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1744 foreach ($row as $colName => $colVal) {
1745 if (in_array($colName, $fields)) {
1746 $row[$colName] = $row[$colName];
1748 elseif (isset($this->_columnHeaders
[$colName])) {
1750 $row[$colName] = "Subtotal";
1754 unset($row[$colName]);
1760 function grandTotal(&$rows) {
1761 if (!$this->_rollup ||
($this->_rollup
== '') ||
1762 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1766 $lastRow = array_pop($rows);
1768 foreach ($this->_columnHeaders
as $fld => $val) {
1769 if (!in_array($fld, $this->_statFields
)) {
1770 if (!$this->_grandFlag
) {
1771 $lastRow[$fld] = "Grand Total";
1772 $this->_grandFlag
= TRUE;
1775 $lastRow[$fld] = "";
1780 $this->assign('grandStat', $lastRow);
1784 function formatDisplay(&$rows, $pager = TRUE) {
1785 // set pager based on if any limit was applied in the query.
1790 // allow building charts if any
1791 if (!empty($this->_params
['charts']) && !empty($rows)) {
1792 $this->buildChart($rows);
1793 $this->assign('chartEnabled', TRUE);
1794 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1795 $this->assign('chartId', $this->_chartId
);
1798 // unset columns not to be displayed.
1799 foreach ($this->_columnHeaders
as $key => $value) {
1800 if (!empty($value['no_display'])) {
1801 unset($this->_columnHeaders
[$key]);
1805 // unset columns not to be displayed.
1806 if (!empty($rows)) {
1807 foreach ($this->_noDisplay
as $noDisplayField) {
1808 foreach ($rows as $rowNum => $row) {
1809 unset($this->_columnHeaders
[$noDisplayField]);
1814 // build array of section totals
1815 $this->sectionTotals();
1817 // process grand-total row
1818 $this->grandTotal($rows);
1820 // use this method for formatting rows for display purpose.
1821 $this->alterDisplay($rows);
1822 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1824 // use this method for formatting custom rows for display purpose.
1825 $this->alterCustomDataDisplay($rows);
1828 function buildChart(&$rows) {
1829 // override this method for building charts.
1832 // select() method below has been added recently (v3.3), and many of the report templates might
1833 // still be having their own select() method. We should fix them as and when encountered and move
1834 // towards generalizing the select() method below.
1836 $select = $this->_selectAliases
= array();
1838 foreach ($this->_columns
as $tableName => $table) {
1839 if (array_key_exists('fields', $table)) {
1840 foreach ($table['fields'] as $fieldName => $field) {
1841 if ($tableName == 'civicrm_address') {
1842 $this->_addressField
= TRUE;
1844 if ($tableName == 'civicrm_email') {
1845 $this->_emailField
= TRUE;
1847 if ($tableName == 'civicrm_phone') {
1848 $this->_phoneField
= TRUE;
1851 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1853 // 1. In many cases we want select clause to be built in slightly different way
1854 // for a particular field of a particular type.
1855 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1857 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1858 if ($selectClause) {
1859 $select[] = $selectClause;
1863 // include statistics columns only if set
1864 if (!empty($field['statistics'])) {
1865 foreach ($field['statistics'] as $stat => $label) {
1866 $alias = "{$tableName}_{$fieldName}_{$stat}";
1867 switch (strtolower($stat)) {
1870 $select[] = "$stat({$field['dbAlias']}) as $alias";
1871 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1872 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1873 $this->_statFields
[$label] = $alias;
1874 $this->_selectAliases
[] = $alias;
1878 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1879 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1880 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1881 $this->_statFields
[$label] = $alias;
1882 $this->_selectAliases
[] = $alias;
1885 case 'count_distinct':
1886 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1887 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1888 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1889 $this->_statFields
[$label] = $alias;
1890 $this->_selectAliases
[] = $alias;
1894 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1895 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1896 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1897 $this->_statFields
[$label] = $alias;
1898 $this->_selectAliases
[] = $alias;
1904 $alias = "{$tableName}_{$fieldName}";
1905 $select[] = "{$field['dbAlias']} as $alias";
1906 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1907 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1908 $this->_selectAliases
[] = $alias;
1914 // select for group bys
1915 if (array_key_exists('group_bys', $table)) {
1916 foreach ($table['group_bys'] as $fieldName => $field) {
1918 if ($tableName == 'civicrm_address') {
1919 $this->_addressField
= TRUE;
1921 if ($tableName == 'civicrm_email') {
1922 $this->_emailField
= TRUE;
1924 if ($tableName == 'civicrm_phone') {
1925 $this->_phoneField
= TRUE;
1927 // 1. In many cases we want select clause to be built in slightly different way
1928 // for a particular field of a particular type.
1929 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1931 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1932 if ($selectClause) {
1933 $select[] = $selectClause;
1937 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
1938 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1940 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1941 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1942 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1943 $field['title'] = 'Week';
1947 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1948 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1949 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1950 $field['title'] = 'Year';
1954 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1955 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1956 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1957 $field['title'] = 'Month';
1961 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1962 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1963 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1964 $field['title'] = 'Quarter';
1967 // for graphs and charts -
1968 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
1969 $this->_interval
= $field['title'];
1970 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1971 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1972 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1974 // just to make sure these values are transfered to rows.
1975 // since we 'll need them for calculation purpose,
1976 // e.g making subtotals look nicer or graphs
1977 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1978 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1985 $this->_selectClauses
= $select;
1986 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1989 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1994 $this->storeWhereHavingClauseArray();
1996 if (empty($this->_whereClauses
)) {
1997 $this->_where
= "WHERE ( 1 ) ";
1998 $this->_having
= "";
2001 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2004 if ($this->_aclWhere
) {
2005 $this->_where
.= " AND {$this->_aclWhere} ";
2008 if (!empty($this->_havingClauses
)) {
2009 // use this clause to construct group by clause.
2010 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2015 * Store Where clauses into an array - breaking out this step makes
2016 * over-riding more flexible as the clauses can be used in constructing a
2017 * temp table that may not be part of the final where clause or added
2018 * in other functions
2020 function storeWhereHavingClauseArray(){
2021 foreach ($this->_columns
as $tableName => $table) {
2022 if (array_key_exists('filters', $table)) {
2023 foreach ($table['filters'] as $fieldName => $field) {
2024 // respect pseudofield to filter spec so fields can be marked as
2025 // not to be handled here
2026 if(!empty($field['pseudofield'])){
2030 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2031 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2032 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2033 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2034 if (is_array($value) && !empty($value)) {
2035 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2039 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2040 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2041 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2042 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2043 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2044 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2048 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2050 $clause = $this->whereClause($field,
2052 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2053 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2054 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2059 if (!empty($clause)) {
2060 if (!empty($field['having'])) {
2061 $this->_havingClauses
[] = $clause;
2064 $this->_whereClauses
[] = $clause;
2072 function processReportMode() {
2073 $buttonName = $this->controller
->getButtonName();
2075 $output = CRM_Utils_Request
::retrieve(
2078 CRM_Core_DAO
::$_nullObject
2082 CRM_Utils_Request
::retrieve(
2085 CRM_Core_DAO
::$_nullObject
2088 $this->_absoluteUrl
= FALSE;
2090 $this->assign('printOnly', FALSE);
2092 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2093 $this->assign('printOnly', TRUE);
2095 $this->assign('outputMode', 'print');
2096 $this->_outputMode
= 'print';
2097 if ($this->_sendmail
) {
2098 $this->_absoluteUrl
= TRUE;
2101 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2102 $this->assign('printOnly', TRUE);
2104 $this->assign('outputMode', 'pdf');
2105 $this->_outputMode
= 'pdf';
2106 $this->_absoluteUrl
= TRUE;
2108 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2109 $this->assign('printOnly', TRUE);
2111 $this->assign('outputMode', 'csv');
2112 $this->_outputMode
= 'csv';
2113 $this->_absoluteUrl
= TRUE;
2115 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2116 $this->assign('outputMode', 'group');
2117 $this->_outputMode
= 'group';
2119 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2120 $this->assign('outputMode', 'create_report');
2121 $this->_outputMode
= 'create_report';
2124 $this->assign('outputMode', 'html');
2125 $this->_outputMode
= 'html';
2128 // Get today's date to include in printed reports
2130 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2131 $this->assign('reportDate', $reportDate);
2135 function beginPostProcess() {
2136 $this->setParams($this->controller
->exportValues($this->_name
));
2138 if (empty($this->_params
) &&
2141 $this->setParams($this->_formValues
);
2144 // hack to fix params when submitted from dashboard, CRM-8532
2145 // fields array is missing because form building etc is skipped
2146 // in dashboard mode for report
2147 //@todo - this could be done in the dashboard no we have a setter
2148 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2149 $this->setParams($this->_formValues
);
2152 $this->_formValues
= $this->_params
;
2153 if (CRM_Core_Permission
::check('administer Reports') &&
2154 isset($this->_id
) &&
2155 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2156 $this->_chartButtonName
== $this->controller
->getButtonName()
2159 $this->assign('updateReportButton', TRUE);
2161 $this->processReportMode();
2162 $this->beginPostProcessCommon();
2166 * beginPostProcess function run in both report mode and non-report mode (api)
2168 function beginPostProcessCommon() {
2172 function buildQuery($applyLimit = TRUE) {
2175 $this->customDataFrom();
2180 // order_by columns not selected for display need to be included in SELECT
2181 $unselectedSectionColumns = $this->unselectedSectionColumns();
2182 foreach ($unselectedSectionColumns as $alias => $section) {
2183 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2186 if ($applyLimit && empty($this->_params
['charts'])) {
2189 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2191 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2195 function groupBy() {
2196 $groupBys = array();
2197 if (!empty($this->_params
['group_bys']) &&
2198 is_array($this->_params
['group_bys']) &&
2199 !empty($this->_params
['group_bys'])
2201 foreach ($this->_columns
as $tableName => $table) {
2202 if (array_key_exists('group_bys', $table)) {
2203 foreach ($table['group_bys'] as $fieldName => $field) {
2204 if (!empty($this->_params
['group_bys'][$fieldName])) {
2205 $groupBys[] = $field['dbAlias'];
2212 if (!empty($groupBys)) {
2213 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2217 function orderBy() {
2218 $this->_orderBy
= "";
2219 $this->_sections
= array();
2220 $this->storeOrderByArray();
2221 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2222 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2224 $this->assign('sections', $this->_sections
);
2228 * In some cases other functions want to know which fields are selected for ordering by
2229 * Separating this into a separate function allows it to be called separately from constructing
2230 * the order by clause
2232 function storeOrderByArray() {
2233 $orderBys = array();
2235 if (!empty($this->_params
['order_bys']) &&
2236 is_array($this->_params
['order_bys']) &&
2237 !empty($this->_params
['order_bys'])
2240 // Proces order_bys in user-specified order
2241 foreach ($this->_params
['order_bys'] as $orderBy) {
2242 $orderByField = array();
2243 foreach ($this->_columns
as $tableName => $table) {
2244 if (array_key_exists('order_bys', $table)) {
2245 // For DAO columns defined in $this->_columns
2246 $fields = $table['order_bys'];
2248 elseif (array_key_exists('extends', $table)) {
2249 // For custom fields referenced in $this->_customGroupExtends
2250 $fields = CRM_Utils_Array
::value('fields', $table, array());
2252 if (!empty($fields) && is_array($fields)) {
2253 foreach ($fields as $fieldName => $field) {
2254 if ($fieldName == $orderBy['column']) {
2255 $orderByField = array_merge($field, $orderBy);
2256 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2263 if (!empty($orderByField)) {
2264 $this->_orderByFields
[] = $orderByField;
2265 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2267 // Record any section headers for assignment to the template
2268 if (!empty($orderBy['section'])) {
2269 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2270 $this->_sections
[$orderByField['tplField']] = $orderByField;
2276 $this->_orderByArray
= $orderBys;
2278 $this->assign('sections', $this->_sections
);
2281 function unselectedSectionColumns() {
2282 $selectColumns = array();
2283 foreach ($this->_columns
as $tableName => $table) {
2284 if (array_key_exists('fields', $table)) {
2285 foreach ($table['fields'] as $fieldName => $field) {
2286 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2288 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2294 if (is_array($this->_sections
)) {
2295 return array_diff_key($this->_sections
, $selectColumns);
2302 function buildRows($sql, &$rows) {
2303 $dao = CRM_Core_DAO
::executeQuery($sql);
2304 if (!is_array($rows)) {
2308 // use this method to modify $this->_columnHeaders
2309 $this->modifyColumnHeaders();
2311 $unselectedSectionColumns = $this->unselectedSectionColumns();
2313 while ($dao->fetch()) {
2315 foreach ($this->_columnHeaders
as $key => $value) {
2316 if (property_exists($dao, $key)) {
2317 $row[$key] = $dao->$key;
2321 // section headers not selected for display need to be added to row
2322 foreach ($unselectedSectionColumns as $key => $values) {
2323 if (property_exists($dao, $key)) {
2324 $row[$key] = $dao->$key;
2333 * When "order by" fields are marked as sections, this assigns to the template
2334 * an array of total counts for each section. This data is used by the Smarty
2335 * plugin {sectionTotal}
2337 function sectionTotals() {
2339 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2340 if (empty($this->_selectAliases
)) {
2344 if (!empty($this->_sections
)) {
2345 // build the query with no LIMIT clause
2346 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2347 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2349 // pull section aliases out of $this->_sections
2350 $sectionAliases = array_keys($this->_sections
);
2353 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2354 $ifnulls[] = "ifnull($alias, '') as $alias";
2357 /* Group (un-limited) report by all aliases and get counts. This might
2358 * be done more efficiently when the contents of $sql are known, ie. by
2359 * overriding this method in the report class.
2363 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2365 // initialize array of total counts
2367 $dao = CRM_Core_DAO
::executeQuery($query);
2368 while ($dao->fetch()) {
2370 // let $this->_alterDisplay translate any integer ids to human-readable values.
2371 $rows[0] = $dao->toArray();
2372 $this->alterDisplay($rows);
2375 // add totals for all permutations of section values
2378 $aliasCount = count($sectionAliases);
2379 foreach ($sectionAliases as $alias) {
2380 $values[] = $row[$alias];
2381 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2382 if ($i == $aliasCount) {
2383 // the last alias is the lowest-level section header; use count as-is
2384 $totals[$key] = $dao->ct
;
2387 // other aliases are higher level; roll count into their total
2388 $totals[$key] +
= $dao->ct
;
2392 $this->assign('sectionTotals', $totals);
2396 function modifyColumnHeaders() {
2397 // use this method to modify $this->_columnHeaders
2400 function doTemplateAssignment(&$rows) {
2401 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2402 $this->assign_by_ref('rows', $rows);
2403 $this->assign('statistics', $this->statistics($rows));
2406 // override this method to build your own statistics
2407 function statistics(&$rows) {
2408 $statistics = array();
2410 $count = count($rows);
2412 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2416 $this->countStat($statistics, $count);
2418 $this->groupByStat($statistics);
2420 $this->filterStat($statistics);
2425 function countStat(&$statistics, $count) {
2426 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2430 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2431 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2432 'value' => $this->_rowsFound
,
2437 function groupByStat(&$statistics) {
2438 if (!empty($this->_params
['group_bys']) &&
2439 is_array($this->_params
['group_bys']) &&
2440 !empty($this->_params
['group_bys'])
2442 foreach ($this->_columns
as $tableName => $table) {
2443 if (array_key_exists('group_bys', $table)) {
2444 foreach ($table['group_bys'] as $fieldName => $field) {
2445 if (!empty($this->_params
['group_bys'][$fieldName])) {
2446 $combinations[] = $field['title'];
2451 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2452 'value' => implode(' & ', $combinations),
2457 function filterStat(&$statistics) {
2458 foreach ($this->_columns
as $tableName => $table) {
2459 if (array_key_exists('filters', $table)) {
2460 foreach ($table['filters'] as $fieldName => $field) {
2461 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2464 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2465 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2466 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2467 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2468 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2470 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2471 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2473 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2474 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2477 $statistics['filters'][] = array(
2478 'title' => $field['title'],
2479 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2482 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2483 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2485 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2486 $statistics['filters'][] = array(
2487 'title' => $field['title'],
2488 'value' => $pair[$rel],
2493 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2496 $pair = $this->getOperationPair(
2497 CRM_Utils_Array
::value('operatorType', $field),
2500 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2501 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2502 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2503 if (in_array($op, array(
2504 'bw', 'nbw')) && ($min ||
$max)) {
2505 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2507 elseif ($op == 'nll' ||
$op == 'nnll') {
2508 $value = $pair[$op];
2510 elseif (is_array($val) && (!empty($val))) {
2511 $options = CRM_Utils_Array
::value('options', $field, array());
2512 foreach ($val as $key => $valIds) {
2513 if (isset($options[$valIds])) {
2514 $val[$key] = $options[$valIds];
2517 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2518 $val = implode(', ', $val);
2519 $value = "{$pair[$op]} " . $val;
2521 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2522 is_array($field['options']) && !empty($field['options'])
2524 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2527 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2531 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2541 function endPostProcess(&$rows = NULL) {
2542 if ( $this->_storeResultSet
) {
2543 $this->_resultSet
= $rows;
2546 if ($this->_outputMode
== 'print' ||
2547 $this->_outputMode
== 'pdf' ||
2551 $content = $this->compileContent();
2552 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2556 if ($this->_sendmail
) {
2557 $config = CRM_Core_Config
::singleton();
2558 $attachments = array();
2560 if ($this->_outputMode
== 'csv') {
2561 $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'];
2563 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2564 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2565 file_put_contents($csvFullFilename, $csvContent);
2566 $attachments[] = array(
2567 'fullPath' => $csvFullFilename,
2568 'mime_type' => 'text/csv',
2569 'cleanName' => 'CiviReport.csv',
2572 if ($this->_outputMode
== 'pdf') {
2573 // generate PDF content
2574 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2575 file_put_contents($pdfFullFilename,
2576 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2577 TRUE, array('orientation' => 'landscape')
2580 // generate Email Content
2581 $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'];
2583 $attachments[] = array(
2584 'fullPath' => $pdfFullFilename,
2585 'mime_type' => 'application/pdf',
2586 'cleanName' => 'CiviReport.pdf',
2590 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2591 $this->_outputMode
, $attachments
2593 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2596 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2600 elseif ($this->_outputMode
== 'print') {
2604 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2605 $config = CRM_Core_Config
::singleton();
2606 //get chart image name
2607 $chartImg = $this->_chartId
. '.png';
2608 //get image url path
2609 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2610 $uploadUrl .= $chartImg;
2611 //get image doc path to overwrite
2612 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2614 $chart = imagecreatefrompng($uploadUrl);
2615 //convert it into formattd png
2616 header('Content-type: image/png');
2617 //overwrite with same image
2618 imagepng($chart, $uploadImg);
2620 imagedestroy($chart);
2622 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2624 CRM_Utils_System
::civiExit();
2626 elseif ($this->_outputMode
== 'csv') {
2627 CRM_Report_Utils_Report
::export2csv($this, $rows);
2629 elseif ($this->_outputMode
== 'group') {
2630 $group = $this->_params
['groups'];
2631 $this->add2group($group);
2633 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2634 CRM_Report_Form_Instance
::postProcess($this);
2636 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2637 $this->_outputMode
== 'create_report' ) {
2638 $this->_createNew
= TRUE;
2639 CRM_Report_Form_Instance
::postProcess($this);
2643 function storeResultSet() {
2644 $this->_storeResultSet
= TRUE;
2647 function getResultSet() {
2648 return $this->_resultSet
;
2652 * Get Template file name - use default form template if a specific one has not been set up for this report
2655 function getTemplateFileName(){
2656 $defaultTpl = parent
::getTemplateFileName();
2657 $template = CRM_Core_Smarty
::singleton();
2658 if (!$template->template_exists($defaultTpl)) {
2659 $defaultTpl = 'CRM/Report/Form.tpl';
2665 * Compile the report content
2667 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2669 function compileContent(){
2670 $templateFile = $this->getHookedTemplateFileName();
2671 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2675 function postProcess() {
2676 // get ready with post process params
2677 $this->beginPostProcess();
2680 $sql = $this->buildQuery();
2682 // build array of result based on column headers. This method also allows
2683 // modifying column headers before using it to build result set i.e $rows.
2685 $this->buildRows($sql, $rows);
2687 // format result set.
2688 $this->formatDisplay($rows);
2690 // assign variables to templates
2691 $this->doTemplateAssignment($rows);
2693 // do print / pdf / instance stuff if needed
2694 $this->endPostProcess($rows);
2697 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2698 // lets do the pager if in html mode
2699 $this->_limit
= NULL;
2701 // CRM-14115, over-ride row count if rowCount is specified in URL
2702 if ($this->_dashBoardRowCount
) {
2703 $rowCount = $this->_dashBoardRowCount
;
2705 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2706 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2708 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2710 if (!$pageId && !empty($_POST)) {
2711 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2712 $pageId = max((int)@$_POST['crmPID_B'], 1);
2714 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2715 $pageId = max((int)@$_POST['crmPID'], 1);
2717 unset($_POST['crmPID_B'], $_POST['crmPID']);
2720 $pageId = $pageId ?
$pageId : 1;
2721 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2722 $offset = ($pageId - 1) * $rowCount;
2724 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2725 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2727 $this->_limit
= " LIMIT $offset, $rowCount";
2728 return array($offset, $rowCount);
2730 if($this->_limitValue
) {
2731 if($this->_offsetValue
) {
2732 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2735 $this->_limit
= " LIMIT " . $this->_limitValue
;
2740 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2742 // CRM-14115, over-ride row count if rowCount is specified in URL
2743 if ($this->_dashBoardRowCount
) {
2744 $rowCount = $this->_dashBoardRowCount
;
2747 if ($this->_limit
&& ($this->_limit
!= '')) {
2748 $sql = "SELECT FOUND_ROWS();";
2749 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2751 'total' => $this->_rowsFound
,
2752 'rowCount' => $rowCount,
2753 'status' => ts('Records') . ' %%StatusMessage%%',
2754 'buttonBottom' => 'PagerBottomButton',
2755 'buttonTop' => 'PagerTopButton',
2756 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2759 $pager = new CRM_Utils_Pager($params);
2760 $this->assign_by_ref('pager', $pager);
2761 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2765 function whereGroupClause($field, $value, $op) {
2767 $smartGroupQuery = "";
2769 $group = new CRM_Contact_DAO_Group();
2770 $group->is_active
= 1;
2772 $smartGroups = array();
2773 while ($group->fetch()) {
2774 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2775 $smartGroups[] = $group->id
;
2779 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2781 $smartGroupQuery = '';
2782 if (!empty($smartGroups)) {
2783 $smartGroups = implode(',', $smartGroups);
2784 $smartGroupQuery = " UNION DISTINCT
2785 SELECT DISTINCT smartgroup_contact.contact_id
2786 FROM civicrm_group_contact_cache smartgroup_contact
2787 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2790 $sqlOp = $this->getSQLOperator($op);
2791 if (!is_array($value)) {
2792 $value = array($value);
2794 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2796 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2797 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2798 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2799 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2800 {$smartGroupQuery} ) ";
2803 function whereTagClause($field, $value, $op) {
2804 // not using left join in query because if any contact
2805 // belongs to more than one tag, results duplicate
2807 $sqlOp = $this->getSQLOperator($op);
2808 if (!is_array($value)) {
2809 $value = array($value);
2811 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2813 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2814 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2815 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2816 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2819 function buildACLClause($tableAlias = 'contact_a') {
2820 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2823 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2824 if (empty($this->_customGroupExtends
)) {
2827 if (!is_array($this->_customGroupExtends
)) {
2828 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2830 $customGroupWhere = '';
2831 if (!empty($permCustomGroupIds)) {
2832 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2835 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2836 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2837 FROM civicrm_custom_group cg
2838 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2839 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2841 cg.is_active = 1 AND
2842 cf.is_active = 1 AND
2843 cf.is_searchable = 1
2844 ORDER BY cg.weight, cf.weight";
2845 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2848 while ($customDAO->fetch()) {
2849 if ($customDAO->table_name
!= $curTable) {
2850 $curTable = $customDAO->table_name
;
2851 $curFields = $curFilters = array();
2854 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2855 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2856 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2857 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2860 'fields', 'filters', 'group_bys') as $colKey) {
2861 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2862 $this->_columns
[$curTable][$colKey] = array();
2866 $fieldName = 'custom_' . $customDAO->cf_id
;
2869 // this makes aliasing work in favor
2870 $curFields[$fieldName] = array(
2871 'name' => $customDAO->column_name
,
2872 'title' => $customDAO->label
,
2873 'dataType' => $customDAO->data_type
,
2874 'htmlType' => $customDAO->html_type
,
2877 if ($this->_customGroupFilters
) {
2878 // this makes aliasing work in favor
2879 $curFilters[$fieldName] = array(
2880 'name' => $customDAO->column_name
,
2881 'title' => $customDAO->label
,
2882 'dataType' => $customDAO->data_type
,
2883 'htmlType' => $customDAO->html_type
,
2887 switch ($customDAO->data_type
) {
2890 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2891 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2892 // CRM-6946, show time part for datetime date fields
2893 if ($customDAO->time_format
) {
2894 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2899 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2900 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2904 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2908 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2909 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2913 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2914 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2918 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2919 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2923 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2925 if (!empty($customDAO->option_group_id
)) {
2926 if (in_array($customDAO->html_type
, array(
2927 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2928 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2931 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2933 if ($this->_customGroupFilters
) {
2934 $curFilters[$fieldName]['options'] = array();
2935 $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')));
2936 while ($ogDAO->fetch()) {
2937 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2943 case 'StateProvince':
2944 if (in_array($customDAO->html_type
, array(
2945 'Multi-Select State/Province'))) {
2946 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2949 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2951 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2955 if (in_array($customDAO->html_type
, array(
2956 'Multi-Select Country'))) {
2957 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2960 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2962 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2965 case 'ContactReference':
2966 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2967 $curFilters[$fieldName]['name'] = 'display_name';
2968 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2970 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2971 $curFields[$fieldName]['name'] = 'display_name';
2972 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2976 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2977 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2980 if (!array_key_exists('type', $curFields[$fieldName])) {
2981 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2985 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2987 if ($this->_customGroupFilters
) {
2988 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2990 if ($this->_customGroupGroupBy
) {
2991 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2996 function customDataFrom() {
2997 if (empty($this->_customGroupExtends
)) {
3000 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3002 foreach ($this->_columns
as $table => $prop) {
3003 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
3004 $extendsTable = $mapper[$prop['extends']];
3006 // check field is in params
3007 if (!$this->isFieldSelected($prop)) {
3010 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3012 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3014 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3015 // handle for ContactReference
3016 if (array_key_exists('fields', $prop)) {
3017 foreach ($prop['fields'] as $fieldName => $field) {
3018 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
3019 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3021 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3029 function isFieldSelected($prop) {
3034 if (!empty($this->_params
['fields'])) {
3035 foreach (array_keys($prop['fields']) as $fieldAlias) {
3036 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3037 if ($customFieldId) {
3038 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3042 //might be survey response field.
3043 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3050 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3051 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3052 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3058 if (!empty($this->_params
['order_bys'])) {
3059 foreach (array_keys($prop['fields']) as $fieldAlias) {
3060 foreach ($this->_params
['order_bys'] as $orderBy) {
3061 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3068 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3069 foreach ($prop['filters'] as $fieldAlias => $val) {
3071 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3072 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3073 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3074 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3080 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3081 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3092 * Check for empty order_by configurations and remove them; also set
3093 * template to hide them.
3095 function preProcessOrderBy(&$formValues) {
3096 // Object to show/hide form elements
3097 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3099 $_showHide->addShow('optionField_1');
3101 // Cycle through order_by options; skip any empty ones, and hide them as well
3104 if (!empty($formValues['order_bys'])) {
3105 foreach ($formValues['order_bys'] as $order_by) {
3106 if ($order_by['column'] && $order_by['column'] != '-') {
3107 $_showHide->addShow('optionField_' . $n);
3108 $orderBys[$n] = $order_by;
3113 for ($i = $n; $i <= 5; $i++
) {
3115 $_showHide->addHide('optionField_' . $i);
3119 // overwrite order_by options with modified values
3120 if (!empty($orderBys)) {
3121 $formValues['order_bys'] = $orderBys;
3124 $formValues['order_bys'] = array(1 => array('column' => '-'));
3127 // assign show/hide data to template
3128 $_showHide->addToTemplate();
3132 * Does table name have columns in SELECT clause?
3134 * @param string $tableName Name of table (index of $this->_columns array)
3138 function isTableSelected($tableName) {
3139 return in_array($tableName, $this->selectedTables());
3143 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3144 * (building the array if it's unset)
3146 * @return Array $this->_selectedTables
3148 function selectedTables() {
3149 if (!$this->_selectedTables
) {
3150 $orderByColumns = array();
3151 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3152 foreach ($this->_params
['order_bys'] as $orderBy) {
3153 $orderByColumns[] = $orderBy['column'];
3157 foreach ($this->_columns
as $tableName => $table) {
3158 if (array_key_exists('fields', $table)) {
3159 foreach ($table['fields'] as $fieldName => $field) {
3160 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3161 $this->_selectedTables
[] = $tableName;
3166 if (array_key_exists('order_bys', $table)) {
3167 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3168 if (in_array($orderByName, $orderByColumns)) {
3169 $this->_selectedTables
[] = $tableName;
3174 if (array_key_exists('filters', $table)) {
3175 foreach ($table['filters'] as $filterName => $filter) {
3176 if (!empty($this->_params
["{$filterName}_value"]) ||
3177 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3178 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3180 $this->_selectedTables
[] = $tableName;
3187 return $this->_selectedTables
;
3191 * @deprecated - use getAddressColumns which is a more accurate description
3192 * and also accepts an array of options rather than a long list
3194 * function for adding address fields to construct function in reports
3196 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3197 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3198 * @param bool $filters
3199 * @param array $defaults
3201 * @return array address fields for construct clause
3203 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3204 'country_id' => TRUE)) {
3205 $addressFields = array(
3206 'civicrm_address' =>
3208 'dao' => 'CRM_Core_DAO_Address',
3212 array('title' => ts('Address Name'),
3213 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3216 array('title' => ts('Street Address'),
3217 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3219 'supplemental_address_1' =>
3220 array('title' => ts('Supplementary Address Field 1'),
3221 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3223 'supplemental_address_2' =>
3224 array('title' => ts('Supplementary Address Field 2'),
3225 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3229 'name' => 'street_number',
3230 'title' => ts('Street Number'),
3232 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3236 'name' => 'street_name',
3237 'title' => ts('Street Name'),
3239 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3243 'name' => 'street_unit',
3244 'title' => ts('Street Unit'),
3246 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3249 array('title' => ts('City'),
3250 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3253 array('title' => ts('Postal Code'),
3254 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3256 'postal_code_suffix' =>
3257 array('title' => ts('Postal Code Suffix'),
3258 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3261 array('title' => ts('County'),
3262 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3264 'state_province_id' =>
3265 array('title' => ts('State/Province'),
3266 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3269 array('title' => ts('Country'),
3270 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3273 'grouping' => 'location-fields',
3278 $addressFields['civicrm_address']['filters'] = array(
3279 'street_number' => array('title' => ts('Street Number'),
3281 'name' => 'street_number',
3283 'street_name' => array('title' => ts('Street Name'),
3284 'name' => 'street_name',
3285 'operator' => 'like',
3287 'postal_code' => array('title' => ts('Postal Code'),
3289 'name' => 'postal_code',
3291 'city' => array('title' => ts('City'),
3292 'operator' => 'like',
3295 'county_id' => array(
3296 'name' => 'county_id',
3297 'title' => ts('County'),
3298 'type' => CRM_Utils_Type
::T_INT
,
3300 CRM_Report_Form
::OP_MULTISELECT
,
3302 CRM_Core_PseudoConstant
::county(),
3304 'state_province_id' => array(
3305 'name' => 'state_province_id',
3306 'title' => ts('State/Province'),
3307 'type' => CRM_Utils_Type
::T_INT
,
3309 CRM_Report_Form
::OP_MULTISELECT
,
3311 CRM_Core_PseudoConstant
::stateProvince(),
3313 'country_id' => array(
3314 'name' => 'country_id',
3315 'title' => ts('Country'),
3316 'type' => CRM_Utils_Type
::T_INT
,
3318 CRM_Report_Form
::OP_MULTISELECT
,
3320 CRM_Core_PseudoConstant
::country(),
3326 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3327 'street_number' => array('title' => 'Odd / Even Street Number'),
3328 'street_address' => NULL,
3330 'postal_code' => NULL,
3335 $addressFields['civicrm_address']['group_bys'] = array(
3336 'street_address' => NULL,
3338 'postal_code' => NULL,
3339 'state_province_id' =>
3340 array('title' => ts('State/Province'),
3343 array('title' => ts('Country'),
3346 array('title' => ts('County'),
3350 return $addressFields;
3354 * Do AlterDisplay processing on Address Fields
3356 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3357 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3358 $entryFound = FALSE;
3360 if (array_key_exists('civicrm_address_country_id', $row)) {
3361 if ($value = $row['civicrm_address_country_id']) {
3362 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3363 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3364 "reset=1&force=1&{$criteriaQueryParams}&" .
3365 "country_id_op=in&country_id_value={$value}",
3366 $this->_absoluteUrl
, $this->_id
3368 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3369 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3376 if (array_key_exists('civicrm_address_county_id', $row)) {
3377 if ($value = $row['civicrm_address_county_id']) {
3378 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3379 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3380 "reset=1&force=1&{$criteriaQueryParams}&" .
3381 "county_id_op=in&county_id_value={$value}",
3382 $this->_absoluteUrl
, $this->_id
3384 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3385 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3391 // handle state province
3392 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3393 if ($value = $row['civicrm_address_state_province_id']) {
3394 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3396 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3397 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3398 $this->_absoluteUrl
, $this->_id
3400 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3401 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3412 * Adjusts dates passed in to YEAR() for fiscal year.
3414 function fiscalYearOffset($fieldName) {
3415 $config = CRM_Core_Config
::singleton();
3416 $fy = $config->fiscalYearStart
;
3417 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3418 return "YEAR( $fieldName )";
3420 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3424 * Add Address into From Table if required
3426 function addAddressFromClause() {
3427 // include address field if address column is to be included
3428 if ((isset($this->_addressField
) &&
3429 $this->_addressField
3431 $this->isTableSelected('civicrm_address')
3434 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3435 ON ({$this->_aliases['civicrm_contact']}.id =
3436 {$this->_aliases['civicrm_address']}.contact_id) AND
3437 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3442 * Add Phone into From Table if required
3444 function addPhoneFromClause() {
3445 // include address field if address column is to be included
3446 if ($this->isTableSelected('civicrm_phone')
3449 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3450 ON ({$this->_aliases['civicrm_contact']}.id =
3451 {$this->_aliases['civicrm_phone']}.contact_id) AND
3452 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3457 * Get phone columns to add to array
3458 * @param array $options
3459 * - prefix Prefix to add to table (in case of more than one instance of the table)
3460 * - prefix_label Label to give columns from this phone table instance
3461 * @return array phone columns definition
3463 function getPhoneColumns($options = array()){
3464 $defaultOptions = array(
3466 'prefix_label' => '',
3469 $options = array_merge($defaultOptions,$options);
3472 $options['prefix'] . 'civicrm_phone' => array(
3473 'dao' => 'CRM_Core_DAO_Phone',
3475 $options['prefix'] . 'phone' => array(
3476 'title' => ts($options['prefix_label'] . 'Phone'),
3486 * Get address columns to add to array
3487 * @param array $options
3488 * - prefix Prefix to add to table (in case of more than one instance of the table)
3489 * - prefix_label Label to give columns from this address table instance
3490 * @return array address columns definition
3492 function getAddressColumns($options = array()){
3493 $defaultOptions = array(
3495 'prefix_label' => '',
3499 'defaults' => array(
3502 $options = array_merge($defaultOptions,$options);
3503 return $this->addAddressFields(
3504 $options['group_by'],
3505 $options['order_by'],
3506 $options['filters'],
3507 $options['defaults']
3512 function add2group($groupID) {
3513 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3514 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3515 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3517 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3518 $dao = CRM_Core_DAO
::executeQuery($sql);
3520 $contact_ids = array();
3521 // Add resulting contacts to group
3522 while ($dao->fetch()) {
3523 if ($dao->addtogroup_contact_id
) {
3524 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3528 if ( !empty($contact_ids) ) {
3529 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3530 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3533 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3538 /* function used for showing charts on print screen */
3539 static function uploadChartImage() {
3540 // upload strictly for '.png' images
3541 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3542 if (preg_match('/\.png$/', $name)) {
3544 // POST data is usually string data, but we are passing a RAW .png
3545 // so PHP is a bit confused and $_POST is empty. But it has saved
3546 // the raw bits into $HTTP_RAW_POST_DATA
3548 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3550 // prepare the directory
3551 $config = CRM_Core_Config
::singleton();
3552 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3553 if (!file_exists($defaultPath)) {
3554 mkdir($defaultPath, 0777, TRUE);
3557 // full path to the saved image including filename
3558 $destination = $defaultPath . $name;
3561 $jfh = fopen($destination, 'w') or die("can't open file");
3562 fwrite($jfh, $httpRawPostData);
3564 CRM_Utils_System
::civiExit();