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() {
881 $options = $filters = array();
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'])) {
920 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
921 if (count($operations) <= 1) {
924 $select = $this->addElement('select', "{$fieldName}_value", NULL,
925 $field['options'], array(
927 'style' => 'min-width:250px',
930 $select->setMultiple(TRUE);
934 case CRM_Report_Form
::OP_SELECT
:
935 // assume a select field
936 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
937 if (!empty($field['options']))
938 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
941 case CRM_Report_Form
::OP_DATE
:
942 // build datetime fields
943 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
947 case CRM_Report_Form
::OP_DATETIME
:
948 // build datetime fields
949 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
953 case CRM_Report_Form
::OP_INT
:
954 case CRM_Report_Form
::OP_FLOAT
:
955 // and a min value input box
956 $this->add('text', "{$fieldName}_min", ts('Min'));
957 // and a max value input box
958 $this->add('text', "{$fieldName}_max", ts('Max'));
960 // default type is string
961 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
962 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
964 // we need text box for value input
965 $this->add('text', "{$fieldName}_value", NULL);
970 $this->assign('filters', $filters);
973 function addOptions() {
974 if (!empty($this->_options
)) {
975 // FIXME: For now lets build all elements as checkboxes.
976 // Once we clear with the format we can build elements based on type
979 foreach ($this->_options
as $fieldName => $field) {
980 if ($field['type'] == 'select') {
981 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
983 else if ($field['type'] == 'checkbox') {
984 $options[$field['title']] = $fieldName;
985 $this->addCheckBox($fieldName, NULL,
987 NULL, NULL, NULL, $this->_fourColumnAttribute
992 $this->assign('otherOptions', $this->_options
);
995 function addChartOptions() {
996 if (!empty($this->_charts
)) {
997 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
998 $this->assign('charts', $this->_charts
);
999 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1003 function addGroupBys() {
1004 $options = $freqElements = array();
1006 foreach ($this->_columns
as $tableName => $table) {
1007 if (array_key_exists('group_bys', $table)) {
1008 foreach ($table['group_bys'] as $fieldName => $field) {
1009 if (!empty($field)) {
1010 $options[$field['title']] = $fieldName;
1011 if (!empty($field['frequency'])) {
1012 $freqElements[$field['title']] = $fieldName;
1018 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1019 NULL, NULL, NULL, $this->_fourColumnAttribute
1021 $this->assign('groupByElements', $options);
1023 foreach ($freqElements as $name) {
1024 $this->addElement('select', "group_bys_freq[$name]",
1025 ts('Frequency'), $this->_groupByDateFreq
1030 function addOrderBys() {
1032 foreach ($this->_columns
as $tableName => $table) {
1034 // Report developer may define any column to order by; include these as order-by options
1035 if (array_key_exists('order_bys', $table)) {
1036 foreach ($table['order_bys'] as $fieldName => $field) {
1037 if (!empty($field)) {
1038 $options[$fieldName] = $field['title'];
1043 /* Add searchable custom fields as order-by options, if so requested
1044 * (These are already indexed, so allowing to order on them is cheap.)
1048 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1049 foreach ($table['fields'] as $fieldName => $field) {
1050 if (empty($field['no_display'])) {
1051 $options[$fieldName] = $field['title'];
1059 $this->assign('orderByOptions', $options);
1061 if (!empty($options)) {
1063 '-' => ' - none - ') +
$options;
1064 for ($i = 1; $i <= 5; $i++
) {
1065 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1066 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1067 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1068 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1073 function buildInstanceAndButtons() {
1074 CRM_Report_Form_Instance
::buildForm($this);
1076 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1078 $this->addElement('submit', $this->_instanceButtonName
, $label);
1079 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1080 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1083 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1085 if ($this->_instanceForm
) {
1086 $this->assign('instanceForm', TRUE);
1089 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1090 $this->addElement('submit', $this->_printButtonName
, $label);
1092 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1093 $this->addElement('submit', $this->_pdfButtonName
, $label);
1095 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1097 if ($this->_csvSupported
) {
1098 $this->addElement('submit', $this->_csvButtonName
, $label);
1101 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1102 $this->addElement('select', 'groups', ts('Group'),
1103 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
1105 $this->assign('group', TRUE);
1108 $label = ts('Add These Contacts to Group');
1109 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1111 $this->addChartOptions();
1112 $this->addButtons(array(
1115 'name' => ts('Preview Report'),
1116 'isDefault' => TRUE,
1122 function buildQuickForm() {
1123 $this->addColumns();
1125 $this->addFilters();
1127 $this->addOptions();
1129 $this->addGroupBys();
1131 $this->addOrderBys();
1133 $this->buildInstanceAndButtons();
1135 //add form rule for report
1136 if (is_callable(array(
1137 $this, 'formRule'))) {
1138 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1142 // a formrule function to ensure that fields selected in group_by
1143 // (if any) should only be the ones present in display/select fields criteria;
1144 // note: works if and only if any custom field selected in group_by.
1147 * @param array $ignoreFields
1151 function customDataFormRule($fields, $ignoreFields = array( )) {
1153 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1154 foreach ($this->_columns
as $tableName => $table) {
1155 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1156 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1157 if (array_key_exists($fieldName, $fields['group_bys']) &&
1158 !array_key_exists($fieldName, $fields['fields'])
1160 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1162 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1163 foreach ($fields['fields'] as $fld => $val) {
1164 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1165 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1176 // Note: $fieldName param allows inheriting class to build operationPairs
1177 // specific to a field.
1179 * @param string $type
1180 * @param null $fieldName
1184 function getOperationPair($type = "string", $fieldName = NULL) {
1185 // FIXME: At some point we should move these key-val pairs
1186 // to option_group and option_value table.
1188 case CRM_Report_Form
::OP_INT
:
1189 case CRM_Report_Form
::OP_FLOAT
:
1191 'lte' => ts('Is less than or equal to'),
1192 'gte' => ts('Is greater than or equal to'),
1193 'bw' => ts('Is between'),
1194 'eq' => ts('Is equal to'),
1195 'lt' => ts('Is less than'),
1196 'gt' => ts('Is greater than'),
1197 'neq' => ts('Is not equal to'),
1198 'nbw' => ts('Is not between'),
1199 'nll' => ts('Is empty (Null)'),
1200 'nnll' => ts('Is not empty (Null)'),
1204 case CRM_Report_Form
::OP_SELECT
:
1206 'eq' => ts('Is equal to'),
1209 case CRM_Report_Form
::OP_MONTH
:
1210 case CRM_Report_Form
::OP_MULTISELECT
:
1212 'in' => ts('Is one of'),
1213 'notin' => ts('Is not one of'),
1217 case CRM_Report_Form
::OP_DATE
:
1219 'nll' => ts('Is empty (Null)'),
1220 'nnll' => ts('Is not empty (Null)'),
1224 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1225 // use this operator for the values, concatenated with separator. For e.g if
1226 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1228 'mhas' => ts('Is one of'),
1229 'mnot' => ts('Is not one of'),
1235 'has' => ts('Contains'),
1236 'sw' => ts('Starts with'),
1237 'ew' => ts('Ends with'),
1238 'nhas' => ts('Does not contain'),
1239 'eq' => ts('Is equal to'),
1240 'neq' => ts('Is not equal to'),
1241 'nll' => ts('Is empty (Null)'),
1242 'nnll' => ts('Is not empty (Null)'),
1247 function buildTagFilter() {
1248 $contactTags = CRM_Core_BAO_Tag
::getTags();
1249 if (!empty($contactTags)) {
1250 $this->_columns
['civicrm_tag'] = array(
1251 'dao' => 'CRM_Core_DAO_Tag',
1257 'title' => ts('Tag'),
1259 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1260 'options' => $contactTags,
1268 * Adds group filters to _columns (called from _Constuct
1270 function buildGroupFilter() {
1271 $this->_columns
['civicrm_group']['filters'] = array(
1274 'name' => 'group_id',
1275 'title' => ts('Group'),
1276 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1278 'options' => CRM_Core_PseudoConstant
::group(),
1281 if (empty($this->_columns
['civicrm_group']['dao'])) {
1282 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1284 if (empty($this->_columns
['civicrm_group']['alias'])) {
1285 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1290 * @param string $operator
1294 function getSQLOperator($operator = "like") {
1295 switch ($operator) {
1328 return 'IS NOT NULL';
1343 * @return null|string
1345 function whereClause(&$field, $op,
1349 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1355 if (($min !== NULL && strlen($min) > 0) ||
1356 ($max !== NULL && strlen($max) > 0)
1358 $min = CRM_Utils_Type
::escape($min, $type);
1359 $max = CRM_Utils_Type
::escape($max, $type);
1363 $clauses[] = "( {$field['dbAlias']} >= $min )";
1366 $clauses[] = "( {$field['dbAlias']} < $min )";
1371 $clauses[] = "( {$field['dbAlias']} <= $max )";
1374 $clauses[] = "( {$field['dbAlias']} > $max )";
1378 if (!empty($clauses)) {
1380 $clause = implode(' AND ', $clauses);
1383 $clause = implode(' OR ', $clauses);
1391 if ($value !== NULL && strlen($value) > 0) {
1392 $value = CRM_Utils_Type
::escape($value, $type);
1393 if (strpos($value, '%') === FALSE) {
1394 $value = "'%{$value}%'";
1397 $value = "'{$value}'";
1399 $sqlOP = $this->getSQLOperator($op);
1400 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1406 if ($value !== NULL && is_array($value) && count($value) > 0) {
1407 $sqlOP = $this->getSQLOperator($op);
1408 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1409 //cycle through selections and esacape values
1410 foreach ($value as $key => $selection) {
1411 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1413 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1416 // for numerical values
1417 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1419 if ($op == 'notin') {
1420 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1423 $clause = "( " . $clause . " )";
1429 // mhas == multiple has
1430 if ($value !== NULL && count($value) > 0) {
1431 $sqlOP = $this->getSQLOperator($op);
1432 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1437 // mnot == multiple is not one of
1438 if ($value !== NULL && count($value) > 0) {
1439 $sqlOP = $this->getSQLOperator($op);
1440 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1446 if ($value !== NULL && strlen($value) > 0) {
1447 $value = CRM_Utils_Type
::escape($value, $type);
1448 if (strpos($value, '%') === FALSE) {
1450 $value = "'{$value}%'";
1453 $value = "'%{$value}'";
1457 $value = "'{$value}'";
1459 $sqlOP = $this->getSQLOperator($op);
1460 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1466 $sqlOP = $this->getSQLOperator($op);
1467 $clause = "( {$field['dbAlias']} $sqlOP )";
1471 if ($value !== NULL && strlen($value) > 0) {
1472 if (isset($field['clause'])) {
1473 // FIXME: we not doing escape here. Better solution is to use two
1474 // different types - data-type and filter-type
1475 $clause = $field['clause'];
1478 $value = CRM_Utils_Type
::escape($value, $type);
1479 $sqlOP = $this->getSQLOperator($op);
1480 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1481 $value = "'{$value}'";
1483 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1489 if (!empty($field['group']) && $clause) {
1490 $clause = $this->whereGroupClause($field, $value, $op);
1492 elseif (!empty($field['tag']) && $clause) {
1493 // not using left join in query because if any contact
1494 // belongs to more than one tag, results duplicate
1496 $clause = $this->whereTagClause($field, $value, $op);
1508 * @param null $fromTime
1509 * @param null $toTime
1511 * @return null|string
1513 function dateClause($fieldName,
1514 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1517 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1518 $sqlOP = $this->getSQLOperator($relative);
1519 return "( {$fieldName} {$sqlOP} )";
1522 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1525 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1526 $clauses[] = "( {$fieldName} >= $from )";
1530 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1531 $clauses[] = "( {$fieldName} <= {$to} )";
1534 if (!empty($clauses)) {
1535 return implode(' AND ', $clauses);
1541 * @todo - could not find any instances where this is called
1542 * @param unknown_type $relative
1543 * @param String $from
1544 * @param String_type $to
1545 * @return string|NULL
1547 function dateDisplay($relative, $from, $to) {
1548 list($from, $to) = $this->getFromTo($relative, $from, $to);
1551 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1554 $clauses[] = 'Past';
1558 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1561 $clauses[] = 'Today';
1564 if (!empty($clauses)) {
1565 return implode(' - ', $clauses);
1575 * @param null $fromtime
1576 * @param null $totime
1580 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1581 if (empty($totime)) {
1584 //FIX ME not working for relative
1586 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1587 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1588 $from = substr($dateRange['from'], 0, 8);
1589 //Take only Date Part, Sometime Time part is also present in 'to'
1590 $to = substr($dateRange['to'], 0, 8);
1592 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1593 $to = CRM_Utils_Date
::processDate($to, $totime);
1594 return array($from, $to);
1600 function alterDisplay(&$rows) {
1601 // custom code to alter rows
1607 function alterCustomDataDisplay(&$rows) {
1608 // custom code to alter rows having custom values
1609 if (empty($this->_customGroupExtends
)) {
1613 $customFieldIds = array();
1614 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1615 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1616 $customFieldIds[$fieldAlias] = $fieldId;
1619 if (empty($customFieldIds)) {
1623 $customFields = $fieldValueMap = array();
1624 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1626 // skip for type date and ContactReference since date format is already handled
1628 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1629 FROM civicrm_custom_field cf
1630 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1631 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1632 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1633 cg.is_active = 1 AND
1634 cf.is_active = 1 AND
1635 cf.is_searchable = 1 AND
1636 cf.data_type NOT IN ('ContactReference', 'Date') AND
1637 cf.id IN (" . implode(",", $customFieldIds) . ")";
1639 $dao = CRM_Core_DAO
::executeQuery($query);
1640 while ($dao->fetch()) {
1641 foreach ($customFieldCols as $key) {
1642 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1644 if ($dao->option_group_id
) {
1645 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1650 $entryFound = FALSE;
1651 foreach ($rows as $rowNum => $row) {
1652 foreach ($row as $tableCol => $val) {
1653 if (array_key_exists($tableCol, $customFields)) {
1654 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1659 // skip looking further in rows, if first row itself doesn't
1660 // have the column we need
1669 * @param $customField
1670 * @param $fieldValueMap
1672 * @return float|string
1674 function formatCustomValues($value, $customField, $fieldValueMap) {
1675 if (CRM_Utils_System
::isNull($value)) {
1679 $htmlType = $customField['html_type'];
1681 switch ($customField['data_type']) {
1683 if ($value == '1') {
1684 $retValue = ts('Yes');
1687 $retValue = ts('No');
1692 $retValue = CRM_Utils_System
::formatWikiURL($value);
1704 if ($htmlType == 'Text') {
1705 $retValue = (float)$value;
1709 if ($htmlType == 'Text') {
1719 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1724 if (in_array($htmlType, array(
1725 'Text', 'TextArea'))) {
1729 case 'StateProvince':
1732 switch ($htmlType) {
1733 case 'Multi-Select Country':
1734 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1735 $customData = array();
1736 foreach ($value as $val) {
1738 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1741 $retValue = implode(', ', $customData);
1744 case 'Select Country':
1745 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1748 case 'Select State/Province':
1749 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1752 case 'Multi-Select State/Province':
1753 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1754 $customData = array();
1755 foreach ($value as $val) {
1757 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1760 $retValue = implode(', ', $customData);
1765 case 'Autocomplete-Select':
1766 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1770 case 'AdvMulti-Select':
1771 case 'Multi-Select':
1772 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1773 $customData = array();
1774 foreach ($value as $val) {
1776 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1779 $retValue = implode(', ', $customData);
1797 function removeDuplicates(&$rows) {
1798 if (empty($this->_noRepeats
)) {
1801 $checkList = array();
1803 foreach ($rows as $key => $list) {
1804 foreach ($list as $colName => $colVal) {
1805 if (array_key_exists($colName, $checkList) &&
1806 $checkList[$colName] == $colVal) {
1807 $rows[$key][$colName] = "";
1809 if (in_array($colName, $this->_noRepeats
)) {
1810 $checkList[$colName] = $colVal;
1819 * @param bool $subtotal
1821 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1822 foreach ($row as $colName => $colVal) {
1823 if (in_array($colName, $fields)) {
1824 $row[$colName] = $row[$colName];
1826 elseif (isset($this->_columnHeaders
[$colName])) {
1828 $row[$colName] = "Subtotal";
1832 unset($row[$colName]);
1843 function grandTotal(&$rows) {
1844 if (!$this->_rollup ||
($this->_rollup
== '') ||
1845 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1849 $lastRow = array_pop($rows);
1851 foreach ($this->_columnHeaders
as $fld => $val) {
1852 if (!in_array($fld, $this->_statFields
)) {
1853 if (!$this->_grandFlag
) {
1854 $lastRow[$fld] = "Grand Total";
1855 $this->_grandFlag
= TRUE;
1858 $lastRow[$fld] = "";
1863 $this->assign('grandStat', $lastRow);
1869 * @param bool $pager
1871 function formatDisplay(&$rows, $pager = TRUE) {
1872 // set pager based on if any limit was applied in the query.
1877 // allow building charts if any
1878 if (!empty($this->_params
['charts']) && !empty($rows)) {
1879 $this->buildChart($rows);
1880 $this->assign('chartEnabled', TRUE);
1881 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1882 $this->assign('chartId', $this->_chartId
);
1885 // unset columns not to be displayed.
1886 foreach ($this->_columnHeaders
as $key => $value) {
1887 if (!empty($value['no_display'])) {
1888 unset($this->_columnHeaders
[$key]);
1892 // unset columns not to be displayed.
1893 if (!empty($rows)) {
1894 foreach ($this->_noDisplay
as $noDisplayField) {
1895 foreach ($rows as $rowNum => $row) {
1896 unset($this->_columnHeaders
[$noDisplayField]);
1901 // build array of section totals
1902 $this->sectionTotals();
1904 // process grand-total row
1905 $this->grandTotal($rows);
1907 // use this method for formatting rows for display purpose.
1908 $this->alterDisplay($rows);
1909 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1911 // use this method for formatting custom rows for display purpose.
1912 $this->alterCustomDataDisplay($rows);
1918 function buildChart(&$rows) {
1919 // override this method for building charts.
1922 // select() method below has been added recently (v3.3), and many of the report templates might
1923 // still be having their own select() method. We should fix them as and when encountered and move
1924 // towards generalizing the select() method below.
1926 $select = $this->_selectAliases
= array();
1928 foreach ($this->_columns
as $tableName => $table) {
1929 if (array_key_exists('fields', $table)) {
1930 foreach ($table['fields'] as $fieldName => $field) {
1931 if ($tableName == 'civicrm_address') {
1932 $this->_addressField
= TRUE;
1934 if ($tableName == 'civicrm_email') {
1935 $this->_emailField
= TRUE;
1937 if ($tableName == 'civicrm_phone') {
1938 $this->_phoneField
= TRUE;
1941 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1943 // 1. In many cases we want select clause to be built in slightly different way
1944 // for a particular field of a particular type.
1945 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1947 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1948 if ($selectClause) {
1949 $select[] = $selectClause;
1953 // include statistics columns only if set
1954 if (!empty($field['statistics'])) {
1955 foreach ($field['statistics'] as $stat => $label) {
1956 $alias = "{$tableName}_{$fieldName}_{$stat}";
1957 switch (strtolower($stat)) {
1960 $select[] = "$stat({$field['dbAlias']}) as $alias";
1961 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1962 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1963 $this->_statFields
[$label] = $alias;
1964 $this->_selectAliases
[] = $alias;
1968 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1969 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1970 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1971 $this->_statFields
[$label] = $alias;
1972 $this->_selectAliases
[] = $alias;
1975 case 'count_distinct':
1976 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1977 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1978 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1979 $this->_statFields
[$label] = $alias;
1980 $this->_selectAliases
[] = $alias;
1984 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1985 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1986 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1987 $this->_statFields
[$label] = $alias;
1988 $this->_selectAliases
[] = $alias;
1994 $alias = "{$tableName}_{$fieldName}";
1995 $select[] = "{$field['dbAlias']} as $alias";
1996 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1997 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1998 $this->_selectAliases
[] = $alias;
2004 // select for group bys
2005 if (array_key_exists('group_bys', $table)) {
2006 foreach ($table['group_bys'] as $fieldName => $field) {
2008 if ($tableName == 'civicrm_address') {
2009 $this->_addressField
= TRUE;
2011 if ($tableName == 'civicrm_email') {
2012 $this->_emailField
= TRUE;
2014 if ($tableName == 'civicrm_phone') {
2015 $this->_phoneField
= TRUE;
2017 // 1. In many cases we want select clause to be built in slightly different way
2018 // for a particular field of a particular type.
2019 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2021 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2022 if ($selectClause) {
2023 $select[] = $selectClause;
2027 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
2028 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2030 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2031 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2032 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2033 $field['title'] = 'Week';
2037 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2038 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2039 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2040 $field['title'] = 'Year';
2044 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2045 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2046 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2047 $field['title'] = 'Month';
2051 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2052 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2053 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2054 $field['title'] = 'Quarter';
2057 // for graphs and charts -
2058 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2059 $this->_interval
= $field['title'];
2060 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
2061 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2062 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2064 // just to make sure these values are transfered to rows.
2065 // since we 'll need them for calculation purpose,
2066 // e.g making subtotals look nicer or graphs
2067 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2068 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2075 $this->_selectClauses
= $select;
2076 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2087 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2092 $this->storeWhereHavingClauseArray();
2094 if (empty($this->_whereClauses
)) {
2095 $this->_where
= "WHERE ( 1 ) ";
2096 $this->_having
= "";
2099 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2102 if ($this->_aclWhere
) {
2103 $this->_where
.= " AND {$this->_aclWhere} ";
2106 if (!empty($this->_havingClauses
)) {
2107 // use this clause to construct group by clause.
2108 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2113 * Store Where clauses into an array - breaking out this step makes
2114 * over-riding more flexible as the clauses can be used in constructing a
2115 * temp table that may not be part of the final where clause or added
2116 * in other functions
2118 function storeWhereHavingClauseArray(){
2119 foreach ($this->_columns
as $tableName => $table) {
2120 if (array_key_exists('filters', $table)) {
2121 foreach ($table['filters'] as $fieldName => $field) {
2122 // respect pseudofield to filter spec so fields can be marked as
2123 // not to be handled here
2124 if(!empty($field['pseudofield'])){
2128 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2129 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2130 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2131 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2132 if (is_array($value) && !empty($value)) {
2133 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2137 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2138 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2139 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2140 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2141 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2142 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2146 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2148 $clause = $this->whereClause($field,
2150 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2151 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2152 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2157 if (!empty($clause)) {
2158 if (!empty($field['having'])) {
2159 $this->_havingClauses
[] = $clause;
2162 $this->_whereClauses
[] = $clause;
2170 function processReportMode() {
2171 $buttonName = $this->controller
->getButtonName();
2173 $output = CRM_Utils_Request
::retrieve(
2176 CRM_Core_DAO
::$_nullObject
2180 CRM_Utils_Request
::retrieve(
2183 CRM_Core_DAO
::$_nullObject
2186 $this->_absoluteUrl
= FALSE;
2188 $this->assign('printOnly', FALSE);
2190 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2191 $this->assign('printOnly', TRUE);
2193 $this->assign('outputMode', 'print');
2194 $this->_outputMode
= 'print';
2195 if ($this->_sendmail
) {
2196 $this->_absoluteUrl
= TRUE;
2199 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2200 $this->assign('printOnly', TRUE);
2202 $this->assign('outputMode', 'pdf');
2203 $this->_outputMode
= 'pdf';
2204 $this->_absoluteUrl
= TRUE;
2206 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2207 $this->assign('printOnly', TRUE);
2209 $this->assign('outputMode', 'csv');
2210 $this->_outputMode
= 'csv';
2211 $this->_absoluteUrl
= TRUE;
2213 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2214 $this->assign('outputMode', 'group');
2215 $this->_outputMode
= 'group';
2217 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2218 $this->assign('outputMode', 'create_report');
2219 $this->_outputMode
= 'create_report';
2222 $this->assign('outputMode', 'html');
2223 $this->_outputMode
= 'html';
2226 // Get today's date to include in printed reports
2228 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2229 $this->assign('reportDate', $reportDate);
2233 function beginPostProcess() {
2234 $this->setParams($this->controller
->exportValues($this->_name
));
2236 if (empty($this->_params
) &&
2239 $this->setParams($this->_formValues
);
2242 // hack to fix params when submitted from dashboard, CRM-8532
2243 // fields array is missing because form building etc is skipped
2244 // in dashboard mode for report
2245 //@todo - this could be done in the dashboard no we have a setter
2246 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2247 $this->setParams($this->_formValues
);
2250 $this->_formValues
= $this->_params
;
2251 if (CRM_Core_Permission
::check('administer Reports') &&
2252 isset($this->_id
) &&
2253 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2254 $this->_chartButtonName
== $this->controller
->getButtonName()
2257 $this->assign('updateReportButton', TRUE);
2259 $this->processReportMode();
2260 $this->beginPostProcessCommon();
2264 * beginPostProcess function run in both report mode and non-report mode (api)
2266 function beginPostProcessCommon() {
2271 * @param bool $applyLimit
2275 function buildQuery($applyLimit = TRUE) {
2278 $this->customDataFrom();
2283 // order_by columns not selected for display need to be included in SELECT
2284 $unselectedSectionColumns = $this->unselectedSectionColumns();
2285 foreach ($unselectedSectionColumns as $alias => $section) {
2286 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2289 if ($applyLimit && empty($this->_params
['charts'])) {
2292 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2294 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2298 function groupBy() {
2299 $groupBys = array();
2300 if (!empty($this->_params
['group_bys']) &&
2301 is_array($this->_params
['group_bys']) &&
2302 !empty($this->_params
['group_bys'])
2304 foreach ($this->_columns
as $tableName => $table) {
2305 if (array_key_exists('group_bys', $table)) {
2306 foreach ($table['group_bys'] as $fieldName => $field) {
2307 if (!empty($this->_params
['group_bys'][$fieldName])) {
2308 $groupBys[] = $field['dbAlias'];
2315 if (!empty($groupBys)) {
2316 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2320 function orderBy() {
2321 $this->_orderBy
= "";
2322 $this->_sections
= array();
2323 $this->storeOrderByArray();
2324 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2325 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2327 $this->assign('sections', $this->_sections
);
2331 * In some cases other functions want to know which fields are selected for ordering by
2332 * Separating this into a separate function allows it to be called separately from constructing
2333 * the order by clause
2335 function storeOrderByArray() {
2336 $orderBys = array();
2338 if (!empty($this->_params
['order_bys']) &&
2339 is_array($this->_params
['order_bys']) &&
2340 !empty($this->_params
['order_bys'])
2343 // Proces order_bys in user-specified order
2344 foreach ($this->_params
['order_bys'] as $orderBy) {
2345 $orderByField = array();
2346 foreach ($this->_columns
as $tableName => $table) {
2347 if (array_key_exists('order_bys', $table)) {
2348 // For DAO columns defined in $this->_columns
2349 $fields = $table['order_bys'];
2351 elseif (array_key_exists('extends', $table)) {
2352 // For custom fields referenced in $this->_customGroupExtends
2353 $fields = CRM_Utils_Array
::value('fields', $table, array());
2355 if (!empty($fields) && is_array($fields)) {
2356 foreach ($fields as $fieldName => $field) {
2357 if ($fieldName == $orderBy['column']) {
2358 $orderByField = array_merge($field, $orderBy);
2359 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2366 if (!empty($orderByField)) {
2367 $this->_orderByFields
[] = $orderByField;
2368 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2370 // Record any section headers for assignment to the template
2371 if (!empty($orderBy['section'])) {
2372 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2373 $this->_sections
[$orderByField['tplField']] = $orderByField;
2379 $this->_orderByArray
= $orderBys;
2381 $this->assign('sections', $this->_sections
);
2387 function unselectedSectionColumns() {
2388 $selectColumns = array();
2389 foreach ($this->_columns
as $tableName => $table) {
2390 if (array_key_exists('fields', $table)) {
2391 foreach ($table['fields'] as $fieldName => $field) {
2392 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2394 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2400 if (is_array($this->_sections
)) {
2401 return array_diff_key($this->_sections
, $selectColumns);
2412 function buildRows($sql, &$rows) {
2413 $dao = CRM_Core_DAO
::executeQuery($sql);
2414 if (!is_array($rows)) {
2418 // use this method to modify $this->_columnHeaders
2419 $this->modifyColumnHeaders();
2421 $unselectedSectionColumns = $this->unselectedSectionColumns();
2423 while ($dao->fetch()) {
2425 foreach ($this->_columnHeaders
as $key => $value) {
2426 if (property_exists($dao, $key)) {
2427 $row[$key] = $dao->$key;
2431 // section headers not selected for display need to be added to row
2432 foreach ($unselectedSectionColumns as $key => $values) {
2433 if (property_exists($dao, $key)) {
2434 $row[$key] = $dao->$key;
2443 * When "order by" fields are marked as sections, this assigns to the template
2444 * an array of total counts for each section. This data is used by the Smarty
2445 * plugin {sectionTotal}
2447 function sectionTotals() {
2449 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2450 if (empty($this->_selectAliases
)) {
2454 if (!empty($this->_sections
)) {
2455 // build the query with no LIMIT clause
2456 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2457 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2459 // pull section aliases out of $this->_sections
2460 $sectionAliases = array_keys($this->_sections
);
2463 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2464 $ifnulls[] = "ifnull($alias, '') as $alias";
2467 /* Group (un-limited) report by all aliases and get counts. This might
2468 * be done more efficiently when the contents of $sql are known, ie. by
2469 * overriding this method in the report class.
2473 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2475 // initialize array of total counts
2477 $dao = CRM_Core_DAO
::executeQuery($query);
2478 while ($dao->fetch()) {
2480 // let $this->_alterDisplay translate any integer ids to human-readable values.
2481 $rows[0] = $dao->toArray();
2482 $this->alterDisplay($rows);
2485 // add totals for all permutations of section values
2488 $aliasCount = count($sectionAliases);
2489 foreach ($sectionAliases as $alias) {
2490 $values[] = $row[$alias];
2491 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2492 if ($i == $aliasCount) {
2493 // the last alias is the lowest-level section header; use count as-is
2494 $totals[$key] = $dao->ct
;
2497 // other aliases are higher level; roll count into their total
2498 $totals[$key] +
= $dao->ct
;
2502 $this->assign('sectionTotals', $totals);
2506 function modifyColumnHeaders() {
2507 // use this method to modify $this->_columnHeaders
2513 function doTemplateAssignment(&$rows) {
2514 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2515 $this->assign_by_ref('rows', $rows);
2516 $this->assign('statistics', $this->statistics($rows));
2519 // override this method to build your own statistics
2525 function statistics(&$rows) {
2526 $statistics = array();
2528 $count = count($rows);
2530 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2534 $this->countStat($statistics, $count);
2536 $this->groupByStat($statistics);
2538 $this->filterStat($statistics);
2544 * @param $statistics
2547 function countStat(&$statistics, $count) {
2548 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2552 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2553 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2554 'value' => $this->_rowsFound
,
2560 * @param $statistics
2562 function groupByStat(&$statistics) {
2563 if (!empty($this->_params
['group_bys']) &&
2564 is_array($this->_params
['group_bys']) &&
2565 !empty($this->_params
['group_bys'])
2567 foreach ($this->_columns
as $tableName => $table) {
2568 if (array_key_exists('group_bys', $table)) {
2569 foreach ($table['group_bys'] as $fieldName => $field) {
2570 if (!empty($this->_params
['group_bys'][$fieldName])) {
2571 $combinations[] = $field['title'];
2576 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2577 'value' => implode(' & ', $combinations),
2583 * @param $statistics
2585 function filterStat(&$statistics) {
2586 foreach ($this->_columns
as $tableName => $table) {
2587 if (array_key_exists('filters', $table)) {
2588 foreach ($table['filters'] as $fieldName => $field) {
2589 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2592 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2593 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2594 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2595 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2596 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2598 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2599 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2601 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2602 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2605 $statistics['filters'][] = array(
2606 'title' => $field['title'],
2607 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2610 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2611 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2613 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2614 $statistics['filters'][] = array(
2615 'title' => $field['title'],
2616 'value' => $pair[$rel],
2621 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2624 $pair = $this->getOperationPair(
2625 CRM_Utils_Array
::value('operatorType', $field),
2628 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2629 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2630 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2631 if (in_array($op, array(
2632 'bw', 'nbw')) && ($min ||
$max)) {
2633 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2635 elseif ($op == 'nll' ||
$op == 'nnll') {
2636 $value = $pair[$op];
2638 elseif (is_array($val) && (!empty($val))) {
2639 $options = CRM_Utils_Array
::value('options', $field, array());
2640 foreach ($val as $key => $valIds) {
2641 if (isset($options[$valIds])) {
2642 $val[$key] = $options[$valIds];
2645 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2646 $val = implode(', ', $val);
2647 $value = "{$pair[$op]} " . $val;
2649 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2650 is_array($field['options']) && !empty($field['options'])
2652 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2655 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2659 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2672 function endPostProcess(&$rows = NULL) {
2673 if ( $this->_storeResultSet
) {
2674 $this->_resultSet
= $rows;
2677 if ($this->_outputMode
== 'print' ||
2678 $this->_outputMode
== 'pdf' ||
2682 $content = $this->compileContent();
2683 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2687 if ($this->_sendmail
) {
2688 $config = CRM_Core_Config
::singleton();
2689 $attachments = array();
2691 if ($this->_outputMode
== 'csv') {
2692 $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'];
2694 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2695 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2696 file_put_contents($csvFullFilename, $csvContent);
2697 $attachments[] = array(
2698 'fullPath' => $csvFullFilename,
2699 'mime_type' => 'text/csv',
2700 'cleanName' => 'CiviReport.csv',
2703 if ($this->_outputMode
== 'pdf') {
2704 // generate PDF content
2705 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2706 file_put_contents($pdfFullFilename,
2707 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2708 TRUE, array('orientation' => 'landscape')
2711 // generate Email Content
2712 $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'];
2714 $attachments[] = array(
2715 'fullPath' => $pdfFullFilename,
2716 'mime_type' => 'application/pdf',
2717 'cleanName' => 'CiviReport.pdf',
2721 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2722 $this->_outputMode
, $attachments
2724 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2727 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2731 elseif ($this->_outputMode
== 'print') {
2735 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2736 $config = CRM_Core_Config
::singleton();
2737 //get chart image name
2738 $chartImg = $this->_chartId
. '.png';
2739 //get image url path
2740 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2741 $uploadUrl .= $chartImg;
2742 //get image doc path to overwrite
2743 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2745 $chart = imagecreatefrompng($uploadUrl);
2746 //convert it into formattd png
2747 header('Content-type: image/png');
2748 //overwrite with same image
2749 imagepng($chart, $uploadImg);
2751 imagedestroy($chart);
2753 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2755 CRM_Utils_System
::civiExit();
2757 elseif ($this->_outputMode
== 'csv') {
2758 CRM_Report_Utils_Report
::export2csv($this, $rows);
2760 elseif ($this->_outputMode
== 'group') {
2761 $group = $this->_params
['groups'];
2762 $this->add2group($group);
2764 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2765 CRM_Report_Form_Instance
::postProcess($this);
2767 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2768 $this->_outputMode
== 'create_report' ) {
2769 $this->_createNew
= TRUE;
2770 CRM_Report_Form_Instance
::postProcess($this);
2774 function storeResultSet() {
2775 $this->_storeResultSet
= TRUE;
2781 function getResultSet() {
2782 return $this->_resultSet
;
2786 * Get Template file name - use default form template if a specific one has not been set up for this report
2790 * Use the form name to create the tpl file name
2798 function getTemplateFileName(){
2799 $defaultTpl = parent
::getTemplateFileName();
2800 $template = CRM_Core_Smarty
::singleton();
2801 if (!$template->template_exists($defaultTpl)) {
2802 $defaultTpl = 'CRM/Report/Form.tpl';
2808 * Compile the report content
2810 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2815 function compileContent(){
2816 $templateFile = $this->getHookedTemplateFileName();
2817 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2821 function postProcess() {
2822 // get ready with post process params
2823 $this->beginPostProcess();
2826 $sql = $this->buildQuery();
2828 // build array of result based on column headers. This method also allows
2829 // modifying column headers before using it to build result set i.e $rows.
2831 $this->buildRows($sql, $rows);
2833 // format result set.
2834 $this->formatDisplay($rows);
2836 // assign variables to templates
2837 $this->doTemplateAssignment($rows);
2839 // do print / pdf / instance stuff if needed
2840 $this->endPostProcess($rows);
2844 * @param int $rowCount
2846 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2847 // lets do the pager if in html mode
2848 $this->_limit
= NULL;
2850 // CRM-14115, over-ride row count if rowCount is specified in URL
2851 if ($this->_dashBoardRowCount
) {
2852 $rowCount = $this->_dashBoardRowCount
;
2854 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2855 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2857 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2859 if (!$pageId && !empty($_POST)) {
2860 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2861 $pageId = max((int)@$_POST['crmPID_B'], 1);
2863 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2864 $pageId = max((int)@$_POST['crmPID'], 1);
2866 unset($_POST['crmPID_B'], $_POST['crmPID']);
2869 $pageId = $pageId ?
$pageId : 1;
2870 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2871 $offset = ($pageId - 1) * $rowCount;
2873 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2874 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2876 $this->_limit
= " LIMIT $offset, $rowCount";
2877 return array($offset, $rowCount);
2879 if($this->_limitValue
) {
2880 if($this->_offsetValue
) {
2881 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2884 $this->_limit
= " LIMIT " . $this->_limitValue
;
2890 * @param int $rowCount
2892 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2894 // CRM-14115, over-ride row count if rowCount is specified in URL
2895 if ($this->_dashBoardRowCount
) {
2896 $rowCount = $this->_dashBoardRowCount
;
2899 if ($this->_limit
&& ($this->_limit
!= '')) {
2900 $sql = "SELECT FOUND_ROWS();";
2901 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2903 'total' => $this->_rowsFound
,
2904 'rowCount' => $rowCount,
2905 'status' => ts('Records') . ' %%StatusMessage%%',
2906 'buttonBottom' => 'PagerBottomButton',
2907 'buttonTop' => 'PagerTopButton',
2908 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2911 $pager = new CRM_Utils_Pager($params);
2912 $this->assign_by_ref('pager', $pager);
2913 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2924 function whereGroupClause($field, $value, $op) {
2926 $smartGroupQuery = "";
2928 $group = new CRM_Contact_DAO_Group();
2929 $group->is_active
= 1;
2931 $smartGroups = array();
2932 while ($group->fetch()) {
2933 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2934 $smartGroups[] = $group->id
;
2938 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2940 $smartGroupQuery = '';
2941 if (!empty($smartGroups)) {
2942 $smartGroups = implode(',', $smartGroups);
2943 $smartGroupQuery = " UNION DISTINCT
2944 SELECT DISTINCT smartgroup_contact.contact_id
2945 FROM civicrm_group_contact_cache smartgroup_contact
2946 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2949 $sqlOp = $this->getSQLOperator($op);
2950 if (!is_array($value)) {
2951 $value = array($value);
2953 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2955 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2956 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2957 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2958 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2959 {$smartGroupQuery} ) ";
2969 function whereTagClause($field, $value, $op) {
2970 // not using left join in query because if any contact
2971 // belongs to more than one tag, results duplicate
2973 $sqlOp = $this->getSQLOperator($op);
2974 if (!is_array($value)) {
2975 $value = array($value);
2977 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2979 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2980 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2981 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2982 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2986 * @param string $tableAlias
2988 function buildACLClause($tableAlias = 'contact_a') {
2989 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2993 * @param bool $addFields
2994 * @param array $permCustomGroupIds
2996 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2997 if (empty($this->_customGroupExtends
)) {
3000 if (!is_array($this->_customGroupExtends
)) {
3001 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3003 $customGroupWhere = '';
3004 if (!empty($permCustomGroupIds)) {
3005 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
3008 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3009 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3010 FROM civicrm_custom_group cg
3011 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3012 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3014 cg.is_active = 1 AND
3015 cf.is_active = 1 AND
3016 cf.is_searchable = 1
3017 ORDER BY cg.weight, cf.weight";
3018 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3021 while ($customDAO->fetch()) {
3022 if ($customDAO->table_name
!= $curTable) {
3023 $curTable = $customDAO->table_name
;
3024 $curFields = $curFilters = array();
3027 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3028 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3029 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3030 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3033 'fields', 'filters', 'group_bys') as $colKey) {
3034 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3035 $this->_columns
[$curTable][$colKey] = array();
3039 $fieldName = 'custom_' . $customDAO->cf_id
;
3042 // this makes aliasing work in favor
3043 $curFields[$fieldName] = array(
3044 'name' => $customDAO->column_name
,
3045 'title' => $customDAO->label
,
3046 'dataType' => $customDAO->data_type
,
3047 'htmlType' => $customDAO->html_type
,
3050 if ($this->_customGroupFilters
) {
3051 // this makes aliasing work in favor
3052 $curFilters[$fieldName] = array(
3053 'name' => $customDAO->column_name
,
3054 'title' => $customDAO->label
,
3055 'dataType' => $customDAO->data_type
,
3056 'htmlType' => $customDAO->html_type
,
3060 switch ($customDAO->data_type
) {
3063 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3064 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3065 // CRM-6946, show time part for datetime date fields
3066 if ($customDAO->time_format
) {
3067 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3072 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3073 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
3077 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3081 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3082 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3086 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3087 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3091 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3092 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3096 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3098 if (!empty($customDAO->option_group_id
)) {
3099 if (in_array($customDAO->html_type
, array(
3100 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
3101 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3104 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3106 if ($this->_customGroupFilters
) {
3107 $curFilters[$fieldName]['options'] = array();
3108 $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')));
3109 while ($ogDAO->fetch()) {
3110 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3116 case 'StateProvince':
3117 if (in_array($customDAO->html_type
, array(
3118 'Multi-Select State/Province'))) {
3119 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3122 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3124 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3128 if (in_array($customDAO->html_type
, array(
3129 'Multi-Select Country'))) {
3130 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3133 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3135 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3138 case 'ContactReference':
3139 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3140 $curFilters[$fieldName]['name'] = 'display_name';
3141 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3143 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3144 $curFields[$fieldName]['name'] = 'display_name';
3145 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3149 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3150 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3153 if (!array_key_exists('type', $curFields[$fieldName])) {
3154 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3158 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3160 if ($this->_customGroupFilters
) {
3161 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3163 if ($this->_customGroupGroupBy
) {
3164 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3169 function customDataFrom() {
3170 if (empty($this->_customGroupExtends
)) {
3173 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3175 foreach ($this->_columns
as $table => $prop) {
3176 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
3177 $extendsTable = $mapper[$prop['extends']];
3179 // check field is in params
3180 if (!$this->isFieldSelected($prop)) {
3183 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3185 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3187 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3188 // handle for ContactReference
3189 if (array_key_exists('fields', $prop)) {
3190 foreach ($prop['fields'] as $fieldName => $field) {
3191 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
3192 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3194 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3207 function isFieldSelected($prop) {
3212 if (!empty($this->_params
['fields'])) {
3213 foreach (array_keys($prop['fields']) as $fieldAlias) {
3214 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3215 if ($customFieldId) {
3216 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3220 //might be survey response field.
3221 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3228 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3229 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3230 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3236 if (!empty($this->_params
['order_bys'])) {
3237 foreach (array_keys($prop['fields']) as $fieldAlias) {
3238 foreach ($this->_params
['order_bys'] as $orderBy) {
3239 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3246 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3247 foreach ($prop['filters'] as $fieldAlias => $val) {
3249 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3250 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3251 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3252 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3258 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3259 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3270 * Check for empty order_by configurations and remove them; also set
3271 * template to hide them.
3273 function preProcessOrderBy(&$formValues) {
3274 // Object to show/hide form elements
3275 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3277 $_showHide->addShow('optionField_1');
3279 // Cycle through order_by options; skip any empty ones, and hide them as well
3282 if (!empty($formValues['order_bys'])) {
3283 foreach ($formValues['order_bys'] as $order_by) {
3284 if ($order_by['column'] && $order_by['column'] != '-') {
3285 $_showHide->addShow('optionField_' . $n);
3286 $orderBys[$n] = $order_by;
3291 for ($i = $n; $i <= 5; $i++
) {
3293 $_showHide->addHide('optionField_' . $i);
3297 // overwrite order_by options with modified values
3298 if (!empty($orderBys)) {
3299 $formValues['order_bys'] = $orderBys;
3302 $formValues['order_bys'] = array(1 => array('column' => '-'));
3305 // assign show/hide data to template
3306 $_showHide->addToTemplate();
3310 * Does table name have columns in SELECT clause?
3312 * @param string $tableName Name of table (index of $this->_columns array)
3316 function isTableSelected($tableName) {
3317 return in_array($tableName, $this->selectedTables());
3321 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3322 * (building the array if it's unset)
3324 * @return Array $this->_selectedTables
3326 function selectedTables() {
3327 if (!$this->_selectedTables
) {
3328 $orderByColumns = array();
3329 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3330 foreach ($this->_params
['order_bys'] as $orderBy) {
3331 $orderByColumns[] = $orderBy['column'];
3335 foreach ($this->_columns
as $tableName => $table) {
3336 if (array_key_exists('fields', $table)) {
3337 foreach ($table['fields'] as $fieldName => $field) {
3338 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3339 $this->_selectedTables
[] = $tableName;
3344 if (array_key_exists('order_bys', $table)) {
3345 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3346 if (in_array($orderByName, $orderByColumns)) {
3347 $this->_selectedTables
[] = $tableName;
3352 if (array_key_exists('filters', $table)) {
3353 foreach ($table['filters'] as $filterName => $filter) {
3354 if (!empty($this->_params
["{$filterName}_value"]) ||
3355 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3356 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3358 $this->_selectedTables
[] = $tableName;
3365 return $this->_selectedTables
;
3369 * @deprecated - use getAddressColumns which is a more accurate description
3370 * and also accepts an array of options rather than a long list
3372 * function for adding address fields to construct function in reports
3374 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3375 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3376 * @param bool $filters
3377 * @param array $defaults
3379 * @return array address fields for construct clause
3381 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3382 'country_id' => TRUE)) {
3383 $addressFields = array(
3384 'civicrm_address' =>
3386 'dao' => 'CRM_Core_DAO_Address',
3390 array('title' => ts('Address Name'),
3391 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3394 array('title' => ts('Street Address'),
3395 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3397 'supplemental_address_1' =>
3398 array('title' => ts('Supplementary Address Field 1'),
3399 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3401 'supplemental_address_2' =>
3402 array('title' => ts('Supplementary Address Field 2'),
3403 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3407 'name' => 'street_number',
3408 'title' => ts('Street Number'),
3410 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3414 'name' => 'street_name',
3415 'title' => ts('Street Name'),
3417 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3421 'name' => 'street_unit',
3422 'title' => ts('Street Unit'),
3424 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3427 array('title' => ts('City'),
3428 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3431 array('title' => ts('Postal Code'),
3432 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3434 'postal_code_suffix' =>
3435 array('title' => ts('Postal Code Suffix'),
3436 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3439 array('title' => ts('County'),
3440 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3442 'state_province_id' =>
3443 array('title' => ts('State/Province'),
3444 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3447 array('title' => ts('Country'),
3448 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3451 'grouping' => 'location-fields',
3456 $addressFields['civicrm_address']['filters'] = array(
3457 'street_number' => array('title' => ts('Street Number'),
3459 'name' => 'street_number',
3461 'street_name' => array('title' => ts('Street Name'),
3462 'name' => 'street_name',
3463 'operator' => 'like',
3465 'postal_code' => array('title' => ts('Postal Code'),
3467 'name' => 'postal_code',
3469 'city' => array('title' => ts('City'),
3470 'operator' => 'like',
3473 'county_id' => array(
3474 'name' => 'county_id',
3475 'title' => ts('County'),
3476 'type' => CRM_Utils_Type
::T_INT
,
3478 CRM_Report_Form
::OP_MULTISELECT
,
3480 CRM_Core_PseudoConstant
::county(),
3482 'state_province_id' => array(
3483 'name' => 'state_province_id',
3484 'title' => ts('State/Province'),
3485 'type' => CRM_Utils_Type
::T_INT
,
3487 CRM_Report_Form
::OP_MULTISELECT
,
3489 CRM_Core_PseudoConstant
::stateProvince(),
3491 'country_id' => array(
3492 'name' => 'country_id',
3493 'title' => ts('Country'),
3494 'type' => CRM_Utils_Type
::T_INT
,
3496 CRM_Report_Form
::OP_MULTISELECT
,
3498 CRM_Core_PseudoConstant
::country(),
3504 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3505 'street_number' => array('title' => 'Odd / Even Street Number'),
3506 'street_address' => NULL,
3508 'postal_code' => NULL,
3513 $addressFields['civicrm_address']['group_bys'] = array(
3514 'street_address' => NULL,
3516 'postal_code' => NULL,
3517 'state_province_id' =>
3518 array('title' => ts('State/Province'),
3521 array('title' => ts('Country'),
3524 array('title' => ts('County'),
3528 return $addressFields;
3532 * Do AlterDisplay processing on Address Fields
3543 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3544 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3545 $entryFound = FALSE;
3547 if (array_key_exists('civicrm_address_country_id', $row)) {
3548 if ($value = $row['civicrm_address_country_id']) {
3549 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3550 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3551 "reset=1&force=1&{$criteriaQueryParams}&" .
3552 "country_id_op=in&country_id_value={$value}",
3553 $this->_absoluteUrl
, $this->_id
3555 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3556 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3563 if (array_key_exists('civicrm_address_county_id', $row)) {
3564 if ($value = $row['civicrm_address_county_id']) {
3565 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3566 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3567 "reset=1&force=1&{$criteriaQueryParams}&" .
3568 "county_id_op=in&county_id_value={$value}",
3569 $this->_absoluteUrl
, $this->_id
3571 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3572 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3578 // handle state province
3579 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3580 if ($value = $row['civicrm_address_state_province_id']) {
3581 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3583 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3584 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3585 $this->_absoluteUrl
, $this->_id
3587 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3588 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3599 * Adjusts dates passed in to YEAR() for fiscal year.
3606 function fiscalYearOffset($fieldName) {
3607 $config = CRM_Core_Config
::singleton();
3608 $fy = $config->fiscalYearStart
;
3609 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3610 return "YEAR( $fieldName )";
3612 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3616 * Add Address into From Table if required
3618 function addAddressFromClause() {
3619 // include address field if address column is to be included
3620 if ((isset($this->_addressField
) &&
3621 $this->_addressField
3623 $this->isTableSelected('civicrm_address')
3626 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3627 ON ({$this->_aliases['civicrm_contact']}.id =
3628 {$this->_aliases['civicrm_address']}.contact_id) AND
3629 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3634 * Add Phone into From Table if required
3636 function addPhoneFromClause() {
3637 // include address field if address column is to be included
3638 if ($this->isTableSelected('civicrm_phone')
3641 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3642 ON ({$this->_aliases['civicrm_contact']}.id =
3643 {$this->_aliases['civicrm_phone']}.contact_id) AND
3644 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3649 * Get phone columns to add to array
3650 * @param array $options
3651 * - prefix Prefix to add to table (in case of more than one instance of the table)
3652 * - prefix_label Label to give columns from this phone table instance
3653 * @return array phone columns definition
3655 function getPhoneColumns($options = array()){
3656 $defaultOptions = array(
3658 'prefix_label' => '',
3661 $options = array_merge($defaultOptions,$options);
3664 $options['prefix'] . 'civicrm_phone' => array(
3665 'dao' => 'CRM_Core_DAO_Phone',
3667 $options['prefix'] . 'phone' => array(
3668 'title' => ts($options['prefix_label'] . 'Phone'),
3678 * Get address columns to add to array
3679 * @param array $options
3680 * - prefix Prefix to add to table (in case of more than one instance of the table)
3681 * - prefix_label Label to give columns from this address table instance
3682 * @return array address columns definition
3684 function getAddressColumns($options = array()){
3685 $defaultOptions = array(
3687 'prefix_label' => '',
3691 'defaults' => array(
3694 $options = array_merge($defaultOptions,$options);
3695 return $this->addAddressFields(
3696 $options['group_by'],
3697 $options['order_by'],
3698 $options['filters'],
3699 $options['defaults']
3707 function add2group($groupID) {
3708 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3709 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3710 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3712 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3713 $dao = CRM_Core_DAO
::executeQuery($sql);
3715 $contact_ids = array();
3716 // Add resulting contacts to group
3717 while ($dao->fetch()) {
3718 if ($dao->addtogroup_contact_id
) {
3719 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3723 if ( !empty($contact_ids) ) {
3724 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3725 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3728 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3733 /* function used for showing charts on print screen */
3734 static function uploadChartImage() {
3735 // upload strictly for '.png' images
3736 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3737 if (preg_match('/\.png$/', $name)) {
3739 // POST data is usually string data, but we are passing a RAW .png
3740 // so PHP is a bit confused and $_POST is empty. But it has saved
3741 // the raw bits into $HTTP_RAW_POST_DATA
3743 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3745 // prepare the directory
3746 $config = CRM_Core_Config
::singleton();
3747 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3748 if (!file_exists($defaultPath)) {
3749 mkdir($defaultPath, 0777, TRUE);
3752 // full path to the saved image including filename
3753 $destination = $defaultPath . $name;
3756 $jfh = fopen($destination, 'w') or die("can't open file");
3757 fwrite($jfh, $httpRawPostData);
3759 CRM_Utils_System
::civiExit();