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);
971 $stateCountryMap[] = array(
972 'country' => 'country_id_value',
973 'state_province' => 'state_province_id_value',
974 'county' => 'county_id_value'
976 CRM_Core_BAO_Address
::addStateCountryMap($stateCountryMap);
978 $this->assign('filters', $filters);
981 function addOptions() {
982 if (!empty($this->_options
)) {
983 // FIXME: For now lets build all elements as checkboxes.
984 // Once we clear with the format we can build elements based on type
987 foreach ($this->_options
as $fieldName => $field) {
988 if ($field['type'] == 'select') {
989 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
991 else if ($field['type'] == 'checkbox') {
992 $options[$field['title']] = $fieldName;
993 $this->addCheckBox($fieldName, NULL,
995 NULL, NULL, NULL, $this->_fourColumnAttribute
1000 $this->assign('otherOptions', $this->_options
);
1003 function addChartOptions() {
1004 if (!empty($this->_charts
)) {
1005 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
1006 $this->assign('charts', $this->_charts
);
1007 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1011 function addGroupBys() {
1012 $options = $freqElements = array();
1014 foreach ($this->_columns
as $tableName => $table) {
1015 if (array_key_exists('group_bys', $table)) {
1016 foreach ($table['group_bys'] as $fieldName => $field) {
1017 if (!empty($field)) {
1018 $options[$field['title']] = $fieldName;
1019 if (!empty($field['frequency'])) {
1020 $freqElements[$field['title']] = $fieldName;
1026 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1027 NULL, NULL, NULL, $this->_fourColumnAttribute
1029 $this->assign('groupByElements', $options);
1031 foreach ($freqElements as $name) {
1032 $this->addElement('select', "group_bys_freq[$name]",
1033 ts('Frequency'), $this->_groupByDateFreq
1038 function addOrderBys() {
1040 foreach ($this->_columns
as $tableName => $table) {
1042 // Report developer may define any column to order by; include these as order-by options
1043 if (array_key_exists('order_bys', $table)) {
1044 foreach ($table['order_bys'] as $fieldName => $field) {
1045 if (!empty($field)) {
1046 $options[$fieldName] = $field['title'];
1051 /* Add searchable custom fields as order-by options, if so requested
1052 * (These are already indexed, so allowing to order on them is cheap.)
1056 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1057 foreach ($table['fields'] as $fieldName => $field) {
1058 if (empty($field['no_display'])) {
1059 $options[$fieldName] = $field['title'];
1067 $this->assign('orderByOptions', $options);
1069 if (!empty($options)) {
1071 '-' => ' - none - ') +
$options;
1072 for ($i = 1; $i <= 5; $i++
) {
1073 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1074 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1075 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1076 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1081 function buildInstanceAndButtons() {
1082 CRM_Report_Form_Instance
::buildForm($this);
1084 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1086 $this->addElement('submit', $this->_instanceButtonName
, $label);
1087 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1088 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1091 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1093 if ($this->_instanceForm
) {
1094 $this->assign('instanceForm', TRUE);
1097 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1098 $this->addElement('submit', $this->_printButtonName
, $label);
1100 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1101 $this->addElement('submit', $this->_pdfButtonName
, $label);
1103 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1105 if ($this->_csvSupported
) {
1106 $this->addElement('submit', $this->_csvButtonName
, $label);
1109 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1110 $this->addElement('select', 'groups', ts('Group'),
1111 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
1113 $this->assign('group', TRUE);
1116 $label = ts('Add These Contacts to Group');
1117 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1119 $this->addChartOptions();
1120 $this->addButtons(array(
1123 'name' => ts('Preview Report'),
1124 'isDefault' => TRUE,
1130 function buildQuickForm() {
1131 $this->addColumns();
1133 $this->addFilters();
1135 $this->addOptions();
1137 $this->addGroupBys();
1139 $this->addOrderBys();
1141 $this->buildInstanceAndButtons();
1143 //add form rule for report
1144 if (is_callable(array(
1145 $this, 'formRule'))) {
1146 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1150 // a formrule function to ensure that fields selected in group_by
1151 // (if any) should only be the ones present in display/select fields criteria;
1152 // note: works if and only if any custom field selected in group_by.
1155 * @param array $ignoreFields
1159 function customDataFormRule($fields, $ignoreFields = array( )) {
1161 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1162 foreach ($this->_columns
as $tableName => $table) {
1163 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1164 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1165 if (array_key_exists($fieldName, $fields['group_bys']) &&
1166 !array_key_exists($fieldName, $fields['fields'])
1168 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1170 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1171 foreach ($fields['fields'] as $fld => $val) {
1172 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1173 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1184 // Note: $fieldName param allows inheriting class to build operationPairs
1185 // specific to a field.
1187 * @param string $type
1188 * @param null $fieldName
1192 function getOperationPair($type = "string", $fieldName = NULL) {
1193 // FIXME: At some point we should move these key-val pairs
1194 // to option_group and option_value table.
1196 case CRM_Report_Form
::OP_INT
:
1197 case CRM_Report_Form
::OP_FLOAT
:
1199 'lte' => ts('Is less than or equal to'),
1200 'gte' => ts('Is greater than or equal to'),
1201 'bw' => ts('Is between'),
1202 'eq' => ts('Is equal to'),
1203 'lt' => ts('Is less than'),
1204 'gt' => ts('Is greater than'),
1205 'neq' => ts('Is not equal to'),
1206 'nbw' => ts('Is not between'),
1207 'nll' => ts('Is empty (Null)'),
1208 'nnll' => ts('Is not empty (Null)'),
1212 case CRM_Report_Form
::OP_SELECT
:
1214 'eq' => ts('Is equal to'),
1217 case CRM_Report_Form
::OP_MONTH
:
1218 case CRM_Report_Form
::OP_MULTISELECT
:
1220 'in' => ts('Is one of'),
1221 'notin' => ts('Is not one of'),
1225 case CRM_Report_Form
::OP_DATE
:
1227 'nll' => ts('Is empty (Null)'),
1228 'nnll' => ts('Is not empty (Null)'),
1232 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1233 // use this operator for the values, concatenated with separator. For e.g if
1234 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1236 'mhas' => ts('Is one of'),
1237 'mnot' => ts('Is not one of'),
1243 'has' => ts('Contains'),
1244 'sw' => ts('Starts with'),
1245 'ew' => ts('Ends with'),
1246 'nhas' => ts('Does not contain'),
1247 'eq' => ts('Is equal to'),
1248 'neq' => ts('Is not equal to'),
1249 'nll' => ts('Is empty (Null)'),
1250 'nnll' => ts('Is not empty (Null)'),
1255 function buildTagFilter() {
1256 $contactTags = CRM_Core_BAO_Tag
::getTags();
1257 if (!empty($contactTags)) {
1258 $this->_columns
['civicrm_tag'] = array(
1259 'dao' => 'CRM_Core_DAO_Tag',
1265 'title' => ts('Tag'),
1267 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1268 'options' => $contactTags,
1276 * Adds group filters to _columns (called from _Constuct
1278 function buildGroupFilter() {
1279 $this->_columns
['civicrm_group']['filters'] = array(
1282 'name' => 'group_id',
1283 'title' => ts('Group'),
1284 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1286 'options' => CRM_Core_PseudoConstant
::group(),
1289 if (empty($this->_columns
['civicrm_group']['dao'])) {
1290 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1292 if (empty($this->_columns
['civicrm_group']['alias'])) {
1293 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1298 * @param string $operator
1302 function getSQLOperator($operator = "like") {
1303 switch ($operator) {
1336 return 'IS NOT NULL';
1351 * @return null|string
1353 function whereClause(&$field, $op,
1357 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1363 if (($min !== NULL && strlen($min) > 0) ||
1364 ($max !== NULL && strlen($max) > 0)
1366 $min = CRM_Utils_Type
::escape($min, $type);
1367 $max = CRM_Utils_Type
::escape($max, $type);
1371 $clauses[] = "( {$field['dbAlias']} >= $min )";
1374 $clauses[] = "( {$field['dbAlias']} < $min )";
1379 $clauses[] = "( {$field['dbAlias']} <= $max )";
1382 $clauses[] = "( {$field['dbAlias']} > $max )";
1386 if (!empty($clauses)) {
1388 $clause = implode(' AND ', $clauses);
1391 $clause = implode(' OR ', $clauses);
1399 if ($value !== NULL && strlen($value) > 0) {
1400 $value = CRM_Utils_Type
::escape($value, $type);
1401 if (strpos($value, '%') === FALSE) {
1402 $value = "'%{$value}%'";
1405 $value = "'{$value}'";
1407 $sqlOP = $this->getSQLOperator($op);
1408 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1414 if ($value !== NULL && is_array($value) && count($value) > 0) {
1415 $sqlOP = $this->getSQLOperator($op);
1416 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1417 //cycle through selections and esacape values
1418 foreach ($value as $key => $selection) {
1419 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1421 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1424 // for numerical values
1425 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1427 if ($op == 'notin') {
1428 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1431 $clause = "( " . $clause . " )";
1437 // mhas == multiple has
1438 if ($value !== NULL && count($value) > 0) {
1439 $sqlOP = $this->getSQLOperator($op);
1440 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1445 // mnot == multiple is not one of
1446 if ($value !== NULL && count($value) > 0) {
1447 $sqlOP = $this->getSQLOperator($op);
1448 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1454 if ($value !== NULL && strlen($value) > 0) {
1455 $value = CRM_Utils_Type
::escape($value, $type);
1456 if (strpos($value, '%') === FALSE) {
1458 $value = "'{$value}%'";
1461 $value = "'%{$value}'";
1465 $value = "'{$value}'";
1467 $sqlOP = $this->getSQLOperator($op);
1468 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1474 $sqlOP = $this->getSQLOperator($op);
1475 $clause = "( {$field['dbAlias']} $sqlOP )";
1479 if ($value !== NULL && strlen($value) > 0) {
1480 if (isset($field['clause'])) {
1481 // FIXME: we not doing escape here. Better solution is to use two
1482 // different types - data-type and filter-type
1483 $clause = $field['clause'];
1486 $value = CRM_Utils_Type
::escape($value, $type);
1487 $sqlOP = $this->getSQLOperator($op);
1488 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1489 $value = "'{$value}'";
1491 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1497 if (!empty($field['group']) && $clause) {
1498 $clause = $this->whereGroupClause($field, $value, $op);
1500 elseif (!empty($field['tag']) && $clause) {
1501 // not using left join in query because if any contact
1502 // belongs to more than one tag, results duplicate
1504 $clause = $this->whereTagClause($field, $value, $op);
1506 elseif (!empty($field['membership_org']) && $clause) {
1507 $clause = $this->whereMembershipOrgClause($field, $value, $op);
1509 elseif (!empty($field['membership_type']) && $clause) {
1510 $clause = $this->whereMembershipTypeClause($field, $value, $op);
1521 * @param null $fromTime
1522 * @param null $toTime
1524 * @return null|string
1526 function dateClause($fieldName,
1527 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1530 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1531 $sqlOP = $this->getSQLOperator($relative);
1532 return "( {$fieldName} {$sqlOP} )";
1535 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1538 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1539 $clauses[] = "( {$fieldName} >= $from )";
1543 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1544 $clauses[] = "( {$fieldName} <= {$to} )";
1547 if (!empty($clauses)) {
1548 return implode(' AND ', $clauses);
1554 * @todo - could not find any instances where this is called
1555 * @param unknown_type $relative
1556 * @param String $from
1557 * @param String_type $to
1558 * @return string|NULL
1560 function dateDisplay($relative, $from, $to) {
1561 list($from, $to) = $this->getFromTo($relative, $from, $to);
1564 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1567 $clauses[] = 'Past';
1571 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1574 $clauses[] = 'Today';
1577 if (!empty($clauses)) {
1578 return implode(' - ', $clauses);
1588 * @param null $fromtime
1589 * @param null $totime
1593 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1594 if (empty($totime)) {
1597 //FIX ME not working for relative
1599 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1600 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1601 $from = substr($dateRange['from'], 0, 8);
1602 //Take only Date Part, Sometime Time part is also present in 'to'
1603 $to = substr($dateRange['to'], 0, 8);
1605 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1606 $to = CRM_Utils_Date
::processDate($to, $totime);
1607 return array($from, $to);
1613 function alterDisplay(&$rows) {
1614 // custom code to alter rows
1620 function alterCustomDataDisplay(&$rows) {
1621 // custom code to alter rows having custom values
1622 if (empty($this->_customGroupExtends
)) {
1626 $customFieldIds = array();
1627 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1628 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1629 $customFieldIds[$fieldAlias] = $fieldId;
1632 if (empty($customFieldIds)) {
1636 $customFields = $fieldValueMap = array();
1637 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1639 // skip for type date and ContactReference since date format is already handled
1641 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1642 FROM civicrm_custom_field cf
1643 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1644 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1645 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1646 cg.is_active = 1 AND
1647 cf.is_active = 1 AND
1648 cf.is_searchable = 1 AND
1649 cf.data_type NOT IN ('ContactReference', 'Date') AND
1650 cf.id IN (" . implode(",", $customFieldIds) . ")";
1652 $dao = CRM_Core_DAO
::executeQuery($query);
1653 while ($dao->fetch()) {
1654 foreach ($customFieldCols as $key) {
1655 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1657 if ($dao->option_group_id
) {
1658 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1663 $entryFound = FALSE;
1664 foreach ($rows as $rowNum => $row) {
1665 foreach ($row as $tableCol => $val) {
1666 if (array_key_exists($tableCol, $customFields)) {
1667 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1672 // skip looking further in rows, if first row itself doesn't
1673 // have the column we need
1682 * @param $customField
1683 * @param $fieldValueMap
1685 * @return float|string
1687 function formatCustomValues($value, $customField, $fieldValueMap) {
1688 if (CRM_Utils_System
::isNull($value)) {
1692 $htmlType = $customField['html_type'];
1694 switch ($customField['data_type']) {
1696 if ($value == '1') {
1697 $retValue = ts('Yes');
1700 $retValue = ts('No');
1705 $retValue = CRM_Utils_System
::formatWikiURL($value);
1717 if ($htmlType == 'Text') {
1718 $retValue = (float)$value;
1722 if ($htmlType == 'Text') {
1732 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1737 if (in_array($htmlType, array(
1738 'Text', 'TextArea'))) {
1742 case 'StateProvince':
1745 switch ($htmlType) {
1746 case 'Multi-Select Country':
1747 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1748 $customData = array();
1749 foreach ($value as $val) {
1751 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1754 $retValue = implode(', ', $customData);
1757 case 'Select Country':
1758 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1761 case 'Select State/Province':
1762 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1765 case 'Multi-Select State/Province':
1766 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1767 $customData = array();
1768 foreach ($value as $val) {
1770 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1773 $retValue = implode(', ', $customData);
1778 case 'Autocomplete-Select':
1779 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1783 case 'AdvMulti-Select':
1784 case 'Multi-Select':
1785 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1786 $customData = array();
1787 foreach ($value as $val) {
1789 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1792 $retValue = implode(', ', $customData);
1810 function removeDuplicates(&$rows) {
1811 if (empty($this->_noRepeats
)) {
1814 $checkList = array();
1816 foreach ($rows as $key => $list) {
1817 foreach ($list as $colName => $colVal) {
1818 if (array_key_exists($colName, $checkList) &&
1819 $checkList[$colName] == $colVal) {
1820 $rows[$key][$colName] = "";
1822 if (in_array($colName, $this->_noRepeats
)) {
1823 $checkList[$colName] = $colVal;
1832 * @param bool $subtotal
1834 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1835 foreach ($row as $colName => $colVal) {
1836 if (in_array($colName, $fields)) {
1837 $row[$colName] = $row[$colName];
1839 elseif (isset($this->_columnHeaders
[$colName])) {
1841 $row[$colName] = "Subtotal";
1845 unset($row[$colName]);
1856 function grandTotal(&$rows) {
1857 if (!$this->_rollup ||
($this->_rollup
== '') ||
1858 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1862 $lastRow = array_pop($rows);
1864 foreach ($this->_columnHeaders
as $fld => $val) {
1865 if (!in_array($fld, $this->_statFields
)) {
1866 if (!$this->_grandFlag
) {
1867 $lastRow[$fld] = "Grand Total";
1868 $this->_grandFlag
= TRUE;
1871 $lastRow[$fld] = "";
1876 $this->assign('grandStat', $lastRow);
1882 * @param bool $pager
1884 function formatDisplay(&$rows, $pager = TRUE) {
1885 // set pager based on if any limit was applied in the query.
1890 // allow building charts if any
1891 if (!empty($this->_params
['charts']) && !empty($rows)) {
1892 $this->buildChart($rows);
1893 $this->assign('chartEnabled', TRUE);
1894 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1895 $this->assign('chartId', $this->_chartId
);
1898 // unset columns not to be displayed.
1899 foreach ($this->_columnHeaders
as $key => $value) {
1900 if (!empty($value['no_display'])) {
1901 unset($this->_columnHeaders
[$key]);
1905 // unset columns not to be displayed.
1906 if (!empty($rows)) {
1907 foreach ($this->_noDisplay
as $noDisplayField) {
1908 foreach ($rows as $rowNum => $row) {
1909 unset($this->_columnHeaders
[$noDisplayField]);
1914 // build array of section totals
1915 $this->sectionTotals();
1917 // process grand-total row
1918 $this->grandTotal($rows);
1920 // use this method for formatting rows for display purpose.
1921 $this->alterDisplay($rows);
1922 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1924 // use this method for formatting custom rows for display purpose.
1925 $this->alterCustomDataDisplay($rows);
1931 function buildChart(&$rows) {
1932 // override this method for building charts.
1935 // select() method below has been added recently (v3.3), and many of the report templates might
1936 // still be having their own select() method. We should fix them as and when encountered and move
1937 // towards generalizing the select() method below.
1939 $select = $this->_selectAliases
= array();
1941 foreach ($this->_columns
as $tableName => $table) {
1942 if (array_key_exists('fields', $table)) {
1943 foreach ($table['fields'] as $fieldName => $field) {
1944 if ($tableName == 'civicrm_address') {
1945 $this->_addressField
= TRUE;
1947 if ($tableName == 'civicrm_email') {
1948 $this->_emailField
= TRUE;
1950 if ($tableName == 'civicrm_phone') {
1951 $this->_phoneField
= TRUE;
1954 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1956 // 1. In many cases we want select clause to be built in slightly different way
1957 // for a particular field of a particular type.
1958 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1960 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1961 if ($selectClause) {
1962 $select[] = $selectClause;
1966 // include statistics columns only if set
1967 if (!empty($field['statistics'])) {
1968 foreach ($field['statistics'] as $stat => $label) {
1969 $alias = "{$tableName}_{$fieldName}_{$stat}";
1970 switch (strtolower($stat)) {
1973 $select[] = "$stat({$field['dbAlias']}) as $alias";
1974 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1975 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1976 $this->_statFields
[$label] = $alias;
1977 $this->_selectAliases
[] = $alias;
1981 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1982 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1983 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1984 $this->_statFields
[$label] = $alias;
1985 $this->_selectAliases
[] = $alias;
1988 case 'count_distinct':
1989 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1990 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1991 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1992 $this->_statFields
[$label] = $alias;
1993 $this->_selectAliases
[] = $alias;
1997 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1998 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1999 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2000 $this->_statFields
[$label] = $alias;
2001 $this->_selectAliases
[] = $alias;
2007 $alias = "{$tableName}_{$fieldName}";
2008 $select[] = "{$field['dbAlias']} as $alias";
2009 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2010 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2011 $this->_selectAliases
[] = $alias;
2017 // select for group bys
2018 if (array_key_exists('group_bys', $table)) {
2019 foreach ($table['group_bys'] as $fieldName => $field) {
2021 if ($tableName == 'civicrm_address') {
2022 $this->_addressField
= TRUE;
2024 if ($tableName == 'civicrm_email') {
2025 $this->_emailField
= TRUE;
2027 if ($tableName == 'civicrm_phone') {
2028 $this->_phoneField
= TRUE;
2030 // 1. In many cases we want select clause to be built in slightly different way
2031 // for a particular field of a particular type.
2032 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2034 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2035 if ($selectClause) {
2036 $select[] = $selectClause;
2040 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
2041 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2043 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2044 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2045 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2046 $field['title'] = 'Week';
2050 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2051 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2052 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2053 $field['title'] = 'Year';
2057 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2058 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2059 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2060 $field['title'] = 'Month';
2064 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2065 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2066 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2067 $field['title'] = 'Quarter';
2070 // for graphs and charts -
2071 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2072 $this->_interval
= $field['title'];
2073 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
2074 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2075 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2077 // just to make sure these values are transfered to rows.
2078 // since we 'll need them for calculation purpose,
2079 // e.g making subtotals look nicer or graphs
2080 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2081 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2088 $this->_selectClauses
= $select;
2089 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2100 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2105 $this->storeWhereHavingClauseArray();
2107 if (empty($this->_whereClauses
)) {
2108 $this->_where
= "WHERE ( 1 ) ";
2109 $this->_having
= "";
2112 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2115 if ($this->_aclWhere
) {
2116 $this->_where
.= " AND {$this->_aclWhere} ";
2119 if (!empty($this->_havingClauses
)) {
2120 // use this clause to construct group by clause.
2121 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2126 * Store Where clauses into an array - breaking out this step makes
2127 * over-riding more flexible as the clauses can be used in constructing a
2128 * temp table that may not be part of the final where clause or added
2129 * in other functions
2131 function storeWhereHavingClauseArray(){
2132 foreach ($this->_columns
as $tableName => $table) {
2133 if (array_key_exists('filters', $table)) {
2134 foreach ($table['filters'] as $fieldName => $field) {
2135 // respect pseudofield to filter spec so fields can be marked as
2136 // not to be handled here
2137 if(!empty($field['pseudofield'])){
2141 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2142 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2143 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2144 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2145 if (is_array($value) && !empty($value)) {
2146 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2150 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2151 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2152 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2153 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2154 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2155 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2159 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2161 $clause = $this->whereClause($field,
2163 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2164 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2165 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2170 if (!empty($clause)) {
2171 if (!empty($field['having'])) {
2172 $this->_havingClauses
[] = $clause;
2175 $this->_whereClauses
[] = $clause;
2183 function processReportMode() {
2184 $buttonName = $this->controller
->getButtonName();
2186 $output = CRM_Utils_Request
::retrieve(
2189 CRM_Core_DAO
::$_nullObject
2193 CRM_Utils_Request
::retrieve(
2196 CRM_Core_DAO
::$_nullObject
2199 $this->_absoluteUrl
= FALSE;
2201 $this->assign('printOnly', FALSE);
2203 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2204 $this->assign('printOnly', TRUE);
2206 $this->assign('outputMode', 'print');
2207 $this->_outputMode
= 'print';
2208 if ($this->_sendmail
) {
2209 $this->_absoluteUrl
= TRUE;
2212 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2213 $this->assign('printOnly', TRUE);
2215 $this->assign('outputMode', 'pdf');
2216 $this->_outputMode
= 'pdf';
2217 $this->_absoluteUrl
= TRUE;
2219 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2220 $this->assign('printOnly', TRUE);
2222 $this->assign('outputMode', 'csv');
2223 $this->_outputMode
= 'csv';
2224 $this->_absoluteUrl
= TRUE;
2226 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2227 $this->assign('outputMode', 'group');
2228 $this->_outputMode
= 'group';
2230 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2231 $this->assign('outputMode', 'create_report');
2232 $this->_outputMode
= 'create_report';
2235 $this->assign('outputMode', 'html');
2236 $this->_outputMode
= 'html';
2239 // Get today's date to include in printed reports
2241 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2242 $this->assign('reportDate', $reportDate);
2246 function beginPostProcess() {
2247 $this->setParams($this->controller
->exportValues($this->_name
));
2249 if (empty($this->_params
) &&
2252 $this->setParams($this->_formValues
);
2255 // hack to fix params when submitted from dashboard, CRM-8532
2256 // fields array is missing because form building etc is skipped
2257 // in dashboard mode for report
2258 //@todo - this could be done in the dashboard no we have a setter
2259 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2260 $this->setParams($this->_formValues
);
2263 $this->_formValues
= $this->_params
;
2264 if (CRM_Core_Permission
::check('administer Reports') &&
2265 isset($this->_id
) &&
2266 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2267 $this->_chartButtonName
== $this->controller
->getButtonName()
2270 $this->assign('updateReportButton', TRUE);
2272 $this->processReportMode();
2273 $this->beginPostProcessCommon();
2277 * beginPostProcess function run in both report mode and non-report mode (api)
2279 function beginPostProcessCommon() {
2284 * @param bool $applyLimit
2288 function buildQuery($applyLimit = TRUE) {
2291 $this->customDataFrom();
2296 // order_by columns not selected for display need to be included in SELECT
2297 $unselectedSectionColumns = $this->unselectedSectionColumns();
2298 foreach ($unselectedSectionColumns as $alias => $section) {
2299 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2302 if ($applyLimit && empty($this->_params
['charts'])) {
2305 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2307 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2311 function groupBy() {
2312 $groupBys = array();
2313 if (!empty($this->_params
['group_bys']) &&
2314 is_array($this->_params
['group_bys']) &&
2315 !empty($this->_params
['group_bys'])
2317 foreach ($this->_columns
as $tableName => $table) {
2318 if (array_key_exists('group_bys', $table)) {
2319 foreach ($table['group_bys'] as $fieldName => $field) {
2320 if (!empty($this->_params
['group_bys'][$fieldName])) {
2321 $groupBys[] = $field['dbAlias'];
2328 if (!empty($groupBys)) {
2329 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2333 function orderBy() {
2334 $this->_orderBy
= "";
2335 $this->_sections
= array();
2336 $this->storeOrderByArray();
2337 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2338 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2340 $this->assign('sections', $this->_sections
);
2344 * In some cases other functions want to know which fields are selected for ordering by
2345 * Separating this into a separate function allows it to be called separately from constructing
2346 * the order by clause
2348 function storeOrderByArray() {
2349 $orderBys = array();
2351 if (!empty($this->_params
['order_bys']) &&
2352 is_array($this->_params
['order_bys']) &&
2353 !empty($this->_params
['order_bys'])
2356 // Proces order_bys in user-specified order
2357 foreach ($this->_params
['order_bys'] as $orderBy) {
2358 $orderByField = array();
2359 foreach ($this->_columns
as $tableName => $table) {
2360 if (array_key_exists('order_bys', $table)) {
2361 // For DAO columns defined in $this->_columns
2362 $fields = $table['order_bys'];
2364 elseif (array_key_exists('extends', $table)) {
2365 // For custom fields referenced in $this->_customGroupExtends
2366 $fields = CRM_Utils_Array
::value('fields', $table, array());
2368 if (!empty($fields) && is_array($fields)) {
2369 foreach ($fields as $fieldName => $field) {
2370 if ($fieldName == $orderBy['column']) {
2371 $orderByField = array_merge($field, $orderBy);
2372 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2379 if (!empty($orderByField)) {
2380 $this->_orderByFields
[] = $orderByField;
2381 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2383 // Record any section headers for assignment to the template
2384 if (!empty($orderBy['section'])) {
2385 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2386 $this->_sections
[$orderByField['tplField']] = $orderByField;
2392 $this->_orderByArray
= $orderBys;
2394 $this->assign('sections', $this->_sections
);
2400 function unselectedSectionColumns() {
2401 $selectColumns = array();
2402 foreach ($this->_columns
as $tableName => $table) {
2403 if (array_key_exists('fields', $table)) {
2404 foreach ($table['fields'] as $fieldName => $field) {
2405 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2407 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2413 if (is_array($this->_sections
)) {
2414 return array_diff_key($this->_sections
, $selectColumns);
2425 function buildRows($sql, &$rows) {
2426 $dao = CRM_Core_DAO
::executeQuery($sql);
2427 if (!is_array($rows)) {
2431 // use this method to modify $this->_columnHeaders
2432 $this->modifyColumnHeaders();
2434 $unselectedSectionColumns = $this->unselectedSectionColumns();
2436 while ($dao->fetch()) {
2438 foreach ($this->_columnHeaders
as $key => $value) {
2439 if (property_exists($dao, $key)) {
2440 $row[$key] = $dao->$key;
2444 // section headers not selected for display need to be added to row
2445 foreach ($unselectedSectionColumns as $key => $values) {
2446 if (property_exists($dao, $key)) {
2447 $row[$key] = $dao->$key;
2456 * When "order by" fields are marked as sections, this assigns to the template
2457 * an array of total counts for each section. This data is used by the Smarty
2458 * plugin {sectionTotal}
2460 function sectionTotals() {
2462 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2463 if (empty($this->_selectAliases
)) {
2467 if (!empty($this->_sections
)) {
2468 // build the query with no LIMIT clause
2469 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2470 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2472 // pull section aliases out of $this->_sections
2473 $sectionAliases = array_keys($this->_sections
);
2476 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2477 $ifnulls[] = "ifnull($alias, '') as $alias";
2480 /* Group (un-limited) report by all aliases and get counts. This might
2481 * be done more efficiently when the contents of $sql are known, ie. by
2482 * overriding this method in the report class.
2486 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2488 // initialize array of total counts
2490 $dao = CRM_Core_DAO
::executeQuery($query);
2491 while ($dao->fetch()) {
2493 // let $this->_alterDisplay translate any integer ids to human-readable values.
2494 $rows[0] = $dao->toArray();
2495 $this->alterDisplay($rows);
2498 // add totals for all permutations of section values
2501 $aliasCount = count($sectionAliases);
2502 foreach ($sectionAliases as $alias) {
2503 $values[] = $row[$alias];
2504 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2505 if ($i == $aliasCount) {
2506 // the last alias is the lowest-level section header; use count as-is
2507 $totals[$key] = $dao->ct
;
2510 // other aliases are higher level; roll count into their total
2511 $totals[$key] +
= $dao->ct
;
2515 $this->assign('sectionTotals', $totals);
2519 function modifyColumnHeaders() {
2520 // use this method to modify $this->_columnHeaders
2526 function doTemplateAssignment(&$rows) {
2527 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2528 $this->assign_by_ref('rows', $rows);
2529 $this->assign('statistics', $this->statistics($rows));
2532 // override this method to build your own statistics
2538 function statistics(&$rows) {
2539 $statistics = array();
2541 $count = count($rows);
2543 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2547 $this->countStat($statistics, $count);
2549 $this->groupByStat($statistics);
2551 $this->filterStat($statistics);
2557 * @param $statistics
2560 function countStat(&$statistics, $count) {
2561 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2565 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2566 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2567 'value' => $this->_rowsFound
,
2573 * @param $statistics
2575 function groupByStat(&$statistics) {
2576 if (!empty($this->_params
['group_bys']) &&
2577 is_array($this->_params
['group_bys']) &&
2578 !empty($this->_params
['group_bys'])
2580 foreach ($this->_columns
as $tableName => $table) {
2581 if (array_key_exists('group_bys', $table)) {
2582 foreach ($table['group_bys'] as $fieldName => $field) {
2583 if (!empty($this->_params
['group_bys'][$fieldName])) {
2584 $combinations[] = $field['title'];
2589 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2590 'value' => implode(' & ', $combinations),
2596 * @param $statistics
2598 function filterStat(&$statistics) {
2599 foreach ($this->_columns
as $tableName => $table) {
2600 if (array_key_exists('filters', $table)) {
2601 foreach ($table['filters'] as $fieldName => $field) {
2602 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2605 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2606 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2607 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2608 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2609 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2611 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2612 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2614 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2615 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2618 $statistics['filters'][] = array(
2619 'title' => $field['title'],
2620 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2623 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2624 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2626 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2627 $statistics['filters'][] = array(
2628 'title' => $field['title'],
2629 'value' => $pair[$rel],
2634 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2637 $pair = $this->getOperationPair(
2638 CRM_Utils_Array
::value('operatorType', $field),
2641 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2642 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2643 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2644 if (in_array($op, array(
2645 'bw', 'nbw')) && ($min ||
$max)) {
2646 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2648 elseif ($op == 'nll' ||
$op == 'nnll') {
2649 $value = $pair[$op];
2651 elseif (is_array($val) && (!empty($val))) {
2652 $options = CRM_Utils_Array
::value('options', $field, array());
2653 foreach ($val as $key => $valIds) {
2654 if (isset($options[$valIds])) {
2655 $val[$key] = $options[$valIds];
2658 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2659 $val = implode(', ', $val);
2660 $value = "{$pair[$op]} " . $val;
2662 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2663 is_array($field['options']) && !empty($field['options'])
2665 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2668 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2672 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2685 function endPostProcess(&$rows = NULL) {
2686 if ( $this->_storeResultSet
) {
2687 $this->_resultSet
= $rows;
2690 if ($this->_outputMode
== 'print' ||
2691 $this->_outputMode
== 'pdf' ||
2695 $content = $this->compileContent();
2696 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2700 if ($this->_sendmail
) {
2701 $config = CRM_Core_Config
::singleton();
2702 $attachments = array();
2704 if ($this->_outputMode
== 'csv') {
2705 $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'];
2707 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2708 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2709 file_put_contents($csvFullFilename, $csvContent);
2710 $attachments[] = array(
2711 'fullPath' => $csvFullFilename,
2712 'mime_type' => 'text/csv',
2713 'cleanName' => 'CiviReport.csv',
2716 if ($this->_outputMode
== 'pdf') {
2717 // generate PDF content
2718 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2719 file_put_contents($pdfFullFilename,
2720 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2721 TRUE, array('orientation' => 'landscape')
2724 // generate Email Content
2725 $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'];
2727 $attachments[] = array(
2728 'fullPath' => $pdfFullFilename,
2729 'mime_type' => 'application/pdf',
2730 'cleanName' => 'CiviReport.pdf',
2734 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2735 $this->_outputMode
, $attachments
2737 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2740 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2744 elseif ($this->_outputMode
== 'print') {
2748 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2749 $config = CRM_Core_Config
::singleton();
2750 //get chart image name
2751 $chartImg = $this->_chartId
. '.png';
2752 //get image url path
2753 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2754 $uploadUrl .= $chartImg;
2755 //get image doc path to overwrite
2756 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2758 $chart = imagecreatefrompng($uploadUrl);
2759 //convert it into formattd png
2760 header('Content-type: image/png');
2761 //overwrite with same image
2762 imagepng($chart, $uploadImg);
2764 imagedestroy($chart);
2766 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2768 CRM_Utils_System
::civiExit();
2770 elseif ($this->_outputMode
== 'csv') {
2771 CRM_Report_Utils_Report
::export2csv($this, $rows);
2773 elseif ($this->_outputMode
== 'group') {
2774 $group = $this->_params
['groups'];
2775 $this->add2group($group);
2777 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2778 CRM_Report_Form_Instance
::postProcess($this);
2780 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2781 $this->_outputMode
== 'create_report' ) {
2782 $this->_createNew
= TRUE;
2783 CRM_Report_Form_Instance
::postProcess($this);
2787 function storeResultSet() {
2788 $this->_storeResultSet
= TRUE;
2794 function getResultSet() {
2795 return $this->_resultSet
;
2799 * Get Template file name - use default form template if a specific one has not been set up for this report
2803 * Use the form name to create the tpl file name
2811 function getTemplateFileName(){
2812 $defaultTpl = parent
::getTemplateFileName();
2813 $template = CRM_Core_Smarty
::singleton();
2814 if (!$template->template_exists($defaultTpl)) {
2815 $defaultTpl = 'CRM/Report/Form.tpl';
2821 * Compile the report content
2823 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2828 function compileContent(){
2829 $templateFile = $this->getHookedTemplateFileName();
2830 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2834 function postProcess() {
2835 // get ready with post process params
2836 $this->beginPostProcess();
2839 $sql = $this->buildQuery();
2841 // build array of result based on column headers. This method also allows
2842 // modifying column headers before using it to build result set i.e $rows.
2844 $this->buildRows($sql, $rows);
2846 // format result set.
2847 $this->formatDisplay($rows);
2849 // assign variables to templates
2850 $this->doTemplateAssignment($rows);
2852 // do print / pdf / instance stuff if needed
2853 $this->endPostProcess($rows);
2857 * @param int $rowCount
2859 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2860 // lets do the pager if in html mode
2861 $this->_limit
= NULL;
2863 // CRM-14115, over-ride row count if rowCount is specified in URL
2864 if ($this->_dashBoardRowCount
) {
2865 $rowCount = $this->_dashBoardRowCount
;
2867 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2868 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2870 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2872 if (!$pageId && !empty($_POST)) {
2873 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2874 $pageId = max((int)@$_POST['crmPID_B'], 1);
2876 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2877 $pageId = max((int)@$_POST['crmPID'], 1);
2879 unset($_POST['crmPID_B'], $_POST['crmPID']);
2882 $pageId = $pageId ?
$pageId : 1;
2883 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2884 $offset = ($pageId - 1) * $rowCount;
2886 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2887 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2889 $this->_limit
= " LIMIT $offset, $rowCount";
2890 return array($offset, $rowCount);
2892 if($this->_limitValue
) {
2893 if($this->_offsetValue
) {
2894 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2897 $this->_limit
= " LIMIT " . $this->_limitValue
;
2903 * @param int $rowCount
2905 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2907 // CRM-14115, over-ride row count if rowCount is specified in URL
2908 if ($this->_dashBoardRowCount
) {
2909 $rowCount = $this->_dashBoardRowCount
;
2912 if ($this->_limit
&& ($this->_limit
!= '')) {
2913 $sql = "SELECT FOUND_ROWS();";
2914 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2916 'total' => $this->_rowsFound
,
2917 'rowCount' => $rowCount,
2918 'status' => ts('Records') . ' %%StatusMessage%%',
2919 'buttonBottom' => 'PagerBottomButton',
2920 'buttonTop' => 'PagerTopButton',
2921 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2924 $pager = new CRM_Utils_Pager($params);
2925 $this->assign_by_ref('pager', $pager);
2926 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2937 function whereGroupClause($field, $value, $op) {
2939 $smartGroupQuery = "";
2941 $group = new CRM_Contact_DAO_Group();
2942 $group->is_active
= 1;
2944 $smartGroups = array();
2945 while ($group->fetch()) {
2946 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2947 $smartGroups[] = $group->id
;
2951 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2953 $smartGroupQuery = '';
2954 if (!empty($smartGroups)) {
2955 $smartGroups = implode(',', $smartGroups);
2956 $smartGroupQuery = " UNION DISTINCT
2957 SELECT DISTINCT smartgroup_contact.contact_id
2958 FROM civicrm_group_contact_cache smartgroup_contact
2959 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2962 $sqlOp = $this->getSQLOperator($op);
2963 if (!is_array($value)) {
2964 $value = array($value);
2966 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2968 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2969 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2970 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2971 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2972 {$smartGroupQuery} ) ";
2982 function whereTagClause($field, $value, $op) {
2983 // not using left join in query because if any contact
2984 // belongs to more than one tag, results duplicate
2986 $sqlOp = $this->getSQLOperator($op);
2987 if (!is_array($value)) {
2988 $value = array($value);
2990 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2992 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2993 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2994 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2995 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2998 function whereMembershipOrgClause($field, $value, $op) {
2999 $sqlOp = $this->getSQLOperator($op);
3000 if (!is_array($value)) {
3001 $value = array($value);
3004 $tmp_membership_org_sql_list = implode(', ', $value);
3005 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3006 SELECT DISTINCT mem.contact_id
3007 FROM civicrm_membership mem
3008 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3009 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3010 WHERE mt.member_of_contact_id IN (".$tmp_membership_org_sql_list.")
3011 AND mt.is_active = '1'
3012 AND mem_status.is_current_member = '1'
3013 AND mem_status.is_active = '1' ) ";
3016 function whereMembershipTypeClause($field, $value, $op) {
3017 $sqlOp = $this->getSQLOperator($op);
3018 if (!is_array($value)) {
3019 $value = array($value);
3022 $tmp_membership_sql_list = implode(', ', $value);
3023 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3024 SELECT DISTINCT mem.contact_id
3025 FROM civicrm_membership mem
3026 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3027 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3028 WHERE mem.membership_type_id IN (".$tmp_membership_sql_list.")
3029 AND mt.is_active = '1'
3030 AND mem_status.is_current_member = '1'
3031 AND mem_status.is_active = '1' ) ";
3035 * @param string $tableAlias
3037 function buildACLClause($tableAlias = 'contact_a') {
3038 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3042 * @param bool $addFields
3043 * @param array $permCustomGroupIds
3045 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3046 if (empty($this->_customGroupExtends
)) {
3049 if (!is_array($this->_customGroupExtends
)) {
3050 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3052 $customGroupWhere = '';
3053 if (!empty($permCustomGroupIds)) {
3054 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
3057 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3058 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3059 FROM civicrm_custom_group cg
3060 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3061 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3063 cg.is_active = 1 AND
3064 cf.is_active = 1 AND
3065 cf.is_searchable = 1
3066 ORDER BY cg.weight, cf.weight";
3067 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3070 while ($customDAO->fetch()) {
3071 if ($customDAO->table_name
!= $curTable) {
3072 $curTable = $customDAO->table_name
;
3073 $curFields = $curFilters = array();
3076 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3077 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3078 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3079 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3082 'fields', 'filters', 'group_bys') as $colKey) {
3083 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3084 $this->_columns
[$curTable][$colKey] = array();
3088 $fieldName = 'custom_' . $customDAO->cf_id
;
3091 // this makes aliasing work in favor
3092 $curFields[$fieldName] = array(
3093 'name' => $customDAO->column_name
,
3094 'title' => $customDAO->label
,
3095 'dataType' => $customDAO->data_type
,
3096 'htmlType' => $customDAO->html_type
,
3099 if ($this->_customGroupFilters
) {
3100 // this makes aliasing work in favor
3101 $curFilters[$fieldName] = array(
3102 'name' => $customDAO->column_name
,
3103 'title' => $customDAO->label
,
3104 'dataType' => $customDAO->data_type
,
3105 'htmlType' => $customDAO->html_type
,
3109 switch ($customDAO->data_type
) {
3112 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3113 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3114 // CRM-6946, show time part for datetime date fields
3115 if ($customDAO->time_format
) {
3116 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3121 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3122 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
3126 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3130 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3131 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3135 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3136 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3140 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3141 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3145 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3147 if (!empty($customDAO->option_group_id
)) {
3148 if (in_array($customDAO->html_type
, array(
3149 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
3150 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3153 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3155 if ($this->_customGroupFilters
) {
3156 $curFilters[$fieldName]['options'] = array();
3157 $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')));
3158 while ($ogDAO->fetch()) {
3159 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3165 case 'StateProvince':
3166 if (in_array($customDAO->html_type
, array(
3167 'Multi-Select State/Province'))) {
3168 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3171 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3173 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3177 if (in_array($customDAO->html_type
, array(
3178 'Multi-Select Country'))) {
3179 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3182 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3184 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3187 case 'ContactReference':
3188 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3189 $curFilters[$fieldName]['name'] = 'display_name';
3190 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3192 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3193 $curFields[$fieldName]['name'] = 'display_name';
3194 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3198 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3199 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3202 if (!array_key_exists('type', $curFields[$fieldName])) {
3203 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3207 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3209 if ($this->_customGroupFilters
) {
3210 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3212 if ($this->_customGroupGroupBy
) {
3213 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3218 function customDataFrom() {
3219 if (empty($this->_customGroupExtends
)) {
3222 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3224 foreach ($this->_columns
as $table => $prop) {
3225 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
3226 $extendsTable = $mapper[$prop['extends']];
3228 // check field is in params
3229 if (!$this->isFieldSelected($prop)) {
3232 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3234 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3236 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3237 // handle for ContactReference
3238 if (array_key_exists('fields', $prop)) {
3239 foreach ($prop['fields'] as $fieldName => $field) {
3240 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
3241 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3243 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3256 function isFieldSelected($prop) {
3261 if (!empty($this->_params
['fields'])) {
3262 foreach (array_keys($prop['fields']) as $fieldAlias) {
3263 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3264 if ($customFieldId) {
3265 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3269 //might be survey response field.
3270 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3277 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3278 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3279 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3285 if (!empty($this->_params
['order_bys'])) {
3286 foreach (array_keys($prop['fields']) as $fieldAlias) {
3287 foreach ($this->_params
['order_bys'] as $orderBy) {
3288 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3295 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3296 foreach ($prop['filters'] as $fieldAlias => $val) {
3298 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3299 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3300 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3301 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3307 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3308 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3319 * Check for empty order_by configurations and remove them; also set
3320 * template to hide them.
3322 function preProcessOrderBy(&$formValues) {
3323 // Object to show/hide form elements
3324 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3326 $_showHide->addShow('optionField_1');
3328 // Cycle through order_by options; skip any empty ones, and hide them as well
3331 if (!empty($formValues['order_bys'])) {
3332 foreach ($formValues['order_bys'] as $order_by) {
3333 if ($order_by['column'] && $order_by['column'] != '-') {
3334 $_showHide->addShow('optionField_' . $n);
3335 $orderBys[$n] = $order_by;
3340 for ($i = $n; $i <= 5; $i++
) {
3342 $_showHide->addHide('optionField_' . $i);
3346 // overwrite order_by options with modified values
3347 if (!empty($orderBys)) {
3348 $formValues['order_bys'] = $orderBys;
3351 $formValues['order_bys'] = array(1 => array('column' => '-'));
3354 // assign show/hide data to template
3355 $_showHide->addToTemplate();
3359 * Does table name have columns in SELECT clause?
3361 * @param string $tableName Name of table (index of $this->_columns array)
3365 function isTableSelected($tableName) {
3366 return in_array($tableName, $this->selectedTables());
3370 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3371 * (building the array if it's unset)
3373 * @return Array $this->_selectedTables
3375 function selectedTables() {
3376 if (!$this->_selectedTables
) {
3377 $orderByColumns = array();
3378 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3379 foreach ($this->_params
['order_bys'] as $orderBy) {
3380 $orderByColumns[] = $orderBy['column'];
3384 foreach ($this->_columns
as $tableName => $table) {
3385 if (array_key_exists('fields', $table)) {
3386 foreach ($table['fields'] as $fieldName => $field) {
3387 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3388 $this->_selectedTables
[] = $tableName;
3393 if (array_key_exists('order_bys', $table)) {
3394 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3395 if (in_array($orderByName, $orderByColumns)) {
3396 $this->_selectedTables
[] = $tableName;
3401 if (array_key_exists('filters', $table)) {
3402 foreach ($table['filters'] as $filterName => $filter) {
3403 if (!empty($this->_params
["{$filterName}_value"]) ||
3404 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3405 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3407 $this->_selectedTables
[] = $tableName;
3414 return $this->_selectedTables
;
3418 * @deprecated - use getAddressColumns which is a more accurate description
3419 * and also accepts an array of options rather than a long list
3421 * function for adding address fields to construct function in reports
3423 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3424 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3425 * @param bool $filters
3426 * @param array $defaults
3428 * @return array address fields for construct clause
3430 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3431 'country_id' => TRUE)) {
3432 $addressFields = array(
3433 'civicrm_address' =>
3435 'dao' => 'CRM_Core_DAO_Address',
3439 array('title' => ts('Address Name'),
3440 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3443 array('title' => ts('Street Address'),
3444 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3446 'supplemental_address_1' =>
3447 array('title' => ts('Supplementary Address Field 1'),
3448 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3450 'supplemental_address_2' =>
3451 array('title' => ts('Supplementary Address Field 2'),
3452 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3456 'name' => 'street_number',
3457 'title' => ts('Street Number'),
3459 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3463 'name' => 'street_name',
3464 'title' => ts('Street Name'),
3466 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3470 'name' => 'street_unit',
3471 'title' => ts('Street Unit'),
3473 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3476 array('title' => ts('City'),
3477 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3480 array('title' => ts('Postal Code'),
3481 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3483 'postal_code_suffix' =>
3484 array('title' => ts('Postal Code Suffix'),
3485 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3488 array('title' => ts('County'),
3489 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3491 'state_province_id' =>
3492 array('title' => ts('State/Province'),
3493 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3496 array('title' => ts('Country'),
3497 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3500 'grouping' => 'location-fields',
3505 $addressFields['civicrm_address']['filters'] = array(
3506 'street_number' => array('title' => ts('Street Number'),
3508 'name' => 'street_number',
3510 'street_name' => array('title' => ts('Street Name'),
3511 'name' => 'street_name',
3512 'operator' => 'like',
3514 'postal_code' => array('title' => ts('Postal Code'),
3516 'name' => 'postal_code',
3518 'city' => array('title' => ts('City'),
3519 'operator' => 'like',
3522 'county_id' => array(
3523 'name' => 'county_id',
3524 'title' => ts('County'),
3525 'type' => CRM_Utils_Type
::T_INT
,
3527 CRM_Report_Form
::OP_MULTISELECT
,
3529 CRM_Core_PseudoConstant
::county(),
3531 'state_province_id' => array(
3532 'name' => 'state_province_id',
3533 'title' => ts('State/Province'),
3534 'type' => CRM_Utils_Type
::T_INT
,
3536 CRM_Report_Form
::OP_MULTISELECT
,
3538 CRM_Core_PseudoConstant
::stateProvince(),
3540 'country_id' => array(
3541 'name' => 'country_id',
3542 'title' => ts('Country'),
3543 'type' => CRM_Utils_Type
::T_INT
,
3545 CRM_Report_Form
::OP_MULTISELECT
,
3547 CRM_Core_PseudoConstant
::country(),
3553 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3554 'street_number' => array('title' => 'Odd / Even Street Number'),
3555 'street_address' => NULL,
3557 'postal_code' => NULL,
3562 $addressFields['civicrm_address']['group_bys'] = array(
3563 'street_address' => NULL,
3565 'postal_code' => NULL,
3566 'state_province_id' =>
3567 array('title' => ts('State/Province'),
3570 array('title' => ts('Country'),
3573 array('title' => ts('County'),
3577 return $addressFields;
3581 * Do AlterDisplay processing on Address Fields
3592 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3593 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3594 $entryFound = FALSE;
3596 if (array_key_exists('civicrm_address_country_id', $row)) {
3597 if ($value = $row['civicrm_address_country_id']) {
3598 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3599 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3600 "reset=1&force=1&{$criteriaQueryParams}&" .
3601 "country_id_op=in&country_id_value={$value}",
3602 $this->_absoluteUrl
, $this->_id
3604 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3605 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3612 if (array_key_exists('civicrm_address_county_id', $row)) {
3613 if ($value = $row['civicrm_address_county_id']) {
3614 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3615 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3616 "reset=1&force=1&{$criteriaQueryParams}&" .
3617 "county_id_op=in&county_id_value={$value}",
3618 $this->_absoluteUrl
, $this->_id
3620 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3621 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3627 // handle state province
3628 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3629 if ($value = $row['civicrm_address_state_province_id']) {
3630 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3632 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3633 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3634 $this->_absoluteUrl
, $this->_id
3636 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3637 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3648 * Adjusts dates passed in to YEAR() for fiscal year.
3655 function fiscalYearOffset($fieldName) {
3656 $config = CRM_Core_Config
::singleton();
3657 $fy = $config->fiscalYearStart
;
3658 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3659 return "YEAR( $fieldName )";
3661 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3665 * Add Address into From Table if required
3667 function addAddressFromClause() {
3668 // include address field if address column is to be included
3669 if ((isset($this->_addressField
) &&
3670 $this->_addressField
3672 $this->isTableSelected('civicrm_address')
3675 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3676 ON ({$this->_aliases['civicrm_contact']}.id =
3677 {$this->_aliases['civicrm_address']}.contact_id) AND
3678 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3683 * Add Phone into From Table if required
3685 function addPhoneFromClause() {
3686 // include address field if address column is to be included
3687 if ($this->isTableSelected('civicrm_phone')
3690 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3691 ON ({$this->_aliases['civicrm_contact']}.id =
3692 {$this->_aliases['civicrm_phone']}.contact_id) AND
3693 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3698 * Get phone columns to add to array
3699 * @param array $options
3700 * - prefix Prefix to add to table (in case of more than one instance of the table)
3701 * - prefix_label Label to give columns from this phone table instance
3702 * @return array phone columns definition
3704 function getPhoneColumns($options = array()){
3705 $defaultOptions = array(
3707 'prefix_label' => '',
3710 $options = array_merge($defaultOptions,$options);
3713 $options['prefix'] . 'civicrm_phone' => array(
3714 'dao' => 'CRM_Core_DAO_Phone',
3716 $options['prefix'] . 'phone' => array(
3717 'title' => ts($options['prefix_label'] . 'Phone'),
3727 * Get address columns to add to array
3728 * @param array $options
3729 * - prefix Prefix to add to table (in case of more than one instance of the table)
3730 * - prefix_label Label to give columns from this address table instance
3731 * @return array address columns definition
3733 function getAddressColumns($options = array()){
3734 $defaultOptions = array(
3736 'prefix_label' => '',
3740 'defaults' => array(
3743 $options = array_merge($defaultOptions,$options);
3744 return $this->addAddressFields(
3745 $options['group_by'],
3746 $options['order_by'],
3747 $options['filters'],
3748 $options['defaults']
3756 function add2group($groupID) {
3757 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3758 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3759 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3761 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3762 $dao = CRM_Core_DAO
::executeQuery($sql);
3764 $contact_ids = array();
3765 // Add resulting contacts to group
3766 while ($dao->fetch()) {
3767 if ($dao->addtogroup_contact_id
) {
3768 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3772 if ( !empty($contact_ids) ) {
3773 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3774 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3777 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3782 /* function used for showing charts on print screen */
3783 static function uploadChartImage() {
3784 // upload strictly for '.png' images
3785 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3786 if (preg_match('/\.png$/', $name)) {
3788 // POST data is usually string data, but we are passing a RAW .png
3789 // so PHP is a bit confused and $_POST is empty. But it has saved
3790 // the raw bits into $HTTP_RAW_POST_DATA
3792 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3794 // prepare the directory
3795 $config = CRM_Core_Config
::singleton();
3796 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3797 if (!file_exists($defaultPath)) {
3798 mkdir($defaultPath, 0777, TRUE);
3801 // full path to the saved image including filename
3802 $destination = $defaultPath . $name;
3805 $jfh = fopen($destination, 'w') or die("can't open file");
3806 fwrite($jfh, $httpRawPostData);
3808 CRM_Utils_System
::civiExit();