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();
636 * @param bool $freeze
640 function setDefaultValues($freeze = TRUE) {
641 $freezeGroup = array();
643 // FIXME: generalizing form field naming conventions would reduce
644 // lots of lines below.
645 foreach ($this->_columns
as $tableName => $table) {
646 if (array_key_exists('fields', $table)) {
647 foreach ($table['fields'] as $fieldName => $field) {
648 if (empty($field['no_display'])) {
649 if (isset($field['required'])) {
651 $this->_defaults
['fields'][$fieldName] = 1;
654 // find element object, so that we could use quickform's freeze method
655 // for required elements
656 $obj = $this->getElementFromGroup("fields", $fieldName);
658 $freezeGroup[] = $obj;
662 elseif (isset($field['default'])) {
663 $this->_defaults
['fields'][$fieldName] = $field['default'];
669 if (array_key_exists('group_bys', $table)) {
670 foreach ($table['group_bys'] as $fieldName => $field) {
671 if (isset($field['default'])) {
672 if (!empty($field['frequency'])) {
673 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
675 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
679 if (array_key_exists('filters', $table)) {
680 foreach ($table['filters'] as $fieldName => $field) {
681 if (isset($field['default'])) {
682 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
683 if(is_array($field['default'])){
684 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
685 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
686 $this->_defaults
["{$fieldName}_relative"] = 0;
689 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
693 $this->_defaults
["{$fieldName}_value"] = $field['default'];
696 //assign default value as "in" for multiselect
697 //operator, To freeze the select element
698 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT
) {
699 $this->_defaults
["{$fieldName}_op"] = 'in';
701 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
) {
702 $this->_defaults
["{$fieldName}_op"] = 'mhas';
704 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
705 $this->_defaults
["{$fieldName}_op"] = $op;
711 array_key_exists('order_bys', $table) &&
712 is_array($table['order_bys'])
714 if (!array_key_exists('order_bys', $this->_defaults
)) {
715 $this->_defaults
['order_bys'] = array();
717 foreach ($table['order_bys'] as $fieldName => $field) {
718 if (!empty($field['default']) ||
!empty($field['default_order']) ||
719 CRM_Utils_Array
::value('default_is_section', $field) ||
!empty($field['default_weight'])) {
721 'column' => $fieldName,
722 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
723 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
726 if (!empty($field['default_weight'])) {
727 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
730 array_unshift($this->_defaults
['order_bys'], $order_by);
736 foreach ($this->_options
as $fieldName => $field) {
737 if (isset($field['default'])) {
738 $this->_defaults
['options'][$fieldName] = $field['default'];
743 if (!empty($this->_submitValues
)) {
744 $this->preProcessOrderBy($this->_submitValues
);
747 $this->preProcessOrderBy($this->_defaults
);
750 // lets finish freezing task here itself
751 if (!empty($freezeGroup)) {
752 foreach ($freezeGroup as $elem) {
757 if ($this->_formValues
) {
758 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
761 if ($this->_instanceValues
) {
762 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
765 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
767 return $this->_defaults
;
772 * @param $grpFieldName
776 function getElementFromGroup($group, $grpFieldName) {
777 $eleObj = $this->getElement($group);
778 foreach ($eleObj->_elements
as $index => $obj) {
779 if ($grpFieldName == $obj->_attributes
['name']) {
787 * Setter for $_params
788 * @param array $params
790 function setParams($params) {
791 $this->_params
= $params;
799 * @internal param int $id
801 function setID($instanceid) {
802 $this->_id
= $instanceid;
808 * @internal param bool $force
810 function setForce($isForce) {
811 $this->_force
= $isForce;
815 * Setter for $_limitValue
816 * @param number $_limitValue
818 function setLimitValue($_limitValue) {
819 $this->_limitValue
= $_limitValue;
823 * Setter for $_offsetValue
824 * @param number $_offsetValue
826 function setOffsetValue($_offsetValue) {
827 $this->_offsetValue
= $_offsetValue;
831 * Getter for $_defaultValues
832 * @return array $_defaultValues
834 function getDefaultValues() {
835 return $this->_defaults
;
838 function addColumns() {
841 foreach ($this->_columns
as $tableName => $table) {
842 if (array_key_exists('fields', $table)) {
843 foreach ($table['fields'] as $fieldName => $field) {
845 if (empty($field['no_display'])) {
846 foreach ( array('table', 'field') as $var) {
847 if (!empty($
{$var}['grouping'])) {
848 if (!is_array($
{$var}['grouping'])) {
849 $tableName = $
{$var}['grouping'];
851 $tableName = array_keys($
{$var}['grouping']);
852 $tableName = $tableName[0];
853 $groupTitle = array_values($
{$var}['grouping']);
854 $groupTitle = $groupTitle[0];
859 if (!$groupTitle && isset($table['group_title'])) {
860 $groupTitle = $table['group_title'];
863 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
864 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
865 $colGroups[$tableName]['group_title'] = $groupTitle;
868 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
874 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
875 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
877 $this->assign('colGroups', $colGroups);
880 function addFilters() {
883 foreach ($this->_filters
as $table => $attributes) {
884 foreach ($attributes as $fieldName => $field) {
885 // get ready with option value pair
886 // @ 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
888 $operations = $this->getOperationPair(
889 CRM_Utils_Array
::value('operatorType', $field),
892 $filters[$table][$fieldName] = $field;
894 switch (CRM_Utils_Array
::value('operatorType', $field)) {
895 case CRM_Report_Form
::OP_MONTH
:
896 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
897 // If there's no option list for this filter, define one.
898 $field['options'] = array(
907 9 => ts('September'),
909 11 => ts('November'),
910 12 => ts('December'),
912 // Add this option list to this column _columns. This is
913 // required so that filter statistics show properly.
914 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
916 case CRM_Report_Form
::OP_MULTISELECT
:
917 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
918 // assume a multi-select field
919 if (!empty($field['options']) ||
$fieldName == 'state_province_id' ||
$fieldName == 'county_id') {
920 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
921 if (count($operations) <= 1) {
924 if ($fieldName == 'state_province_id' ||
$fieldName == 'county_id') {
925 $this->addChainSelect($fieldName . '_value', array('multiple' => TRUE, 'label' => NULL));
928 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
929 'style' => 'min-width:250px',
930 'class' => 'crm-select2',
932 'placeholder' => ts('- select -'),
938 case CRM_Report_Form
::OP_SELECT
:
939 // assume a select field
940 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
941 if (!empty($field['options']))
942 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
945 case CRM_Report_Form
::OP_DATE
:
946 // build datetime fields
947 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
951 case CRM_Report_Form
::OP_DATETIME
:
952 // build datetime fields
953 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
957 case CRM_Report_Form
::OP_INT
:
958 case CRM_Report_Form
::OP_FLOAT
:
959 // and a min value input box
960 $this->add('text', "{$fieldName}_min", ts('Min'));
961 // and a max value input box
962 $this->add('text', "{$fieldName}_max", ts('Max'));
964 // default type is string
965 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
966 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
968 // we need text box for value input
969 $this->add('text', "{$fieldName}_value", NULL);
974 $this->assign('filters', $filters);
977 function addOptions() {
978 if (!empty($this->_options
)) {
979 // FIXME: For now lets build all elements as checkboxes.
980 // Once we clear with the format we can build elements based on type
983 foreach ($this->_options
as $fieldName => $field) {
984 if ($field['type'] == 'select') {
985 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
987 else if ($field['type'] == 'checkbox') {
988 $options[$field['title']] = $fieldName;
989 $this->addCheckBox($fieldName, NULL,
991 NULL, NULL, NULL, $this->_fourColumnAttribute
996 $this->assign('otherOptions', $this->_options
);
999 function addChartOptions() {
1000 if (!empty($this->_charts
)) {
1001 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
1002 $this->assign('charts', $this->_charts
);
1003 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1007 function addGroupBys() {
1008 $options = $freqElements = array();
1010 foreach ($this->_columns
as $tableName => $table) {
1011 if (array_key_exists('group_bys', $table)) {
1012 foreach ($table['group_bys'] as $fieldName => $field) {
1013 if (!empty($field)) {
1014 $options[$field['title']] = $fieldName;
1015 if (!empty($field['frequency'])) {
1016 $freqElements[$field['title']] = $fieldName;
1022 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1023 NULL, NULL, NULL, $this->_fourColumnAttribute
1025 $this->assign('groupByElements', $options);
1027 foreach ($freqElements as $name) {
1028 $this->addElement('select', "group_bys_freq[$name]",
1029 ts('Frequency'), $this->_groupByDateFreq
1034 function addOrderBys() {
1036 foreach ($this->_columns
as $tableName => $table) {
1038 // Report developer may define any column to order by; include these as order-by options
1039 if (array_key_exists('order_bys', $table)) {
1040 foreach ($table['order_bys'] as $fieldName => $field) {
1041 if (!empty($field)) {
1042 $options[$fieldName] = $field['title'];
1047 /* Add searchable custom fields as order-by options, if so requested
1048 * (These are already indexed, so allowing to order on them is cheap.)
1052 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1053 foreach ($table['fields'] as $fieldName => $field) {
1054 if (empty($field['no_display'])) {
1055 $options[$fieldName] = $field['title'];
1063 $this->assign('orderByOptions', $options);
1065 if (!empty($options)) {
1067 '-' => ' - none - ') +
$options;
1068 for ($i = 1; $i <= 5; $i++
) {
1069 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1070 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1071 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1072 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1077 function buildInstanceAndButtons() {
1078 CRM_Report_Form_Instance
::buildForm($this);
1080 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1082 $this->addElement('submit', $this->_instanceButtonName
, $label);
1083 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1084 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1087 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1089 if ($this->_instanceForm
) {
1090 $this->assign('instanceForm', TRUE);
1093 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1094 $this->addElement('submit', $this->_printButtonName
, $label);
1096 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1097 $this->addElement('submit', $this->_pdfButtonName
, $label);
1099 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1101 if ($this->_csvSupported
) {
1102 $this->addElement('submit', $this->_csvButtonName
, $label);
1105 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1106 $this->addElement('select', 'groups', ts('Group'),
1107 array('' => ts('Add Contacts to Group')) + CRM_Core_PseudoConstant
::nestedGroup(),
1108 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1110 $this->assign('group', TRUE);
1113 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1115 $this->addChartOptions();
1116 $this->addButtons(array(
1119 'name' => ts('Preview Report'),
1120 'isDefault' => TRUE,
1126 function buildQuickForm() {
1127 $this->addColumns();
1129 $this->addFilters();
1131 $this->addOptions();
1133 $this->addGroupBys();
1135 $this->addOrderBys();
1137 $this->buildInstanceAndButtons();
1139 //add form rule for report
1140 if (is_callable(array(
1141 $this, 'formRule'))) {
1142 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1146 // a formrule function to ensure that fields selected in group_by
1147 // (if any) should only be the ones present in display/select fields criteria;
1148 // note: works if and only if any custom field selected in group_by.
1151 * @param array $ignoreFields
1155 function customDataFormRule($fields, $ignoreFields = array( )) {
1157 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1158 foreach ($this->_columns
as $tableName => $table) {
1159 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1160 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1161 if (array_key_exists($fieldName, $fields['group_bys']) &&
1162 !array_key_exists($fieldName, $fields['fields'])
1164 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1166 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1167 foreach ($fields['fields'] as $fld => $val) {
1168 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1169 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1180 // Note: $fieldName param allows inheriting class to build operationPairs
1181 // specific to a field.
1183 * @param string $type
1184 * @param null $fieldName
1188 function getOperationPair($type = "string", $fieldName = NULL) {
1189 // FIXME: At some point we should move these key-val pairs
1190 // to option_group and option_value table.
1192 case CRM_Report_Form
::OP_INT
:
1193 case CRM_Report_Form
::OP_FLOAT
:
1195 'lte' => ts('Is less than or equal to'),
1196 'gte' => ts('Is greater than or equal to'),
1197 'bw' => ts('Is between'),
1198 'eq' => ts('Is equal to'),
1199 'lt' => ts('Is less than'),
1200 'gt' => ts('Is greater than'),
1201 'neq' => ts('Is not equal to'),
1202 'nbw' => ts('Is not between'),
1203 'nll' => ts('Is empty (Null)'),
1204 'nnll' => ts('Is not empty (Null)'),
1208 case CRM_Report_Form
::OP_SELECT
:
1210 'eq' => ts('Is equal to'),
1213 case CRM_Report_Form
::OP_MONTH
:
1214 case CRM_Report_Form
::OP_MULTISELECT
:
1216 'in' => ts('Is one of'),
1217 'notin' => ts('Is not one of'),
1221 case CRM_Report_Form
::OP_DATE
:
1223 'nll' => ts('Is empty (Null)'),
1224 'nnll' => ts('Is not empty (Null)'),
1228 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1229 // use this operator for the values, concatenated with separator. For e.g if
1230 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1232 'mhas' => ts('Is one of'),
1233 'mnot' => ts('Is not one of'),
1239 'has' => ts('Contains'),
1240 'sw' => ts('Starts with'),
1241 'ew' => ts('Ends with'),
1242 'nhas' => ts('Does not contain'),
1243 'eq' => ts('Is equal to'),
1244 'neq' => ts('Is not equal to'),
1245 'nll' => ts('Is empty (Null)'),
1246 'nnll' => ts('Is not empty (Null)'),
1251 function buildTagFilter() {
1252 $contactTags = CRM_Core_BAO_Tag
::getTags();
1253 if (!empty($contactTags)) {
1254 $this->_columns
['civicrm_tag'] = array(
1255 'dao' => 'CRM_Core_DAO_Tag',
1261 'title' => ts('Tag'),
1263 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1264 'options' => $contactTags,
1272 * Adds group filters to _columns (called from _Constuct
1274 function buildGroupFilter() {
1275 $this->_columns
['civicrm_group']['filters'] = array(
1278 'name' => 'group_id',
1279 'title' => ts('Group'),
1280 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1282 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1285 if (empty($this->_columns
['civicrm_group']['dao'])) {
1286 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1288 if (empty($this->_columns
['civicrm_group']['alias'])) {
1289 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1294 * @param string $operator
1298 function getSQLOperator($operator = "like") {
1299 switch ($operator) {
1332 return 'IS NOT NULL';
1347 * @return null|string
1349 function whereClause(&$field, $op,
1353 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1359 if (($min !== NULL && strlen($min) > 0) ||
1360 ($max !== NULL && strlen($max) > 0)
1362 $min = CRM_Utils_Type
::escape($min, $type);
1363 $max = CRM_Utils_Type
::escape($max, $type);
1367 $clauses[] = "( {$field['dbAlias']} >= $min )";
1370 $clauses[] = "( {$field['dbAlias']} < $min )";
1375 $clauses[] = "( {$field['dbAlias']} <= $max )";
1378 $clauses[] = "( {$field['dbAlias']} > $max )";
1382 if (!empty($clauses)) {
1384 $clause = implode(' AND ', $clauses);
1387 $clause = implode(' OR ', $clauses);
1395 if ($value !== NULL && strlen($value) > 0) {
1396 $value = CRM_Utils_Type
::escape($value, $type);
1397 if (strpos($value, '%') === FALSE) {
1398 $value = "'%{$value}%'";
1401 $value = "'{$value}'";
1403 $sqlOP = $this->getSQLOperator($op);
1404 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1410 if ($value !== NULL && is_array($value) && count($value) > 0) {
1411 $sqlOP = $this->getSQLOperator($op);
1412 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1413 //cycle through selections and esacape values
1414 foreach ($value as $key => $selection) {
1415 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1417 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1420 // for numerical values
1421 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1423 if ($op == 'notin') {
1424 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1427 $clause = "( " . $clause . " )";
1433 // mhas == multiple has
1434 if ($value !== NULL && count($value) > 0) {
1435 $sqlOP = $this->getSQLOperator($op);
1436 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1441 // mnot == multiple is not one of
1442 if ($value !== NULL && count($value) > 0) {
1443 $sqlOP = $this->getSQLOperator($op);
1444 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1450 if ($value !== NULL && strlen($value) > 0) {
1451 $value = CRM_Utils_Type
::escape($value, $type);
1452 if (strpos($value, '%') === FALSE) {
1454 $value = "'{$value}%'";
1457 $value = "'%{$value}'";
1461 $value = "'{$value}'";
1463 $sqlOP = $this->getSQLOperator($op);
1464 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1470 $sqlOP = $this->getSQLOperator($op);
1471 $clause = "( {$field['dbAlias']} $sqlOP )";
1475 if ($value !== NULL && strlen($value) > 0) {
1476 if (isset($field['clause'])) {
1477 // FIXME: we not doing escape here. Better solution is to use two
1478 // different types - data-type and filter-type
1479 $clause = $field['clause'];
1482 $value = CRM_Utils_Type
::escape($value, $type);
1483 $sqlOP = $this->getSQLOperator($op);
1484 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1485 $value = "'{$value}'";
1487 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1493 if (!empty($field['group']) && $clause) {
1494 $clause = $this->whereGroupClause($field, $value, $op);
1496 elseif (!empty($field['tag']) && $clause) {
1497 // not using left join in query because if any contact
1498 // belongs to more than one tag, results duplicate
1500 $clause = $this->whereTagClause($field, $value, $op);
1502 elseif (!empty($field['membership_org']) && $clause) {
1503 $clause = $this->whereMembershipOrgClause($field, $value, $op);
1505 elseif (!empty($field['membership_type']) && $clause) {
1506 $clause = $this->whereMembershipTypeClause($field, $value, $op);
1517 * @param null $fromTime
1518 * @param null $toTime
1520 * @return null|string
1522 function dateClause($fieldName,
1523 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1526 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1527 $sqlOP = $this->getSQLOperator($relative);
1528 return "( {$fieldName} {$sqlOP} )";
1531 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1534 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1535 $clauses[] = "( {$fieldName} >= $from )";
1539 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1540 $clauses[] = "( {$fieldName} <= {$to} )";
1543 if (!empty($clauses)) {
1544 return implode(' AND ', $clauses);
1550 * @todo - could not find any instances where this is called
1551 * @param unknown_type $relative
1552 * @param String $from
1553 * @param String_type $to
1554 * @return string|NULL
1556 function dateDisplay($relative, $from, $to) {
1557 list($from, $to) = $this->getFromTo($relative, $from, $to);
1560 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1563 $clauses[] = 'Past';
1567 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1570 $clauses[] = 'Today';
1573 if (!empty($clauses)) {
1574 return implode(' - ', $clauses);
1584 * @param null $fromtime
1585 * @param null $totime
1589 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1590 if (empty($totime)) {
1593 //FIX ME not working for relative
1595 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1596 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1597 $from = substr($dateRange['from'], 0, 8);
1598 //Take only Date Part, Sometime Time part is also present in 'to'
1599 $to = substr($dateRange['to'], 0, 8);
1601 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1602 $to = CRM_Utils_Date
::processDate($to, $totime);
1603 return array($from, $to);
1609 function alterDisplay(&$rows) {
1610 // custom code to alter rows
1616 function alterCustomDataDisplay(&$rows) {
1617 // custom code to alter rows having custom values
1618 if (empty($this->_customGroupExtends
)) {
1622 $customFieldIds = array();
1623 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1624 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1625 $customFieldIds[$fieldAlias] = $fieldId;
1628 if (empty($customFieldIds)) {
1632 $customFields = $fieldValueMap = array();
1633 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1635 // skip for type date and ContactReference since date format is already handled
1637 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1638 FROM civicrm_custom_field cf
1639 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1640 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1641 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1642 cg.is_active = 1 AND
1643 cf.is_active = 1 AND
1644 cf.is_searchable = 1 AND
1645 cf.data_type NOT IN ('ContactReference', 'Date') AND
1646 cf.id IN (" . implode(",", $customFieldIds) . ")";
1648 $dao = CRM_Core_DAO
::executeQuery($query);
1649 while ($dao->fetch()) {
1650 foreach ($customFieldCols as $key) {
1651 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1653 if ($dao->option_group_id
) {
1654 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1659 $entryFound = FALSE;
1660 foreach ($rows as $rowNum => $row) {
1661 foreach ($row as $tableCol => $val) {
1662 if (array_key_exists($tableCol, $customFields)) {
1663 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1668 // skip looking further in rows, if first row itself doesn't
1669 // have the column we need
1678 * @param $customField
1679 * @param $fieldValueMap
1681 * @return float|string
1683 function formatCustomValues($value, $customField, $fieldValueMap) {
1684 if (CRM_Utils_System
::isNull($value)) {
1688 $htmlType = $customField['html_type'];
1690 switch ($customField['data_type']) {
1692 if ($value == '1') {
1693 $retValue = ts('Yes');
1696 $retValue = ts('No');
1701 $retValue = CRM_Utils_System
::formatWikiURL($value);
1713 if ($htmlType == 'Text') {
1714 $retValue = (float)$value;
1718 if ($htmlType == 'Text') {
1728 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1733 if (in_array($htmlType, array(
1734 'Text', 'TextArea'))) {
1738 case 'StateProvince':
1741 switch ($htmlType) {
1742 case 'Multi-Select Country':
1743 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1744 $customData = array();
1745 foreach ($value as $val) {
1747 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1750 $retValue = implode(', ', $customData);
1753 case 'Select Country':
1754 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1757 case 'Select State/Province':
1758 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1761 case 'Multi-Select State/Province':
1762 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1763 $customData = array();
1764 foreach ($value as $val) {
1766 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1769 $retValue = implode(', ', $customData);
1774 case 'Autocomplete-Select':
1775 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1779 case 'AdvMulti-Select':
1780 case 'Multi-Select':
1781 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1782 $customData = array();
1783 foreach ($value as $val) {
1785 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1788 $retValue = implode(', ', $customData);
1806 function removeDuplicates(&$rows) {
1807 if (empty($this->_noRepeats
)) {
1810 $checkList = array();
1812 foreach ($rows as $key => $list) {
1813 foreach ($list as $colName => $colVal) {
1814 if (array_key_exists($colName, $checkList) &&
1815 $checkList[$colName] == $colVal) {
1816 $rows[$key][$colName] = "";
1818 if (in_array($colName, $this->_noRepeats
)) {
1819 $checkList[$colName] = $colVal;
1828 * @param bool $subtotal
1830 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1831 foreach ($row as $colName => $colVal) {
1832 if (in_array($colName, $fields)) {
1833 $row[$colName] = $row[$colName];
1835 elseif (isset($this->_columnHeaders
[$colName])) {
1837 $row[$colName] = "Subtotal";
1841 unset($row[$colName]);
1852 function grandTotal(&$rows) {
1853 if (!$this->_rollup ||
($this->_rollup
== '') ||
1854 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1858 $lastRow = array_pop($rows);
1860 foreach ($this->_columnHeaders
as $fld => $val) {
1861 if (!in_array($fld, $this->_statFields
)) {
1862 if (!$this->_grandFlag
) {
1863 $lastRow[$fld] = "Grand Total";
1864 $this->_grandFlag
= TRUE;
1867 $lastRow[$fld] = "";
1872 $this->assign('grandStat', $lastRow);
1878 * @param bool $pager
1880 function formatDisplay(&$rows, $pager = TRUE) {
1881 // set pager based on if any limit was applied in the query.
1886 // allow building charts if any
1887 if (!empty($this->_params
['charts']) && !empty($rows)) {
1888 $this->buildChart($rows);
1889 $this->assign('chartEnabled', TRUE);
1890 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1891 $this->assign('chartId', $this->_chartId
);
1894 // unset columns not to be displayed.
1895 foreach ($this->_columnHeaders
as $key => $value) {
1896 if (!empty($value['no_display'])) {
1897 unset($this->_columnHeaders
[$key]);
1901 // unset columns not to be displayed.
1902 if (!empty($rows)) {
1903 foreach ($this->_noDisplay
as $noDisplayField) {
1904 foreach ($rows as $rowNum => $row) {
1905 unset($this->_columnHeaders
[$noDisplayField]);
1910 // build array of section totals
1911 $this->sectionTotals();
1913 // process grand-total row
1914 $this->grandTotal($rows);
1916 // use this method for formatting rows for display purpose.
1917 $this->alterDisplay($rows);
1918 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1920 // use this method for formatting custom rows for display purpose.
1921 $this->alterCustomDataDisplay($rows);
1927 function buildChart(&$rows) {
1928 // override this method for building charts.
1931 // select() method below has been added recently (v3.3), and many of the report templates might
1932 // still be having their own select() method. We should fix them as and when encountered and move
1933 // towards generalizing the select() method below.
1935 $select = $this->_selectAliases
= array();
1937 foreach ($this->_columns
as $tableName => $table) {
1938 if (array_key_exists('fields', $table)) {
1939 foreach ($table['fields'] as $fieldName => $field) {
1940 if ($tableName == 'civicrm_address') {
1941 $this->_addressField
= TRUE;
1943 if ($tableName == 'civicrm_email') {
1944 $this->_emailField
= TRUE;
1946 if ($tableName == 'civicrm_phone') {
1947 $this->_phoneField
= TRUE;
1950 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1952 // 1. In many cases we want select clause to be built in slightly different way
1953 // for a particular field of a particular type.
1954 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1956 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1957 if ($selectClause) {
1958 $select[] = $selectClause;
1962 // include statistics columns only if set
1963 if (!empty($field['statistics'])) {
1964 foreach ($field['statistics'] as $stat => $label) {
1965 $alias = "{$tableName}_{$fieldName}_{$stat}";
1966 switch (strtolower($stat)) {
1969 $select[] = "$stat({$field['dbAlias']}) as $alias";
1970 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1971 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1972 $this->_statFields
[$label] = $alias;
1973 $this->_selectAliases
[] = $alias;
1977 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1978 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1979 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1980 $this->_statFields
[$label] = $alias;
1981 $this->_selectAliases
[] = $alias;
1984 case 'count_distinct':
1985 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1986 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1987 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1988 $this->_statFields
[$label] = $alias;
1989 $this->_selectAliases
[] = $alias;
1993 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1994 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1995 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1996 $this->_statFields
[$label] = $alias;
1997 $this->_selectAliases
[] = $alias;
2003 $alias = "{$tableName}_{$fieldName}";
2004 $select[] = "{$field['dbAlias']} as $alias";
2005 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2006 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2007 $this->_selectAliases
[] = $alias;
2013 // select for group bys
2014 if (array_key_exists('group_bys', $table)) {
2015 foreach ($table['group_bys'] as $fieldName => $field) {
2017 if ($tableName == 'civicrm_address') {
2018 $this->_addressField
= TRUE;
2020 if ($tableName == 'civicrm_email') {
2021 $this->_emailField
= TRUE;
2023 if ($tableName == 'civicrm_phone') {
2024 $this->_phoneField
= TRUE;
2026 // 1. In many cases we want select clause to be built in slightly different way
2027 // for a particular field of a particular type.
2028 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2030 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2031 if ($selectClause) {
2032 $select[] = $selectClause;
2036 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
2037 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2039 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2040 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2041 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2042 $field['title'] = 'Week';
2046 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2047 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2048 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2049 $field['title'] = 'Year';
2053 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2054 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2055 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2056 $field['title'] = 'Month';
2060 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2061 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2062 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2063 $field['title'] = 'Quarter';
2066 // for graphs and charts -
2067 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2068 $this->_interval
= $field['title'];
2069 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
2070 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2071 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2073 // just to make sure these values are transfered to rows.
2074 // since we 'll need them for calculation purpose,
2075 // e.g making subtotals look nicer or graphs
2076 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2077 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2084 $this->_selectClauses
= $select;
2085 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2096 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2101 $this->storeWhereHavingClauseArray();
2103 if (empty($this->_whereClauses
)) {
2104 $this->_where
= "WHERE ( 1 ) ";
2105 $this->_having
= "";
2108 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2111 if ($this->_aclWhere
) {
2112 $this->_where
.= " AND {$this->_aclWhere} ";
2115 if (!empty($this->_havingClauses
)) {
2116 // use this clause to construct group by clause.
2117 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2122 * Store Where clauses into an array - breaking out this step makes
2123 * over-riding more flexible as the clauses can be used in constructing a
2124 * temp table that may not be part of the final where clause or added
2125 * in other functions
2127 function storeWhereHavingClauseArray(){
2128 foreach ($this->_columns
as $tableName => $table) {
2129 if (array_key_exists('filters', $table)) {
2130 foreach ($table['filters'] as $fieldName => $field) {
2131 // respect pseudofield to filter spec so fields can be marked as
2132 // not to be handled here
2133 if(!empty($field['pseudofield'])){
2137 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2138 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2139 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2140 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2141 if (is_array($value) && !empty($value)) {
2142 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2146 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2147 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2148 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2149 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2150 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2151 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2155 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2157 $clause = $this->whereClause($field,
2159 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2160 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2161 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2166 if (!empty($clause)) {
2167 if (!empty($field['having'])) {
2168 $this->_havingClauses
[] = $clause;
2171 $this->_whereClauses
[] = $clause;
2179 function processReportMode() {
2180 $buttonName = $this->controller
->getButtonName();
2182 $output = CRM_Utils_Request
::retrieve(
2185 CRM_Core_DAO
::$_nullObject
2189 CRM_Utils_Request
::retrieve(
2192 CRM_Core_DAO
::$_nullObject
2195 $this->_absoluteUrl
= FALSE;
2197 $this->assign('printOnly', FALSE);
2199 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2200 $this->assign('printOnly', TRUE);
2202 $this->assign('outputMode', 'print');
2203 $this->_outputMode
= 'print';
2204 if ($this->_sendmail
) {
2205 $this->_absoluteUrl
= TRUE;
2208 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2209 $this->assign('printOnly', TRUE);
2211 $this->assign('outputMode', 'pdf');
2212 $this->_outputMode
= 'pdf';
2213 $this->_absoluteUrl
= TRUE;
2215 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2216 $this->assign('printOnly', TRUE);
2218 $this->assign('outputMode', 'csv');
2219 $this->_outputMode
= 'csv';
2220 $this->_absoluteUrl
= TRUE;
2222 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2223 $this->assign('outputMode', 'group');
2224 $this->_outputMode
= 'group';
2226 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2227 $this->assign('outputMode', 'create_report');
2228 $this->_outputMode
= 'create_report';
2231 $this->assign('outputMode', 'html');
2232 $this->_outputMode
= 'html';
2235 // Get today's date to include in printed reports
2237 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2238 $this->assign('reportDate', $reportDate);
2242 function beginPostProcess() {
2243 $this->setParams($this->controller
->exportValues($this->_name
));
2245 if (empty($this->_params
) &&
2248 $this->setParams($this->_formValues
);
2251 // hack to fix params when submitted from dashboard, CRM-8532
2252 // fields array is missing because form building etc is skipped
2253 // in dashboard mode for report
2254 //@todo - this could be done in the dashboard no we have a setter
2255 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2256 $this->setParams($this->_formValues
);
2259 $this->_formValues
= $this->_params
;
2260 if (CRM_Core_Permission
::check('administer Reports') &&
2261 isset($this->_id
) &&
2262 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2263 $this->_chartButtonName
== $this->controller
->getButtonName()
2266 $this->assign('updateReportButton', TRUE);
2268 $this->processReportMode();
2269 $this->beginPostProcessCommon();
2273 * beginPostProcess function run in both report mode and non-report mode (api)
2275 function beginPostProcessCommon() {
2280 * @param bool $applyLimit
2284 function buildQuery($applyLimit = TRUE) {
2287 $this->customDataFrom();
2292 // order_by columns not selected for display need to be included in SELECT
2293 $unselectedSectionColumns = $this->unselectedSectionColumns();
2294 foreach ($unselectedSectionColumns as $alias => $section) {
2295 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2298 if ($applyLimit && empty($this->_params
['charts'])) {
2301 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2303 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2307 function groupBy() {
2308 $groupBys = array();
2309 if (!empty($this->_params
['group_bys']) &&
2310 is_array($this->_params
['group_bys']) &&
2311 !empty($this->_params
['group_bys'])
2313 foreach ($this->_columns
as $tableName => $table) {
2314 if (array_key_exists('group_bys', $table)) {
2315 foreach ($table['group_bys'] as $fieldName => $field) {
2316 if (!empty($this->_params
['group_bys'][$fieldName])) {
2317 $groupBys[] = $field['dbAlias'];
2324 if (!empty($groupBys)) {
2325 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2329 function orderBy() {
2330 $this->_orderBy
= "";
2331 $this->_sections
= array();
2332 $this->storeOrderByArray();
2333 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2334 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2336 $this->assign('sections', $this->_sections
);
2340 * In some cases other functions want to know which fields are selected for ordering by
2341 * Separating this into a separate function allows it to be called separately from constructing
2342 * the order by clause
2344 function storeOrderByArray() {
2345 $orderBys = array();
2347 if (!empty($this->_params
['order_bys']) &&
2348 is_array($this->_params
['order_bys']) &&
2349 !empty($this->_params
['order_bys'])
2352 // Proces order_bys in user-specified order
2353 foreach ($this->_params
['order_bys'] as $orderBy) {
2354 $orderByField = array();
2355 foreach ($this->_columns
as $tableName => $table) {
2356 if (array_key_exists('order_bys', $table)) {
2357 // For DAO columns defined in $this->_columns
2358 $fields = $table['order_bys'];
2360 elseif (array_key_exists('extends', $table)) {
2361 // For custom fields referenced in $this->_customGroupExtends
2362 $fields = CRM_Utils_Array
::value('fields', $table, array());
2364 if (!empty($fields) && is_array($fields)) {
2365 foreach ($fields as $fieldName => $field) {
2366 if ($fieldName == $orderBy['column']) {
2367 $orderByField = array_merge($field, $orderBy);
2368 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2375 if (!empty($orderByField)) {
2376 $this->_orderByFields
[] = $orderByField;
2377 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2379 // Record any section headers for assignment to the template
2380 if (!empty($orderBy['section'])) {
2381 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2382 $this->_sections
[$orderByField['tplField']] = $orderByField;
2388 $this->_orderByArray
= $orderBys;
2390 $this->assign('sections', $this->_sections
);
2396 function unselectedSectionColumns() {
2397 $selectColumns = array();
2398 foreach ($this->_columns
as $tableName => $table) {
2399 if (array_key_exists('fields', $table)) {
2400 foreach ($table['fields'] as $fieldName => $field) {
2401 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2403 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2409 if (is_array($this->_sections
)) {
2410 return array_diff_key($this->_sections
, $selectColumns);
2421 function buildRows($sql, &$rows) {
2422 $dao = CRM_Core_DAO
::executeQuery($sql);
2423 if (!is_array($rows)) {
2427 // use this method to modify $this->_columnHeaders
2428 $this->modifyColumnHeaders();
2430 $unselectedSectionColumns = $this->unselectedSectionColumns();
2432 while ($dao->fetch()) {
2434 foreach ($this->_columnHeaders
as $key => $value) {
2435 if (property_exists($dao, $key)) {
2436 $row[$key] = $dao->$key;
2440 // section headers not selected for display need to be added to row
2441 foreach ($unselectedSectionColumns as $key => $values) {
2442 if (property_exists($dao, $key)) {
2443 $row[$key] = $dao->$key;
2452 * When "order by" fields are marked as sections, this assigns to the template
2453 * an array of total counts for each section. This data is used by the Smarty
2454 * plugin {sectionTotal}
2456 function sectionTotals() {
2458 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2459 if (empty($this->_selectAliases
)) {
2463 if (!empty($this->_sections
)) {
2464 // build the query with no LIMIT clause
2465 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2466 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2468 // pull section aliases out of $this->_sections
2469 $sectionAliases = array_keys($this->_sections
);
2472 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2473 $ifnulls[] = "ifnull($alias, '') as $alias";
2476 /* Group (un-limited) report by all aliases and get counts. This might
2477 * be done more efficiently when the contents of $sql are known, ie. by
2478 * overriding this method in the report class.
2482 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2484 // initialize array of total counts
2486 $dao = CRM_Core_DAO
::executeQuery($query);
2487 while ($dao->fetch()) {
2489 // let $this->_alterDisplay translate any integer ids to human-readable values.
2490 $rows[0] = $dao->toArray();
2491 $this->alterDisplay($rows);
2494 // add totals for all permutations of section values
2497 $aliasCount = count($sectionAliases);
2498 foreach ($sectionAliases as $alias) {
2499 $values[] = $row[$alias];
2500 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2501 if ($i == $aliasCount) {
2502 // the last alias is the lowest-level section header; use count as-is
2503 $totals[$key] = $dao->ct
;
2506 // other aliases are higher level; roll count into their total
2507 $totals[$key] +
= $dao->ct
;
2511 $this->assign('sectionTotals', $totals);
2515 function modifyColumnHeaders() {
2516 // use this method to modify $this->_columnHeaders
2522 function doTemplateAssignment(&$rows) {
2523 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2524 $this->assign_by_ref('rows', $rows);
2525 $this->assign('statistics', $this->statistics($rows));
2528 // override this method to build your own statistics
2534 function statistics(&$rows) {
2535 $statistics = array();
2537 $count = count($rows);
2539 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2543 $this->countStat($statistics, $count);
2545 $this->groupByStat($statistics);
2547 $this->filterStat($statistics);
2553 * @param $statistics
2556 function countStat(&$statistics, $count) {
2557 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2561 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2562 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2563 'value' => $this->_rowsFound
,
2569 * @param $statistics
2571 function groupByStat(&$statistics) {
2572 if (!empty($this->_params
['group_bys']) &&
2573 is_array($this->_params
['group_bys']) &&
2574 !empty($this->_params
['group_bys'])
2576 foreach ($this->_columns
as $tableName => $table) {
2577 if (array_key_exists('group_bys', $table)) {
2578 foreach ($table['group_bys'] as $fieldName => $field) {
2579 if (!empty($this->_params
['group_bys'][$fieldName])) {
2580 $combinations[] = $field['title'];
2585 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2586 'value' => implode(' & ', $combinations),
2592 * @param $statistics
2594 function filterStat(&$statistics) {
2595 foreach ($this->_columns
as $tableName => $table) {
2596 if (array_key_exists('filters', $table)) {
2597 foreach ($table['filters'] as $fieldName => $field) {
2598 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2601 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2602 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2603 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2604 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2605 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2607 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2608 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2610 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2611 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2614 $statistics['filters'][] = array(
2615 'title' => $field['title'],
2616 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2619 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2620 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2622 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2623 $statistics['filters'][] = array(
2624 'title' => $field['title'],
2625 'value' => $pair[$rel],
2630 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2633 $pair = $this->getOperationPair(
2634 CRM_Utils_Array
::value('operatorType', $field),
2637 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2638 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2639 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2640 if (in_array($op, array(
2641 'bw', 'nbw')) && ($min ||
$max)) {
2642 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2644 elseif ($op == 'nll' ||
$op == 'nnll') {
2645 $value = $pair[$op];
2647 elseif (is_array($val) && (!empty($val))) {
2648 $options = CRM_Utils_Array
::value('options', $field, array());
2649 foreach ($val as $key => $valIds) {
2650 if (isset($options[$valIds])) {
2651 $val[$key] = $options[$valIds];
2654 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2655 $val = implode(', ', $val);
2656 $value = "{$pair[$op]} " . $val;
2658 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2659 is_array($field['options']) && !empty($field['options'])
2661 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2664 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2668 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2681 function endPostProcess(&$rows = NULL) {
2682 if ( $this->_storeResultSet
) {
2683 $this->_resultSet
= $rows;
2686 if ($this->_outputMode
== 'print' ||
2687 $this->_outputMode
== 'pdf' ||
2691 $content = $this->compileContent();
2692 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2696 if ($this->_sendmail
) {
2697 $config = CRM_Core_Config
::singleton();
2698 $attachments = array();
2700 if ($this->_outputMode
== 'csv') {
2701 $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'];
2703 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2704 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2705 file_put_contents($csvFullFilename, $csvContent);
2706 $attachments[] = array(
2707 'fullPath' => $csvFullFilename,
2708 'mime_type' => 'text/csv',
2709 'cleanName' => 'CiviReport.csv',
2712 if ($this->_outputMode
== 'pdf') {
2713 // generate PDF content
2714 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2715 file_put_contents($pdfFullFilename,
2716 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2717 TRUE, array('orientation' => 'landscape')
2720 // generate Email Content
2721 $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'];
2723 $attachments[] = array(
2724 'fullPath' => $pdfFullFilename,
2725 'mime_type' => 'application/pdf',
2726 'cleanName' => 'CiviReport.pdf',
2730 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2731 $this->_outputMode
, $attachments
2733 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2736 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2740 elseif ($this->_outputMode
== 'print') {
2744 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2745 $config = CRM_Core_Config
::singleton();
2746 //get chart image name
2747 $chartImg = $this->_chartId
. '.png';
2748 //get image url path
2749 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2750 $uploadUrl .= $chartImg;
2751 //get image doc path to overwrite
2752 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2754 $chart = imagecreatefrompng($uploadUrl);
2755 //convert it into formattd png
2756 header('Content-type: image/png');
2757 //overwrite with same image
2758 imagepng($chart, $uploadImg);
2760 imagedestroy($chart);
2762 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2764 CRM_Utils_System
::civiExit();
2766 elseif ($this->_outputMode
== 'csv') {
2767 CRM_Report_Utils_Report
::export2csv($this, $rows);
2769 elseif ($this->_outputMode
== 'group') {
2770 $group = $this->_params
['groups'];
2771 $this->add2group($group);
2773 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2774 CRM_Report_Form_Instance
::postProcess($this);
2776 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2777 $this->_outputMode
== 'create_report' ) {
2778 $this->_createNew
= TRUE;
2779 CRM_Report_Form_Instance
::postProcess($this);
2783 function storeResultSet() {
2784 $this->_storeResultSet
= TRUE;
2790 function getResultSet() {
2791 return $this->_resultSet
;
2795 * Get Template file name - use default form template if a specific one has not been set up for this report
2799 * Use the form name to create the tpl file name
2807 function getTemplateFileName(){
2808 $defaultTpl = parent
::getTemplateFileName();
2809 $template = CRM_Core_Smarty
::singleton();
2810 if (!$template->template_exists($defaultTpl)) {
2811 $defaultTpl = 'CRM/Report/Form.tpl';
2817 * Compile the report content
2819 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2824 function compileContent(){
2825 $templateFile = $this->getHookedTemplateFileName();
2826 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2830 function postProcess() {
2831 // get ready with post process params
2832 $this->beginPostProcess();
2835 $sql = $this->buildQuery();
2837 // build array of result based on column headers. This method also allows
2838 // modifying column headers before using it to build result set i.e $rows.
2840 $this->buildRows($sql, $rows);
2842 // format result set.
2843 $this->formatDisplay($rows);
2845 // assign variables to templates
2846 $this->doTemplateAssignment($rows);
2848 // do print / pdf / instance stuff if needed
2849 $this->endPostProcess($rows);
2853 * @param int $rowCount
2855 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2856 // lets do the pager if in html mode
2857 $this->_limit
= NULL;
2859 // CRM-14115, over-ride row count if rowCount is specified in URL
2860 if ($this->_dashBoardRowCount
) {
2861 $rowCount = $this->_dashBoardRowCount
;
2863 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2864 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2866 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2868 if (!$pageId && !empty($_POST)) {
2869 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2870 $pageId = max((int)@$_POST['crmPID_B'], 1);
2872 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2873 $pageId = max((int)@$_POST['crmPID'], 1);
2875 unset($_POST['crmPID_B'], $_POST['crmPID']);
2878 $pageId = $pageId ?
$pageId : 1;
2879 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2880 $offset = ($pageId - 1) * $rowCount;
2882 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2883 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2885 $this->_limit
= " LIMIT $offset, $rowCount";
2886 return array($offset, $rowCount);
2888 if($this->_limitValue
) {
2889 if($this->_offsetValue
) {
2890 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2893 $this->_limit
= " LIMIT " . $this->_limitValue
;
2899 * @param int $rowCount
2901 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2903 // CRM-14115, over-ride row count if rowCount is specified in URL
2904 if ($this->_dashBoardRowCount
) {
2905 $rowCount = $this->_dashBoardRowCount
;
2908 if ($this->_limit
&& ($this->_limit
!= '')) {
2909 $sql = "SELECT FOUND_ROWS();";
2910 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2912 'total' => $this->_rowsFound
,
2913 'rowCount' => $rowCount,
2914 'status' => ts('Records') . ' %%StatusMessage%%',
2915 'buttonBottom' => 'PagerBottomButton',
2916 'buttonTop' => 'PagerTopButton',
2917 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2920 $pager = new CRM_Utils_Pager($params);
2921 $this->assign_by_ref('pager', $pager);
2922 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2933 function whereGroupClause($field, $value, $op) {
2935 $smartGroupQuery = "";
2937 $group = new CRM_Contact_DAO_Group();
2938 $group->is_active
= 1;
2940 $smartGroups = array();
2941 while ($group->fetch()) {
2942 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2943 $smartGroups[] = $group->id
;
2947 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2949 $smartGroupQuery = '';
2950 if (!empty($smartGroups)) {
2951 $smartGroups = implode(',', $smartGroups);
2952 $smartGroupQuery = " UNION DISTINCT
2953 SELECT DISTINCT smartgroup_contact.contact_id
2954 FROM civicrm_group_contact_cache smartgroup_contact
2955 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2958 $sqlOp = $this->getSQLOperator($op);
2959 if (!is_array($value)) {
2960 $value = array($value);
2962 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2964 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2965 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2966 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2967 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2968 {$smartGroupQuery} ) ";
2978 function whereTagClause($field, $value, $op) {
2979 // not using left join in query because if any contact
2980 // belongs to more than one tag, results duplicate
2982 $sqlOp = $this->getSQLOperator($op);
2983 if (!is_array($value)) {
2984 $value = array($value);
2986 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2988 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2989 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2990 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2991 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2994 function whereMembershipOrgClause($field, $value, $op) {
2995 $sqlOp = $this->getSQLOperator($op);
2996 if (!is_array($value)) {
2997 $value = array($value);
3000 $tmp_membership_org_sql_list = implode(', ', $value);
3001 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3002 SELECT DISTINCT mem.contact_id
3003 FROM civicrm_membership mem
3004 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3005 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3006 WHERE mt.member_of_contact_id IN (".$tmp_membership_org_sql_list.")
3007 AND mt.is_active = '1'
3008 AND mem_status.is_current_member = '1'
3009 AND mem_status.is_active = '1' ) ";
3012 function whereMembershipTypeClause($field, $value, $op) {
3013 $sqlOp = $this->getSQLOperator($op);
3014 if (!is_array($value)) {
3015 $value = array($value);
3018 $tmp_membership_sql_list = implode(', ', $value);
3019 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3020 SELECT DISTINCT mem.contact_id
3021 FROM civicrm_membership mem
3022 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3023 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3024 WHERE mem.membership_type_id IN (".$tmp_membership_sql_list.")
3025 AND mt.is_active = '1'
3026 AND mem_status.is_current_member = '1'
3027 AND mem_status.is_active = '1' ) ";
3031 * @param string $tableAlias
3033 function buildACLClause($tableAlias = 'contact_a') {
3034 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3038 * @param bool $addFields
3039 * @param array $permCustomGroupIds
3041 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3042 if (empty($this->_customGroupExtends
)) {
3045 if (!is_array($this->_customGroupExtends
)) {
3046 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3048 $customGroupWhere = '';
3049 if (!empty($permCustomGroupIds)) {
3050 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
3053 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3054 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3055 FROM civicrm_custom_group cg
3056 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3057 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3059 cg.is_active = 1 AND
3060 cf.is_active = 1 AND
3061 cf.is_searchable = 1
3062 ORDER BY cg.weight, cf.weight";
3063 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3066 while ($customDAO->fetch()) {
3067 if ($customDAO->table_name
!= $curTable) {
3068 $curTable = $customDAO->table_name
;
3069 $curFields = $curFilters = array();
3072 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3073 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3074 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3075 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3078 'fields', 'filters', 'group_bys') as $colKey) {
3079 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3080 $this->_columns
[$curTable][$colKey] = array();
3084 $fieldName = 'custom_' . $customDAO->cf_id
;
3087 // this makes aliasing work in favor
3088 $curFields[$fieldName] = array(
3089 'name' => $customDAO->column_name
,
3090 'title' => $customDAO->label
,
3091 'dataType' => $customDAO->data_type
,
3092 'htmlType' => $customDAO->html_type
,
3095 if ($this->_customGroupFilters
) {
3096 // this makes aliasing work in favor
3097 $curFilters[$fieldName] = array(
3098 'name' => $customDAO->column_name
,
3099 'title' => $customDAO->label
,
3100 'dataType' => $customDAO->data_type
,
3101 'htmlType' => $customDAO->html_type
,
3105 switch ($customDAO->data_type
) {
3108 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3109 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3110 // CRM-6946, show time part for datetime date fields
3111 if ($customDAO->time_format
) {
3112 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3117 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3118 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
3122 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3126 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3127 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3131 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3132 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3136 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3137 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3141 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3143 if (!empty($customDAO->option_group_id
)) {
3144 if (in_array($customDAO->html_type
, array(
3145 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
3146 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3149 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3151 if ($this->_customGroupFilters
) {
3152 $curFilters[$fieldName]['options'] = array();
3153 $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')));
3154 while ($ogDAO->fetch()) {
3155 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3161 case 'StateProvince':
3162 if (in_array($customDAO->html_type
, array(
3163 'Multi-Select State/Province'))) {
3164 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3167 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3169 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3173 if (in_array($customDAO->html_type
, array(
3174 'Multi-Select Country'))) {
3175 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3178 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3180 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3183 case 'ContactReference':
3184 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3185 $curFilters[$fieldName]['name'] = 'display_name';
3186 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3188 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3189 $curFields[$fieldName]['name'] = 'display_name';
3190 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3194 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3195 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3198 if (!array_key_exists('type', $curFields[$fieldName])) {
3199 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3203 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3205 if ($this->_customGroupFilters
) {
3206 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3208 if ($this->_customGroupGroupBy
) {
3209 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3214 function customDataFrom() {
3215 if (empty($this->_customGroupExtends
)) {
3218 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3220 foreach ($this->_columns
as $table => $prop) {
3221 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
3222 $extendsTable = $mapper[$prop['extends']];
3224 // check field is in params
3225 if (!$this->isFieldSelected($prop)) {
3228 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3230 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3232 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3233 // handle for ContactReference
3234 if (array_key_exists('fields', $prop)) {
3235 foreach ($prop['fields'] as $fieldName => $field) {
3236 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
3237 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3239 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3252 function isFieldSelected($prop) {
3257 if (!empty($this->_params
['fields'])) {
3258 foreach (array_keys($prop['fields']) as $fieldAlias) {
3259 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3260 if ($customFieldId) {
3261 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3265 //might be survey response field.
3266 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3273 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3274 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3275 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3281 if (!empty($this->_params
['order_bys'])) {
3282 foreach (array_keys($prop['fields']) as $fieldAlias) {
3283 foreach ($this->_params
['order_bys'] as $orderBy) {
3284 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3291 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3292 foreach ($prop['filters'] as $fieldAlias => $val) {
3294 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3295 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3296 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3297 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3303 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3304 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3315 * Check for empty order_by configurations and remove them; also set
3316 * template to hide them.
3318 function preProcessOrderBy(&$formValues) {
3319 // Object to show/hide form elements
3320 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3322 $_showHide->addShow('optionField_1');
3324 // Cycle through order_by options; skip any empty ones, and hide them as well
3327 if (!empty($formValues['order_bys'])) {
3328 foreach ($formValues['order_bys'] as $order_by) {
3329 if ($order_by['column'] && $order_by['column'] != '-') {
3330 $_showHide->addShow('optionField_' . $n);
3331 $orderBys[$n] = $order_by;
3336 for ($i = $n; $i <= 5; $i++
) {
3338 $_showHide->addHide('optionField_' . $i);
3342 // overwrite order_by options with modified values
3343 if (!empty($orderBys)) {
3344 $formValues['order_bys'] = $orderBys;
3347 $formValues['order_bys'] = array(1 => array('column' => '-'));
3350 // assign show/hide data to template
3351 $_showHide->addToTemplate();
3355 * Does table name have columns in SELECT clause?
3357 * @param string $tableName Name of table (index of $this->_columns array)
3361 function isTableSelected($tableName) {
3362 return in_array($tableName, $this->selectedTables());
3366 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3367 * (building the array if it's unset)
3369 * @return Array $this->_selectedTables
3371 function selectedTables() {
3372 if (!$this->_selectedTables
) {
3373 $orderByColumns = array();
3374 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3375 foreach ($this->_params
['order_bys'] as $orderBy) {
3376 $orderByColumns[] = $orderBy['column'];
3380 foreach ($this->_columns
as $tableName => $table) {
3381 if (array_key_exists('fields', $table)) {
3382 foreach ($table['fields'] as $fieldName => $field) {
3383 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3384 $this->_selectedTables
[] = $tableName;
3389 if (array_key_exists('order_bys', $table)) {
3390 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3391 if (in_array($orderByName, $orderByColumns)) {
3392 $this->_selectedTables
[] = $tableName;
3397 if (array_key_exists('filters', $table)) {
3398 foreach ($table['filters'] as $filterName => $filter) {
3399 if (!empty($this->_params
["{$filterName}_value"]) ||
3400 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3401 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3403 $this->_selectedTables
[] = $tableName;
3410 return $this->_selectedTables
;
3414 * @deprecated - use getAddressColumns which is a more accurate description
3415 * and also accepts an array of options rather than a long list
3417 * function for adding address fields to construct function in reports
3419 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3420 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3421 * @param bool $filters
3422 * @param array $defaults
3424 * @return array address fields for construct clause
3426 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3427 $addressFields = array(
3428 'civicrm_address' =>
3430 'dao' => 'CRM_Core_DAO_Address',
3434 array('title' => ts('Address Name'),
3435 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3438 array('title' => ts('Street Address'),
3439 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3441 'supplemental_address_1' =>
3442 array('title' => ts('Supplementary Address Field 1'),
3443 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3445 'supplemental_address_2' =>
3446 array('title' => ts('Supplementary Address Field 2'),
3447 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3451 'name' => 'street_number',
3452 'title' => ts('Street Number'),
3454 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3458 'name' => 'street_name',
3459 'title' => ts('Street Name'),
3461 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3465 'name' => 'street_unit',
3466 'title' => ts('Street Unit'),
3468 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3471 array('title' => ts('City'),
3472 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3475 array('title' => ts('Postal Code'),
3476 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3478 'postal_code_suffix' =>
3479 array('title' => ts('Postal Code Suffix'),
3480 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3483 array('title' => ts('Country'),
3484 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3486 'state_province_id' =>
3487 array('title' => ts('State/Province'),
3488 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3491 array('title' => ts('County'),
3492 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3495 'grouping' => 'location-fields',
3500 $addressFields['civicrm_address']['filters'] = array(
3501 'street_number' => array('title' => ts('Street Number'),
3503 'name' => 'street_number',
3505 'street_name' => array('title' => ts('Street Name'),
3506 'name' => 'street_name',
3507 'operator' => 'like',
3509 'postal_code' => array('title' => ts('Postal Code'),
3511 'name' => 'postal_code',
3513 'city' => array('title' => ts('City'),
3514 'operator' => 'like',
3517 'country_id' => array(
3518 'name' => 'country_id',
3519 'title' => ts('Country'),
3520 'type' => CRM_Utils_Type
::T_INT
,
3522 CRM_Report_Form
::OP_MULTISELECT
,
3523 'options' => CRM_Core_PseudoConstant
::country(),
3525 'state_province_id' => array(
3526 'name' => 'state_province_id',
3527 'title' => ts('State/Province'),
3528 'type' => CRM_Utils_Type
::T_INT
,
3529 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3530 'options' => array(),
3532 'county_id' => array(
3533 'name' => 'county_id',
3534 'title' => ts('County'),
3535 'type' => CRM_Utils_Type
::T_INT
,
3536 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3537 'options' => array(),
3543 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3544 'street_number' => array('title' => 'Odd / Even Street Number'),
3545 'street_address' => NULL,
3547 'postal_code' => NULL,
3552 $addressFields['civicrm_address']['group_bys'] = array(
3553 'street_address' => NULL,
3555 'postal_code' => NULL,
3556 'state_province_id' =>
3557 array('title' => ts('State/Province'),
3560 array('title' => ts('Country'),
3563 array('title' => ts('County'),
3567 return $addressFields;
3571 * Do AlterDisplay processing on Address Fields
3582 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3583 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3584 $entryFound = FALSE;
3586 if (array_key_exists('civicrm_address_country_id', $row)) {
3587 if ($value = $row['civicrm_address_country_id']) {
3588 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3589 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3590 "reset=1&force=1&{$criteriaQueryParams}&" .
3591 "country_id_op=in&country_id_value={$value}",
3592 $this->_absoluteUrl
, $this->_id
3594 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3595 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3602 if (array_key_exists('civicrm_address_county_id', $row)) {
3603 if ($value = $row['civicrm_address_county_id']) {
3604 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3605 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3606 "reset=1&force=1&{$criteriaQueryParams}&" .
3607 "county_id_op=in&county_id_value={$value}",
3608 $this->_absoluteUrl
, $this->_id
3610 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3611 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3617 // handle state province
3618 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3619 if ($value = $row['civicrm_address_state_province_id']) {
3620 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3622 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3623 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3624 $this->_absoluteUrl
, $this->_id
3626 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3627 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3638 * Adjusts dates passed in to YEAR() for fiscal year.
3645 function fiscalYearOffset($fieldName) {
3646 $config = CRM_Core_Config
::singleton();
3647 $fy = $config->fiscalYearStart
;
3648 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3649 return "YEAR( $fieldName )";
3651 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3655 * Add Address into From Table if required
3657 function addAddressFromClause() {
3658 // include address field if address column is to be included
3659 if ((isset($this->_addressField
) &&
3660 $this->_addressField
3662 $this->isTableSelected('civicrm_address')
3665 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3666 ON ({$this->_aliases['civicrm_contact']}.id =
3667 {$this->_aliases['civicrm_address']}.contact_id) AND
3668 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3673 * Add Phone into From Table if required
3675 function addPhoneFromClause() {
3676 // include address field if address column is to be included
3677 if ($this->isTableSelected('civicrm_phone')
3680 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3681 ON ({$this->_aliases['civicrm_contact']}.id =
3682 {$this->_aliases['civicrm_phone']}.contact_id) AND
3683 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3688 * Get phone columns to add to array
3689 * @param array $options
3690 * - prefix Prefix to add to table (in case of more than one instance of the table)
3691 * - prefix_label Label to give columns from this phone table instance
3692 * @return array phone columns definition
3694 function getPhoneColumns($options = array()){
3695 $defaultOptions = array(
3697 'prefix_label' => '',
3700 $options = array_merge($defaultOptions,$options);
3703 $options['prefix'] . 'civicrm_phone' => array(
3704 'dao' => 'CRM_Core_DAO_Phone',
3706 $options['prefix'] . 'phone' => array(
3707 'title' => ts($options['prefix_label'] . 'Phone'),
3717 * Get address columns to add to array
3718 * @param array $options
3719 * - prefix Prefix to add to table (in case of more than one instance of the table)
3720 * - prefix_label Label to give columns from this address table instance
3721 * @return array address columns definition
3723 function getAddressColumns($options = array()) {
3726 'prefix_label' => '',
3730 'defaults' => array(),
3732 return $this->addAddressFields(
3733 $options['group_by'],
3734 $options['order_by'],
3735 $options['filters'],
3736 $options['defaults']
3743 function add2group($groupID) {
3744 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3745 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3746 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3748 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3749 $dao = CRM_Core_DAO
::executeQuery($sql);
3751 $contact_ids = array();
3752 // Add resulting contacts to group
3753 while ($dao->fetch()) {
3754 if ($dao->addtogroup_contact_id
) {
3755 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3759 if ( !empty($contact_ids) ) {
3760 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3761 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3764 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3769 /* function used for showing charts on print screen */
3770 static function uploadChartImage() {
3771 // upload strictly for '.png' images
3772 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3773 if (preg_match('/\.png$/', $name)) {
3775 // POST data is usually string data, but we are passing a RAW .png
3776 // so PHP is a bit confused and $_POST is empty. But it has saved
3777 // the raw bits into $HTTP_RAW_POST_DATA
3779 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3781 // prepare the directory
3782 $config = CRM_Core_Config
::singleton();
3783 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3784 if (!file_exists($defaultPath)) {
3785 mkdir($defaultPath, 0777, TRUE);
3788 // full path to the saved image including filename
3789 $destination = $defaultPath . $name;
3792 $jfh = fopen($destination, 'w') or die("can't open file");
3793 fwrite($jfh, $httpRawPostData);
3795 CRM_Utils_System
::civiExit();