3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 $_customGroupFilters = TRUE;
139 protected $_customGroupGroupBy = FALSE;
145 protected $_tagFilter = FALSE;
148 * build groups filter
151 protected $_groupFilter = FALSE;
158 public $_navigation = array();
160 public $_drilldownReport = array();
163 * An attribute for checkbox/radio form field layout
167 protected $_fourColumnAttribute = array(
168 '</td><td width="25%">', '</td><td width="25%">',
169 '</td><td width="25%">', '</tr><tr><td>',
172 protected $_force = 1;
174 protected $_params = NULL;
175 protected $_formValues = NULL;
176 protected $_instanceValues = NULL;
178 protected $_instanceForm = FALSE;
179 protected $_criteriaForm = FALSE;
181 protected $_instanceButtonName = NULL;
182 protected $_createNewButtonName = NULL;
183 protected $_printButtonName = NULL;
184 protected $_pdfButtonName = NULL;
185 protected $_csvButtonName = NULL;
186 protected $_groupButtonName = NULL;
187 protected $_chartButtonName = NULL;
188 protected $_csvSupported = TRUE;
189 protected $_add2groupSupported = TRUE;
190 protected $_groups = NULL;
191 protected $_rowsFound = NULL;
192 protected $_selectAliases = array();
193 protected $_rollup = NULL;
194 protected $_limit = NULL;
195 protected $_sections = NULL;
196 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
197 protected $_absoluteUrl = FALSE;
200 * To what frequency group-by a date column
204 protected $_groupByDateFreq = array(
206 'YEARWEEK' => 'Week',
207 'QUARTER' => 'Quarter',
212 * Variables to hold the acl inner join and where clause
214 protected $_aclFrom = NULL;
215 protected $_aclWhere = NULL;
218 * Array of DAO tables having columns included in SELECT or ORDER BY clause
222 protected $_selectedTables;
224 public $_having = NULL;
225 public $_select = NULL;
226 public $_columnHeaders = array();
227 public $_orderBy = NULL;
228 public $_groupBy = NULL;
229 public $_whereClauses = array();
230 public $_havingClauses = array();
233 * Variable to hold the currency alias
235 protected $_currencyColumn = NULL;
240 function __construct() {
241 parent
::__construct();
244 if ($this->_tagFilter
) {
245 $this->buildTagFilter();
247 if ($this->_exposeContactID
) {
248 if (array_key_exists('civicrm_contact', $this->_columns
)) {
249 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
251 'title' => 'Contact ID',
257 if ($this->_groupFilter
) {
258 $this->buildGroupFilter();
261 // Get all custom groups
262 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
264 // Get the custom groupIds for which the user have VIEW permission
265 require_once 'CRM/ACL/API.php';
266 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
268 // do not allow custom data for reports if user don't have
269 // permission to access custom data.
270 if (!empty($this->_customGroupExtends
) && !CRM_Core_Permission
::check('access all custom data') && empty($permCustomGroupIds)) {
271 $this->_customGroupExtends
= array();
274 // merge custom data columns to _columns list, if any
275 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
277 // add / modify display columns, filters ..etc
278 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
280 //assign currencyColumn variable to tpl
281 $this->assign('currencyColumn', $this->_currencyColumn
);
284 function preProcessCommon() {
286 CRM_Utils_Request
::retrieve(
289 CRM_Core_DAO
::$_nullObject
292 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
294 $this->assign('section', $this->_section
);
295 CRM_Core_Region
::instance('page-header')->add(array(
296 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
299 $this->_id
= $this->get('instanceId');
301 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
303 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
307 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
308 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
309 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
312 $this->assign('instanceId', $this->_id
);
313 $params = array('id' => $this->_id
);
314 $this->_instanceValues
= array();
315 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_Instance',
317 $this->_instanceValues
319 if (empty($this->_instanceValues
)) {
320 CRM_Core_Error
::fatal("Report could not be loaded.");
323 if (!empty($this->_instanceValues
['permission']) &&
324 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
325 CRM_Core_Permission
::check('administer Reports')
328 CRM_Utils_System
::permissionDenied();
329 CRM_Utils_System
::civiExit();
332 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
334 $this->_formValues
= unserialize($formValues);
337 $this->_formValues
= NULL;
340 // lets always do a force if reset is found in the url.
341 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
346 $this->assign('mode', 'instance');
349 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
350 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
351 if (($instanceCount > 0) && $optionValueID) {
352 $this->assign('instanceUrl',
353 CRM_Utils_System
::url('civicrm/report/list',
354 "reset=1&ovid=$optionValueID"
358 if ($optionValueID) {
359 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
363 $this->assign('mode', 'template');
366 // lets display the Report Settings section
367 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
369 // Do not display Report Settings section if administer Reports permission is absent OR
370 // if report instance is reserved and administer reserved reports absent
371 if (!CRM_Core_Permission
::check('administer Reports') ||
372 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
373 $this->_instanceForm
= FALSE;
376 $this->assign('criteriaForm', FALSE);
377 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
378 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
379 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
380 $this->assign('criteriaForm', TRUE);
381 $this->_criteriaForm
= TRUE;
385 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
386 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
387 $this->_printButtonName
= $this->getButtonName('submit', 'print');
388 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
389 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
390 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
391 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
394 function addBreadCrumb() {
398 'title' => ts('Report Templates'),
399 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
403 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
406 function preProcess() {
407 $this->preProcessCommon();
410 $this->addBreadCrumb();
413 foreach ($this->_columns
as $tableName => $table) {
415 if (!isset($table['alias'])) {
416 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
419 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
422 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
424 // higher preference to bao object
425 if (array_key_exists('bao', $table)) {
426 require_once str_replace('_', DIRECTORY_SEPARATOR
, $table['bao'] . '.php');
427 eval("\$expFields = {$table['bao']}::exportableFields( );");
429 elseif (array_key_exists('dao', $table)){
430 require_once str_replace('_', DIRECTORY_SEPARATOR
, $table['dao'] . '.php');
431 eval("\$expFields = {$table['dao']}::export( );");
434 $expFields = array();
437 $doNotCopy = array('required');
439 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
440 foreach ($fieldGroups as $fieldGrp) {
441 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
442 foreach ($table[$fieldGrp] as $fieldName => $field) {
443 // $name is the field name used to reference the BAO/DAO export fields array
444 $name = isset($field['name']) ?
$field['name'] : $fieldName;
446 // Sometimes the field name key in the BAO/DAO export fields array is
447 // different from the actual database field name.
448 // Unset $field['name'] so that actual database field name can be obtained
449 // from the BAO/DAO export fields array.
450 unset($field['name']);
452 if (array_key_exists($name, $expFields)) {
453 foreach ($doNotCopy as $dnc) {
454 // unset the values we don't want to be copied.
455 unset($expFields[$name][$dnc]);
458 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
461 foreach ($expFields[$name] as $property => $val) {
462 if (!array_key_exists($property, $field)) {
463 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
470 if (CRM_Utils_Array
::value('no_repeat', $field)) {
471 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
473 if (CRM_Utils_Array
::value('no_display', $field)) {
474 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
477 // set alias = table-name, unless already set
478 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
479 $this->_columns
[$tableName]['alias'] : $tableName
481 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
483 // set name = fieldName, unless already set
484 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
485 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
488 // set dbAlias = alias.name, unless already set
489 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
490 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
493 if (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName]) &&
494 !isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'])
496 if (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
497 array(CRM_Utils_Type
::T_MONEY
, CRM_Utils_Type
::T_FLOAT
)
499 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
501 elseif (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
502 array(CRM_Utils_Type
::T_INT
)
504 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
511 // copy filters to a separate handy variable
512 if (array_key_exists('filters', $table)) {
513 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
516 if (array_key_exists('group_bys', $table)) {
517 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
520 if (array_key_exists('fields', $table)) {
521 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
526 $this->setDefaultValues(FALSE);
529 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
530 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
531 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
532 CRM_Report_Utils_Get
::processChart($this->_defaults
);
535 $this->_formValues
= $this->_defaults
;
536 $this->postProcess();
540 function setDefaultValues($freeze = TRUE) {
541 $freezeGroup = array();
543 // FIXME: generalizing form field naming conventions would reduce
544 // lots of lines below.
545 foreach ($this->_columns
as $tableName => $table) {
546 if (array_key_exists('fields', $table)) {
547 foreach ($table['fields'] as $fieldName => $field) {
548 if (!array_key_exists('no_display', $field)) {
549 if (isset($field['required'])) {
551 $this->_defaults
['fields'][$fieldName] = 1;
554 // find element object, so that we could use quickform's freeze method
555 // for required elements
556 $obj = $this->getElementFromGroup("fields", $fieldName);
558 $freezeGroup[] = $obj;
562 elseif (isset($field['default'])) {
563 $this->_defaults
['fields'][$fieldName] = $field['default'];
569 if (array_key_exists('group_bys', $table)) {
570 foreach ($table['group_bys'] as $fieldName => $field) {
571 if (isset($field['default'])) {
572 if (CRM_Utils_Array
::value('frequency', $field)) {
573 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
575 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
579 if (array_key_exists('filters', $table)) {
580 foreach ($table['filters'] as $fieldName => $field) {
581 if (isset($field['default'])) {
582 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
583 if(is_array($field['default'])){
584 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
585 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
586 $this->_defaults
["{$fieldName}_relative"] = 0;
589 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
593 $this->_defaults
["{$fieldName}_value"] = $field['default'];
596 //assign default value as "in" for multiselect
597 //operator, To freeze the select element
598 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
599 $this->_defaults
["{$fieldName}_op"] = 'in';
601 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
602 $this->_defaults
["{$fieldName}_op"] = 'mhas';
604 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
605 $this->_defaults
["{$fieldName}_op"] = $op;
611 array_key_exists('order_bys', $table) &&
612 is_array($table['order_bys'])
614 if (!array_key_exists('order_bys', $this->_defaults
)) {
615 $this->_defaults
['order_bys'] = array();
617 foreach ($table['order_bys'] as $fieldName => $field) {
619 CRM_Utils_Array
::value('default', $field) ||
620 CRM_Utils_Array
::value('default_order', $field) ||
621 CRM_Utils_Array
::value('default_is_section', $field) ||
622 CRM_Utils_Array
::value('default_weight', $field)
625 'column' => $fieldName,
626 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
627 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
630 if (CRM_Utils_Array
::value('default_weight', $field)) {
631 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
634 array_unshift($this->_defaults
['order_bys'], $order_by);
640 foreach ($this->_options
as $fieldName => $field) {
641 if (isset($field['default'])) {
642 $this->_defaults
['options'][$fieldName] = $field['default'];
647 if (!empty($this->_submitValues
)) {
648 $this->preProcessOrderBy($this->_submitValues
);
651 $this->preProcessOrderBy($this->_defaults
);
654 // lets finish freezing task here itself
655 if (!empty($freezeGroup)) {
656 foreach ($freezeGroup as $elem) {
661 if ($this->_formValues
) {
662 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
665 if ($this->_instanceValues
) {
666 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
669 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
671 return $this->_defaults
;
674 function getElementFromGroup($group, $grpFieldName) {
675 $eleObj = $this->getElement($group);
676 foreach ($eleObj->_elements
as $index => $obj) {
677 if ($grpFieldName == $obj->_attributes
['name']) {
684 function addColumns() {
687 foreach ($this->_columns
as $tableName => $table) {
688 if (array_key_exists('fields', $table)) {
689 foreach ($table['fields'] as $fieldName => $field) {
690 if (!array_key_exists('no_display', $field)) {
691 if (isset($field['grouping'])) {
692 $tableName = $field['grouping'];
694 elseif (isset($table['grouping'])) {
695 $tableName = $table['grouping'];
697 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
699 if (isset($table['group_title'])) {
700 $colGroups[$tableName]['group_title'] = $table['group_title'];
703 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
709 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
710 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
712 $this->assign('colGroups', $colGroups);
715 function addFilters() {
716 $options = $filters = array();
718 foreach ($this->_filters
as $table => $attributes) {
719 foreach ($attributes as $fieldName => $field) {
720 // get ready with option value pair
721 // @ 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
723 $operations = $this->getOperationPair(
724 CRM_Utils_Array
::value('operatorType', $field),
727 $filters[$table][$fieldName] = $field;
729 switch (CRM_Utils_Array
::value('operatorType', $field)) {
730 case CRM_Report_Form
::OP_MONTH
:
731 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
732 // If there's no option list for this filter, define one.
733 $field['options'] = array(
742 9 => ts('September'),
744 11 => ts('November'),
745 12 => ts('December'),
747 // Add this option list to this column _columns. This is
748 // required so that filter statistics show properly.
749 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
751 case CRM_Report_FORM
::OP_MULTISELECT
:
752 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
753 // assume a multi-select field
754 if (!empty($field['options'])) {
755 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
756 if (count($operations) <= 1) {
759 $select = $this->addElement('select', "{$fieldName}_value", NULL,
760 $field['options'], array(
762 'style' => 'min-width:250px',
765 $select->setMultiple(TRUE);
769 case CRM_Report_FORM
::OP_SELECT
:
770 // assume a select field
771 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
772 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
775 case CRM_Report_FORM
::OP_DATE
:
776 // build datetime fields
777 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
781 case CRM_Report_FORM
::OP_DATETIME
:
782 // build datetime fields
783 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
787 case CRM_Report_FORM
::OP_INT
:
788 case CRM_Report_FORM
::OP_FLOAT
:
789 // and a min value input box
790 $this->add('text', "{$fieldName}_min", ts('Min'));
791 // and a max value input box
792 $this->add('text', "{$fieldName}_max", ts('Max'));
794 // default type is string
795 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
796 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
798 // we need text box for value input
799 $this->add('text', "{$fieldName}_value", NULL);
804 $this->assign('filters', $filters);
807 function addOptions() {
808 if (!empty($this->_options
)) {
809 // FIXME: For now lets build all elements as checkboxes.
810 // Once we clear with the format we can build elements based on type
813 foreach ($this->_options
as $fieldName => $field) {
814 if ($field['type'] == 'select') {
815 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
817 else if ($field['type'] == 'checkbox') {
818 $options[$field['title']] = $fieldName;
819 $this->addCheckBox($fieldName, NULL,
821 NULL, NULL, NULL, $this->_fourColumnAttribute
826 $this->assign('otherOptions', $this->_options
);
829 function addChartOptions() {
830 if (!empty($this->_charts
)) {
831 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
832 $this->assign('charts', $this->_charts
);
833 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
837 function addGroupBys() {
838 $options = $freqElements = array();
840 foreach ($this->_columns
as $tableName => $table) {
841 if (array_key_exists('group_bys', $table)) {
842 foreach ($table['group_bys'] as $fieldName => $field) {
843 if (!empty($field)) {
844 $options[$field['title']] = $fieldName;
845 if (CRM_Utils_Array
::value('frequency', $field)) {
846 $freqElements[$field['title']] = $fieldName;
852 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
853 NULL, NULL, NULL, $this->_fourColumnAttribute
855 $this->assign('groupByElements', $options);
857 foreach ($freqElements as $name) {
858 $this->addElement('select', "group_bys_freq[$name]",
859 ts('Frequency'), $this->_groupByDateFreq
864 function addOrderBys() {
866 foreach ($this->_columns
as $tableName => $table) {
868 // Report developer may define any column to order by; include these as order-by options
869 if (array_key_exists('order_bys', $table)) {
870 foreach ($table['order_bys'] as $fieldName => $field) {
871 if (!empty($field)) {
872 $options[$fieldName] = $field['title'];
877 /* Add searchable custom fields as order-by options, if so requested
878 * (These are already indexed, so allowing to order on them is cheap.)
882 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
883 foreach ($table['fields'] as $fieldName => $field) {
884 if (!array_key_exists('no_display', $field)) {
885 $options[$fieldName] = $field['title'];
893 $this->assign('orderByOptions', $options);
895 if (!empty($options)) {
897 '-' => ' - none - ') +
$options;
898 for ($i = 1; $i <= 5; $i++
) {
899 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
900 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
901 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
906 function buildInstanceAndButtons() {
907 CRM_Report_Form_Instance
::buildForm($this);
909 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
911 $this->addElement('submit', $this->_instanceButtonName
, $label);
912 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
913 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
916 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
918 if ($this->_instanceForm
) {
919 $this->assign('instanceForm', TRUE);
922 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
923 $this->addElement('submit', $this->_printButtonName
, $label);
925 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
926 $this->addElement('submit', $this->_pdfButtonName
, $label);
928 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
930 if ($this->_csvSupported
) {
931 $this->addElement('submit', $this->_csvButtonName
, $label);
934 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
935 $this->addElement('select', 'groups', ts('Group'),
936 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
938 $this->assign('group', TRUE);
941 $label = ts('Add these Contacts to Group');
942 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
944 $this->addChartOptions();
945 $this->addButtons(array(
948 'name' => ts('Preview Report'),
955 function buildQuickForm() {
962 $this->addGroupBys();
964 $this->addOrderBys();
966 $this->buildInstanceAndButtons();
968 //add form rule for report
969 if (is_callable(array(
970 $this, 'formRule'))) {
971 $this->addFormRule(array(get_class($this), 'formRule'), $this);
975 // a formrule function to ensure that fields selected in group_by
976 // (if any) should only be the ones present in display/select fields criteria;
977 // note: works if and only if any custom field selected in group_by.
978 function customDataFormRule($fields, $ignoreFields = array( )) {
980 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
981 foreach ($this->_columns
as $tableName => $table) {
982 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
983 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
984 if (array_key_exists($fieldName, $fields['group_bys']) &&
985 !array_key_exists($fieldName, $fields['fields'])
987 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
989 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
990 foreach ($fields['fields'] as $fld => $val) {
991 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
992 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1003 // Note: $fieldName param allows inheriting class to build operationPairs
1004 // specific to a field.
1005 function getOperationPair($type = "string", $fieldName = NULL) {
1006 // FIXME: At some point we should move these key-val pairs
1007 // to option_group and option_value table.
1009 case CRM_Report_FORM
::OP_INT
:
1010 case CRM_Report_FORM
::OP_FLOAT
:
1012 'lte' => ts('Is less than or equal to'),
1013 'gte' => ts('Is greater than or equal to'),
1014 'bw' => ts('Is between'),
1015 'eq' => ts('Is equal to'),
1016 'lt' => ts('Is less than'),
1017 'gt' => ts('Is greater than'),
1018 'neq' => ts('Is not equal to'),
1019 'nbw' => ts('Is not between'),
1020 'nll' => ts('Is empty (Null)'),
1021 'nnll' => ts('Is not empty (Null)'),
1025 case CRM_Report_FORM
::OP_SELECT
:
1027 'eq' => ts('Is equal to'),
1030 case CRM_Report_FORM
::OP_MONTH
:
1031 case CRM_Report_FORM
::OP_MULTISELECT
:
1033 'in' => ts('Is one of'),
1034 'notin' => ts('Is not one of'),
1038 case CRM_Report_FORM
::OP_DATE
:
1040 'nll' => ts('Is empty (Null)'),
1041 'nnll' => ts('Is not empty (Null)'),
1045 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1046 // use this operator for the values, concatenated with separator. For e.g if
1047 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1049 'mhas' => ts('Is one of'),
1055 'has' => ts('Contains'),
1056 'sw' => ts('Starts with'),
1057 'ew' => ts('Ends with'),
1058 'nhas' => ts('Does not contain'),
1059 'eq' => ts('Is equal to'),
1060 'neq' => ts('Is not equal to'),
1061 'nll' => ts('Is empty (Null)'),
1062 'nnll' => ts('Is not empty (Null)'),
1067 function buildTagFilter() {
1068 $contactTags = CRM_Core_BAO_Tag
::getTags();
1069 if (!empty($contactTags)) {
1070 $this->_columns
['civicrm_tag'] = array(
1071 'dao' => 'CRM_Core_DAO_Tag',
1077 'title' => ts('Tag'),
1079 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1080 'options' => $contactTags,
1088 * Adds group filters to _columns (called from _Constuct
1090 function buildGroupFilter() {
1091 $this->_columns
['civicrm_group']['filters'] = array(
1094 'name' => 'group_id',
1095 'title' => ts('Group'),
1096 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1098 'options' => CRM_Core_PseudoConstant
::group(),
1101 if (empty($this->_columns
['civicrm_group']['dao'])) {
1102 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1104 if (empty($this->_columns
['civicrm_group']['alias'])) {
1105 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1109 function getSQLOperator($operator = "like") {
1110 switch ($operator) {
1143 return 'IS NOT NULL';
1151 function whereClause(&$field, $op,
1155 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1161 if (($min !== NULL && strlen($min) > 0) ||
1162 ($max !== NULL && strlen($max) > 0)
1164 $min = CRM_Utils_Type
::escape($min, $type);
1165 $max = CRM_Utils_Type
::escape($max, $type);
1169 $clauses[] = "( {$field['dbAlias']} >= $min )";
1172 $clauses[] = "( {$field['dbAlias']} < $min )";
1177 $clauses[] = "( {$field['dbAlias']} <= $max )";
1180 $clauses[] = "( {$field['dbAlias']} > $max )";
1184 if (!empty($clauses)) {
1186 $clause = implode(' AND ', $clauses);
1189 $clause = implode(' OR ', $clauses);
1197 if ($value !== NULL && strlen($value) > 0) {
1198 $value = CRM_Utils_Type
::escape($value, $type);
1199 if (strpos($value, '%') === FALSE) {
1200 $value = "'%{$value}%'";
1203 $value = "'{$value}'";
1205 $sqlOP = $this->getSQLOperator($op);
1206 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1212 if ($value !== NULL && is_array($value) && count($value) > 0) {
1213 $sqlOP = $this->getSQLOperator($op);
1214 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1215 //cycle through selections and esacape values
1216 foreach ($value as $key => $selection) {
1217 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1219 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1222 // for numerical values
1223 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1225 if ($op == 'notin') {
1226 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1229 $clause = "( " . $clause . " )";
1235 // mhas == multiple has
1236 if ($value !== NULL && count($value) > 0) {
1237 $sqlOP = $this->getSQLOperator($op);
1238 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1244 if ($value !== NULL && strlen($value) > 0) {
1245 $value = CRM_Utils_Type
::escape($value, $type);
1246 if (strpos($value, '%') === FALSE) {
1248 $value = "'{$value}%'";
1251 $value = "'%{$value}'";
1255 $value = "'{$value}'";
1257 $sqlOP = $this->getSQLOperator($op);
1258 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1264 $sqlOP = $this->getSQLOperator($op);
1265 $clause = "( {$field['dbAlias']} $sqlOP )";
1269 if ($value !== NULL && strlen($value) > 0) {
1270 if (isset($field['clause'])) {
1271 // FIXME: we not doing escape here. Better solution is to use two
1272 // different types - data-type and filter-type
1273 eval("\$clause = \"{$field['clause']}\";");
1276 $value = CRM_Utils_Type
::escape($value, $type);
1277 $sqlOP = $this->getSQLOperator($op);
1278 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1279 $value = "'{$value}'";
1281 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1287 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1288 $clause = $this->whereGroupClause($field, $value, $op);
1290 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1291 // not using left join in query because if any contact
1292 // belongs to more than one tag, results duplicate
1294 $clause = $this->whereTagClause($field, $value, $op);
1300 function dateClause($fieldName,
1301 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1304 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1305 $sqlOP = $this->getSQLOperator($relative);
1306 return "( {$fieldName} {$sqlOP} )";
1309 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1312 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1313 $clauses[] = "( {$fieldName} >= $from )";
1317 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1318 $clauses[] = "( {$fieldName} <= {$to} )";
1321 if (!empty($clauses)) {
1322 return implode(' AND ', $clauses);
1328 * @todo - could not find any instances where this is called
1329 * @param unknown_type $relative
1330 * @param String $from
1331 * @param String_type $to
1332 * @return string|NULL
1334 function dateDisplay($relative, $from, $to) {
1335 list($from, $to) = $this->getFromTo($relative, $from, $to);
1338 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1341 $clauses[] = 'Past';
1345 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1348 $clauses[] = 'Today';
1351 if (!empty($clauses)) {
1352 return implode(' - ', $clauses);
1358 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1359 if (empty($totime)) {
1362 //FIX ME not working for relative
1364 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1365 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1366 $from = substr($dateRange['from'], 0, 8);
1367 //Take only Date Part, Sometime Time part is also present in 'to'
1368 $to = substr($dateRange['to'], 0, 8);
1370 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1371 $to = CRM_Utils_Date
::processDate($to, $totime);
1372 return array($from, $to);
1375 function alterDisplay(&$rows) {
1376 // custom code to alter rows
1379 function alterCustomDataDisplay(&$rows) {
1380 // custom code to alter rows having custom values
1381 if (empty($this->_customGroupExtends
)) {
1385 $customFieldIds = array();
1386 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1387 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1388 $customFieldIds[$fieldAlias] = $fieldId;
1391 if (empty($customFieldIds)) {
1395 $customFields = $fieldValueMap = array();
1396 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1398 // skip for type date and ContactReference since date format is already handled
1400 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1401 FROM civicrm_custom_field cf
1402 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1403 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1404 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1405 cg.is_active = 1 AND
1406 cf.is_active = 1 AND
1407 cf.is_searchable = 1 AND
1408 cf.data_type NOT IN ('ContactReference', 'Date') AND
1409 cf.id IN (" . implode(",", $customFieldIds) . ")";
1411 $dao = CRM_Core_DAO
::executeQuery($query);
1412 while ($dao->fetch()) {
1413 foreach ($customFieldCols as $key) {
1414 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1416 if ($dao->option_group_id
) {
1417 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1422 $entryFound = FALSE;
1423 foreach ($rows as $rowNum => $row) {
1424 foreach ($row as $tableCol => $val) {
1425 if (array_key_exists($tableCol, $customFields)) {
1426 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1431 // skip looking further in rows, if first row itself doesn't
1432 // have the column we need
1439 function formatCustomValues($value, $customField, $fieldValueMap) {
1440 if (CRM_Utils_System
::isNull($value)) {
1444 $htmlType = $customField['html_type'];
1446 switch ($customField['data_type']) {
1448 if ($value == '1') {
1449 $retValue = ts('Yes');
1452 $retValue = ts('No');
1457 $retValue = CRM_Utils_System
::formatWikiURL($value);
1469 if ($htmlType == 'Text') {
1470 $retValue = (float)$value;
1474 if ($htmlType == 'Text') {
1484 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1489 if (in_array($htmlType, array(
1490 'Text', 'TextArea'))) {
1494 case 'StateProvince':
1497 switch ($htmlType) {
1498 case 'Multi-Select Country':
1499 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1500 $customData = array();
1501 foreach ($value as $val) {
1503 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1506 $retValue = implode(', ', $customData);
1509 case 'Select Country':
1510 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1513 case 'Select State/Province':
1514 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1517 case 'Multi-Select State/Province':
1518 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1519 $customData = array();
1520 foreach ($value as $val) {
1522 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1525 $retValue = implode(', ', $customData);
1530 case 'Autocomplete-Select':
1531 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1535 case 'AdvMulti-Select':
1536 case 'Multi-Select':
1537 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1538 $customData = array();
1539 foreach ($value as $val) {
1541 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1544 $retValue = implode(', ', $customData);
1559 function removeDuplicates(&$rows) {
1560 if (empty($this->_noRepeats
)) {
1563 $checkList = array();
1565 foreach ($rows as $key => $list) {
1566 foreach ($list as $colName => $colVal) {
1567 if (array_key_exists($colName, $checkList) &&
1568 $checkList[$colName] == $colVal) {
1569 $rows[$key][$colName] = "";
1571 if (in_array($colName, $this->_noRepeats
)) {
1572 $checkList[$colName] = $colVal;
1578 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1579 foreach ($row as $colName => $colVal) {
1580 if (in_array($colName, $fields)) {
1581 $row[$colName] = $row[$colName];
1583 elseif (isset($this->_columnHeaders
[$colName])) {
1585 $row[$colName] = "Subtotal";
1589 unset($row[$colName]);
1595 function grandTotal(&$rows) {
1596 if (!$this->_rollup ||
($this->_rollup
== '') ||
1597 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1601 $lastRow = array_pop($rows);
1603 $this->_grandFlag
= FALSE;
1604 foreach ($this->_columnHeaders
as $fld => $val) {
1605 if (!in_array($fld, $this->_statFields
)) {
1606 if (!$this->_grandFlag
) {
1607 $lastRow[$fld] = "Grand Total";
1608 $this->_grandFlag
= TRUE;
1611 $lastRow[$fld] = "";
1616 $this->assign('grandStat', $lastRow);
1620 function formatDisplay(&$rows, $pager = TRUE) {
1621 // set pager based on if any limit was applied in the query.
1626 // allow building charts if any
1627 if (!empty($this->_params
['charts']) && !empty($rows)) {
1628 $this->buildChart($rows);
1629 $this->assign('chartEnabled', TRUE);
1630 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1631 $this->assign('chartId', $this->_chartId
);
1634 // unset columns not to be displayed.
1635 foreach ($this->_columnHeaders
as $key => $value) {
1636 if (is_array($value) && isset($value['no_display'])) {
1637 unset($this->_columnHeaders
[$key]);
1641 // unset columns not to be displayed.
1642 if (!empty($rows)) {
1643 foreach ($this->_noDisplay
as $noDisplayField) {
1644 foreach ($rows as $rowNum => $row) {
1645 unset($this->_columnHeaders
[$noDisplayField]);
1650 // build array of section totals
1651 $this->sectionTotals();
1653 // process grand-total row
1654 $this->grandTotal($rows);
1656 // use this method for formatting rows for display purpose.
1657 $this->alterDisplay($rows);
1658 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1660 // use this method for formatting custom rows for display purpose.
1661 $this->alterCustomDataDisplay($rows);
1664 function buildChart(&$rows) {
1665 // override this method for building charts.
1668 // select() method below has been added recently (v3.3), and many of the report templates might
1669 // still be having their own select() method. We should fix them as and when encountered and move
1670 // towards generalizing the select() method below.
1674 foreach ($this->_columns
as $tableName => $table) {
1675 if (array_key_exists('fields', $table)) {
1676 foreach ($table['fields'] as $fieldName => $field) {
1677 if ($tableName == 'civicrm_address') {
1678 $this->_addressField
= TRUE;
1680 if ($tableName == 'civicrm_email') {
1681 $this->_emailField
= TRUE;
1683 if ($tableName == 'civicrm_phone') {
1684 $this->_phoneField
= TRUE;
1687 if (CRM_Utils_Array
::value('required', $field) ||
1688 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1691 // 1. In many cases we want select clause to be built in slightly different way
1692 // for a particular field of a particular type.
1693 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1695 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1696 if ($selectClause) {
1697 $select[] = $selectClause;
1701 // include statistics columns only if set
1702 if (CRM_Utils_Array
::value('statistics', $field)) {
1703 foreach ($field['statistics'] as $stat => $label) {
1704 $alias = "{$tableName}_{$fieldName}_{$stat}";
1705 switch (strtolower($stat)) {
1708 $select[] = "$stat({$field['dbAlias']}) as $alias";
1709 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1710 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1711 $this->_statFields
[] = $alias;
1712 $this->_selectAliases
[] = $alias;
1716 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1717 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1718 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1719 $this->_statFields
[] = $alias;
1720 $this->_selectAliases
[] = $alias;
1724 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1725 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1726 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1727 $this->_statFields
[] = $alias;
1728 $this->_selectAliases
[] = $alias;
1734 $alias = "{$tableName}_{$fieldName}";
1735 $select[] = "{$field['dbAlias']} as $alias";
1736 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1737 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1738 $this->_selectAliases
[] = $alias;
1744 // select for group bys
1745 if (array_key_exists('group_bys', $table)) {
1746 foreach ($table['group_bys'] as $fieldName => $field) {
1748 if ($tableName == 'civicrm_address') {
1749 $this->_addressField
= TRUE;
1751 if ($tableName == 'civicrm_email') {
1752 $this->_emailField
= TRUE;
1754 if ($tableName == 'civicrm_phone') {
1755 $this->_phoneField
= TRUE;
1757 // 1. In many cases we want select clause to be built in slightly different way
1758 // for a particular field of a particular type.
1759 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1761 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1762 if ($selectClause) {
1763 $select[] = $selectClause;
1767 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1768 && !empty($this->_params
['group_bys_freq'])) {
1769 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1771 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1772 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1773 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1774 $field['title'] = 'Week';
1778 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1779 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1780 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1781 $field['title'] = 'Year';
1785 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1786 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1787 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1788 $field['title'] = 'Month';
1792 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1793 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1794 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1795 $field['title'] = 'Quarter';
1798 // for graphs and charts -
1799 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1800 $this->_interval
= $field['title'];
1801 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1802 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1803 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1805 // just to make sure these values are transfered to rows.
1806 // since we 'll need them for calculation purpose,
1807 // e.g making subtotals look nicer or graphs
1808 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1809 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1816 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1819 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1824 $this->storeWhereHavingClauseArray();
1826 if (empty($this->_whereClauses
)) {
1827 $this->_where
= "WHERE ( 1 ) ";
1828 $this->_having
= "";
1831 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1834 if ($this->_aclWhere
) {
1835 $this->_where
.= " AND {$this->_aclWhere} ";
1838 if (!empty($this->_havingClauses
)) {
1839 // use this clause to construct group by clause.
1840 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1845 * Store Where clauses into an array - breaking out this step makes
1846 * over-riding more flexible as the clauses can be used in constructing a
1847 * temp table that may not be part of the final where clause or added
1848 * in other functions
1850 function storeWhereHavingClauseArray(){
1851 foreach ($this->_columns
as $tableName => $table) {
1852 if (array_key_exists('filters', $table)) {
1853 foreach ($table['filters'] as $fieldName => $field) {
1854 // respect pseudofield to filter spec so fields can be marked as
1855 // not to be handled here
1856 if(!empty($field['pseudofield'])){
1860 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1861 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1862 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1863 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1864 if (is_array($value) && !empty($value)) {
1865 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1869 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1870 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1871 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1872 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1873 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1874 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1878 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1880 $clause = $this->whereClause($field,
1882 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1883 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1884 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1889 if (!empty($clause)) {
1890 if (CRM_Utils_Array
::value('having', $field)) {
1891 $this->_havingClauses
[] = $clause;
1894 $this->_whereClauses
[] = $clause;
1902 function processReportMode() {
1903 $buttonName = $this->controller
->getButtonName();
1905 $output = CRM_Utils_Request
::retrieve(
1908 CRM_Core_DAO
::$_nullObject
1912 CRM_Utils_Request
::retrieve(
1915 CRM_Core_DAO
::$_nullObject
1918 $this->_absoluteUrl
= FALSE;
1920 $this->assign('printOnly', FALSE);
1922 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1923 $this->assign('printOnly', TRUE);
1925 $this->assign('outputMode', 'print');
1926 $this->_outputMode
= 'print';
1927 if ($this->_sendmail
) {
1928 $this->_absoluteUrl
= TRUE;
1931 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1932 $this->assign('printOnly', TRUE);
1934 $this->assign('outputMode', 'pdf');
1935 $this->_outputMode
= 'pdf';
1936 $this->_absoluteUrl
= TRUE;
1938 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
1939 $this->assign('printOnly', TRUE);
1941 $this->assign('outputMode', 'csv');
1942 $this->_outputMode
= 'csv';
1943 $this->_absoluteUrl
= TRUE;
1945 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
1946 $this->assign('outputMode', 'group');
1947 $this->_outputMode
= 'group';
1949 elseif ($output == 'create_report' && $this->_criteriaForm
) {
1950 $this->assign('outputMode', 'create_report');
1951 $this->_outputMode
= 'create_report';
1954 $this->assign('outputMode', 'html');
1955 $this->_outputMode
= 'html';
1958 // Get today's date to include in printed reports
1960 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
1961 $this->assign('reportDate', $reportDate);
1965 function beginPostProcess() {
1966 $this->_params
= $this->controller
->exportValues($this->_name
);
1968 if (empty($this->_params
) &&
1971 $this->_params
= $this->_formValues
;
1974 // hack to fix params when submitted from dashboard, CRM-8532
1975 // fields array is missing because form building etc is skipped
1976 // in dashboard mode for report
1977 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
1978 $this->_params
= $this->_formValues
;
1981 $this->_formValues
= $this->_params
;
1982 if (CRM_Core_Permission
::check('administer Reports') &&
1983 isset($this->_id
) &&
1984 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
1985 $this->_chartButtonName
== $this->controller
->getButtonName()
1988 $this->assign('updateReportButton', TRUE);
1990 $this->processReportMode();
1993 function buildQuery($applyLimit = TRUE) {
1996 $this->customDataFrom();
2001 // order_by columns not selected for display need to be included in SELECT
2002 $unselectedSectionColumns = $this->unselectedSectionColumns();
2003 foreach ($unselectedSectionColumns as $alias => $section) {
2004 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2007 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2010 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2012 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2016 function groupBy() {
2017 $groupBys = array();
2018 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2019 is_array($this->_params
['group_bys']) &&
2020 !empty($this->_params
['group_bys'])
2022 foreach ($this->_columns
as $tableName => $table) {
2023 if (array_key_exists('group_bys', $table)) {
2024 foreach ($table['group_bys'] as $fieldName => $field) {
2025 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2026 $groupBys[] = $field['dbAlias'];
2033 if (!empty($groupBys)) {
2034 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2038 function orderBy() {
2039 $this->_orderBy
= "";
2040 $this->_sections
= array();
2041 $this->storeOrderByArray();
2042 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2043 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2045 $this->assign('sections', $this->_sections
);
2048 * In some cases other functions want to know which fields are selected for ordering by
2049 * Separating this into a separate function allows it to be called separately from constructing
2050 * the order by clause
2052 function storeOrderByArray() {
2053 $orderBys = array();
2055 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2056 is_array($this->_params
['order_bys']) &&
2057 !empty($this->_params
['order_bys'])
2060 // Proces order_bys in user-specified order
2061 foreach ($this->_params
['order_bys'] as $orderBy) {
2062 $orderByField = array();
2063 foreach ($this->_columns
as $tableName => $table) {
2064 if (array_key_exists('order_bys', $table)) {
2065 // For DAO columns defined in $this->_columns
2066 $fields = $table['order_bys'];
2068 elseif (array_key_exists('extends', $table)) {
2069 // For custom fields referenced in $this->_customGroupExtends
2070 $fields = $table['fields'];
2072 if (!empty($fields) && is_array($fields)) {
2073 foreach ($fields as $fieldName => $field) {
2074 if ($fieldName == $orderBy['column']) {
2075 $orderByField = $field;
2076 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2083 if (!empty($orderByField)) {
2084 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2086 // Record any section headers for assignment to the template
2087 if (CRM_Utils_Array
::value('section', $orderBy)) {
2088 $this->_sections
[$orderByField['tplField']] = $orderByField;
2094 $this->_orderByArray
= $orderBys;
2096 $this->assign('sections', $this->_sections
);
2099 function unselectedSectionColumns() {
2100 $selectColumns = array();
2101 foreach ($this->_columns
as $tableName => $table) {
2102 if (array_key_exists('fields', $table)) {
2103 foreach ($table['fields'] as $fieldName => $field) {
2104 if (CRM_Utils_Array
::value('required', $field) ||
2105 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2108 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2113 if (is_array($this->_sections
)) {
2114 return array_diff_key($this->_sections
, $selectColumns);
2121 function buildRows($sql, &$rows) {
2122 $dao = CRM_Core_DAO
::executeQuery($sql);
2123 if (!is_array($rows)) {
2127 // use this method to modify $this->_columnHeaders
2128 $this->modifyColumnHeaders();
2130 $unselectedSectionColumns = $this->unselectedSectionColumns();
2132 while ($dao->fetch()) {
2134 foreach ($this->_columnHeaders
as $key => $value) {
2135 if (property_exists($dao, $key)) {
2136 $row[$key] = $dao->$key;
2140 // section headers not selected for display need to be added to row
2141 foreach ($unselectedSectionColumns as $key => $values) {
2142 if (property_exists($dao, $key)) {
2143 $row[$key] = $dao->$key;
2152 * When "order by" fields are marked as sections, this assigns to the template
2153 * an array of total counts for each section. This data is used by the Smarty
2154 * plugin {sectionTotal}
2156 function sectionTotals() {
2158 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2159 if (empty($this->_selectAliases
)) {
2163 if (!empty($this->_sections
)) {
2164 // build the query with no LIMIT clause
2165 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2166 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2168 // pull section aliases out of $this->_sections
2169 $sectionAliases = array_keys($this->_sections
);
2172 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2173 $ifnulls[] = "ifnull($alias, '') as $alias";
2176 /* Group (un-limited) report by all aliases and get counts. This might
2177 * be done more efficiently when the contents of $sql are known, ie. by
2178 * overriding this method in the report class.
2182 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2184 // initialize array of total counts
2186 $dao = CRM_Core_DAO
::executeQuery($query);
2187 while ($dao->fetch()) {
2189 // let $this->_alterDisplay translate any integer ids to human-readable values.
2190 $rows[0] = $dao->toArray();
2191 $this->alterDisplay($rows);
2194 // add totals for all permutations of section values
2197 $aliasCount = count($sectionAliases);
2198 foreach ($sectionAliases as $alias) {
2199 $values[] = $row[$alias];
2200 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2201 if ($i == $aliasCount) {
2202 // the last alias is the lowest-level section header; use count as-is
2203 $totals[$key] = $dao->ct
;
2206 // other aliases are higher level; roll count into their total
2207 $totals[$key] +
= $dao->ct
;
2211 $this->assign('sectionTotals', $totals);
2215 function modifyColumnHeaders() {
2216 // use this method to modify $this->_columnHeaders
2219 function doTemplateAssignment(&$rows) {
2220 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2221 $this->assign_by_ref('rows', $rows);
2222 $this->assign('statistics', $this->statistics($rows));
2225 // override this method to build your own statistics
2226 function statistics(&$rows) {
2227 $statistics = array();
2229 $count = count($rows);
2231 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2235 $this->countStat($statistics, $count);
2237 $this->groupByStat($statistics);
2239 $this->filterStat($statistics);
2244 function countStat(&$statistics, $count) {
2245 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2249 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2250 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2251 'value' => $this->_rowsFound
,
2256 function groupByStat(&$statistics) {
2257 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2258 is_array($this->_params
['group_bys']) &&
2259 !empty($this->_params
['group_bys'])
2261 foreach ($this->_columns
as $tableName => $table) {
2262 if (array_key_exists('group_bys', $table)) {
2263 foreach ($table['group_bys'] as $fieldName => $field) {
2264 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2265 $combinations[] = $field['title'];
2270 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2271 'value' => implode(' & ', $combinations),
2276 function filterStat(&$statistics) {
2277 foreach ($this->_columns
as $tableName => $table) {
2278 if (array_key_exists('filters', $table)) {
2279 foreach ($table['filters'] as $fieldName => $field) {
2280 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2283 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2284 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2285 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2286 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2287 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2289 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2290 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2292 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2293 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2296 $statistics['filters'][] = array(
2297 'title' => $field['title'],
2298 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2301 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2302 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2304 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2305 $statistics['filters'][] = array(
2306 'title' => $field['title'],
2307 'value' => $pair[$rel],
2312 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2315 $pair = $this->getOperationPair(
2316 CRM_Utils_Array
::value('operatorType', $field),
2319 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2320 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2321 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2322 if (in_array($op, array(
2323 'bw', 'nbw')) && ($min ||
$max)) {
2324 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2326 elseif ($op == 'nll' ||
$op == 'nnll') {
2327 $value = $pair[$op];
2329 elseif (is_array($val) && (!empty($val))) {
2330 $options = $field['options'];
2331 foreach ($val as $key => $valIds) {
2332 if (isset($options[$valIds])) {
2333 $val[$key] = $options[$valIds];
2336 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : $pair[$op];
2337 $val = implode(', ', $val);
2338 $value = "{$pair[$op]} " . $val;
2340 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2341 is_array($field['options']) && !empty($field['options'])
2343 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2346 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2350 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2360 function endPostProcess(&$rows = NULL) {
2361 if ($this->_outputMode
== 'print' ||
2362 $this->_outputMode
== 'pdf' ||
2366 $content = $this->compileContent();
2367 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2371 if ($this->_sendmail
) {
2372 $config = CRM_Core_Config
::singleton();
2373 $attachments = array();
2375 if ($this->_outputMode
== 'csv') {
2376 $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'];
2378 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2379 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2380 file_put_contents($csvFullFilename, $csvContent);
2381 $attachments[] = array(
2382 'fullPath' => $csvFullFilename,
2383 'mime_type' => 'text/csv',
2384 'cleanName' => 'CiviReport.csv',
2387 if ($this->_outputMode
== 'pdf') {
2388 // generate PDF content
2389 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2390 file_put_contents($pdfFullFilename,
2391 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2392 TRUE, array('orientation' => 'landscape')
2395 // generate Email Content
2396 $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'];
2398 $attachments[] = array(
2399 'fullPath' => $pdfFullFilename,
2400 'mime_type' => 'application/pdf',
2401 'cleanName' => 'CiviReport.pdf',
2405 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2406 $this->_outputMode
, $attachments
2408 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2411 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2414 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2416 elseif ($this->_outputMode
== 'print') {
2420 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2421 $config = CRM_Core_Config
::singleton();
2422 //get chart image name
2423 $chartImg = $this->_chartId
. '.png';
2424 //get image url path
2425 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2426 $uploadUrl .= $chartImg;
2427 //get image doc path to overwrite
2428 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2430 $chart = imagecreatefrompng($uploadUrl);
2431 //convert it into formattd png
2432 header('Content-type: image/png');
2433 //overwrite with same image
2434 imagepng($chart, $uploadImg);
2436 imagedestroy($chart);
2438 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2440 CRM_Utils_System
::civiExit();
2442 elseif ($this->_outputMode
== 'csv') {
2443 CRM_Report_Utils_Report
::export2csv($this, $rows);
2445 elseif ($this->_outputMode
== 'group') {
2446 $group = $this->_params
['groups'];
2447 $this->add2group($group);
2449 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2450 CRM_Report_Form_Instance
::postProcess($this);
2452 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2453 $this->_outputMode
== 'create_report' ) {
2454 $this->_createNew
= TRUE;
2455 CRM_Report_Form_Instance
::postProcess($this);
2460 * Get Template file name - use default form template if a specific one has not been set up for this report
2463 function getTemplateFileName(){
2464 $defaultTpl = parent
::getTemplateFileName();
2465 $template = CRM_Core_Smarty
::singleton();
2466 if (!$template->template_exists($defaultTpl)) {
2467 $defaultTpl = 'CRM/Report/Form.tpl';
2473 * Compile the report content
2475 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2477 function compileContent(){
2478 $templateFile = $this->getTemplateFileName();
2479 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2483 function postProcess() {
2484 // get ready with post process params
2485 $this->beginPostProcess();
2488 $sql = $this->buildQuery();
2490 // build array of result based on column headers. This method also allows
2491 // modifying column headers before using it to build result set i.e $rows.
2493 $this->buildRows($sql, $rows);
2495 // format result set.
2496 $this->formatDisplay($rows);
2498 // assign variables to templates
2499 $this->doTemplateAssignment($rows);
2501 // do print / pdf / instance stuff if needed
2502 $this->endPostProcess($rows);
2505 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2506 // lets do the pager if in html mode
2507 $this->_limit
= NULL;
2508 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2509 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2511 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2513 if (!$pageId && !empty($_POST)) {
2514 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2515 $pageId = max((int)@$_POST['crmPID_B'], 1);
2517 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2518 $pageId = max((int)@$_POST['crmPID'], 1);
2520 unset($_POST['crmPID_B'], $_POST['crmPID']);
2523 $pageId = $pageId ?
$pageId : 1;
2524 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2525 $offset = ($pageId - 1) * $rowCount;
2527 $this->_limit
= " LIMIT $offset, " . $rowCount;
2528 return array($offset, $rowCount);
2532 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2533 if ($this->_limit
&& ($this->_limit
!= '')) {
2534 $sql = "SELECT FOUND_ROWS();";
2535 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2537 'total' => $this->_rowsFound
,
2538 'rowCount' => $rowCount,
2539 'status' => ts('Records') . ' %%StatusMessage%%',
2540 'buttonBottom' => 'PagerBottomButton',
2541 'buttonTop' => 'PagerTopButton',
2542 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2545 $pager = new CRM_Utils_Pager($params);
2546 $this->assign_by_ref('pager', $pager);
2550 function whereGroupClause($field, $value, $op) {
2552 $smartGroupQuery = "";
2554 $group = new CRM_Contact_DAO_Group();
2555 $group->is_active
= 1;
2557 $smartGroups = array();
2558 while ($group->fetch()) {
2559 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2560 $smartGroups[] = $group->id
;
2564 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2566 $smartGroupQuery = '';
2567 if (!empty($smartGroups)) {
2568 $smartGroups = implode(',', $smartGroups);
2569 $smartGroupQuery = " UNION DISTINCT
2570 SELECT DISTINCT smartgroup_contact.contact_id
2571 FROM civicrm_group_contact_cache smartgroup_contact
2572 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2575 $sqlOp = $this->getSQLOperator($op);
2576 if (!is_array($value)) {
2577 $value = array($value);
2579 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2581 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2582 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2583 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2584 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2585 {$smartGroupQuery} ) ";
2588 function whereTagClause($field, $value, $op) {
2589 // not using left join in query because if any contact
2590 // belongs to more than one tag, results duplicate
2592 $sqlOp = $this->getSQLOperator($op);
2593 if (!is_array($value)) {
2594 $value = array($value);
2596 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2598 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2599 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2600 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2601 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2604 function buildACLClause($tableAlias = 'contact_a') {
2605 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2608 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2609 if (empty($this->_customGroupExtends
)) {
2612 if (!is_array($this->_customGroupExtends
)) {
2613 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2615 $customGroupWhere = '';
2616 if (!empty($permCustomGroupIds)) {
2617 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2620 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2621 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2622 FROM civicrm_custom_group cg
2623 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2624 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2626 cg.is_active = 1 AND
2627 cf.is_active = 1 AND
2628 cf.is_searchable = 1
2629 ORDER BY cg.weight, cf.weight";
2630 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2633 while ($customDAO->fetch()) {
2634 if ($customDAO->table_name
!= $curTable) {
2635 $curTable = $customDAO->table_name
;
2636 $curFields = $curFilters = array();
2639 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2640 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2641 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2642 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2645 'fields', 'filters', 'group_bys') as $colKey) {
2646 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2647 $this->_columns
[$curTable][$colKey] = array();
2651 $fieldName = 'custom_' . $customDAO->cf_id
;
2654 // this makes aliasing work in favor
2655 $curFields[$fieldName] = array(
2656 'name' => $customDAO->column_name
,
2657 'title' => $customDAO->label
,
2658 'dataType' => $customDAO->data_type
,
2659 'htmlType' => $customDAO->html_type
,
2662 if ($this->_customGroupFilters
) {
2663 // this makes aliasing work in favor
2664 $curFilters[$fieldName] = array(
2665 'name' => $customDAO->column_name
,
2666 'title' => $customDAO->label
,
2667 'dataType' => $customDAO->data_type
,
2668 'htmlType' => $customDAO->html_type
,
2672 switch ($customDAO->data_type
) {
2675 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2676 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2677 // CRM-6946, show time part for datetime date fields
2678 if ($customDAO->time_format
) {
2679 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2684 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2685 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2689 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2693 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2694 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2698 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2699 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2703 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2704 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2708 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2710 if (!empty($customDAO->option_group_id
)) {
2711 if (in_array($customDAO->html_type
, array(
2712 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2713 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2716 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2718 if ($this->_customGroupFilters
) {
2719 $curFilters[$fieldName]['options'] = array();
2720 $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')));
2721 while ($ogDAO->fetch()) {
2722 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2728 case 'StateProvince':
2729 if (in_array($customDAO->html_type
, array(
2730 'Multi-Select State/Province'))) {
2731 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2734 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2736 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2740 if (in_array($customDAO->html_type
, array(
2741 'Multi-Select Country'))) {
2742 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2745 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2747 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2750 case 'ContactReference':
2751 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2752 $curFilters[$fieldName]['name'] = 'display_name';
2753 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2755 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2756 $curFields[$fieldName]['name'] = 'display_name';
2757 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2761 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2762 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2765 if (!array_key_exists('type', $curFields[$fieldName])) {
2766 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2770 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2772 if ($this->_customGroupFilters
) {
2773 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2775 if ($this->_customGroupGroupBy
) {
2776 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2781 function customDataFrom() {
2782 if (empty($this->_customGroupExtends
)) {
2785 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2787 foreach ($this->_columns
as $table => $prop) {
2788 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2789 $extendsTable = $mapper[$prop['extends']];
2791 // check field is in params
2792 if (!$this->isFieldSelected($prop)) {
2797 LEFT JOIN $table {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2798 // handle for ContactReference
2799 if (array_key_exists('fields', $prop)) {
2800 foreach ($prop['fields'] as $fieldName => $field) {
2801 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2802 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2804 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2812 function isFieldSelected($prop) {
2817 if (!empty($this->_params
['fields'])) {
2818 foreach (array_keys($prop['fields']) as $fieldAlias) {
2819 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2820 if ($customFieldId) {
2821 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2825 //might be survey response field.
2826 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2827 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2835 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2836 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2837 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2843 if (!empty($this->_params
['order_bys'])) {
2844 foreach (array_keys($prop['fields']) as $fieldAlias) {
2845 foreach ($this->_params
['order_bys'] as $orderBy) {
2846 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2853 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2854 foreach ($prop['filters'] as $fieldAlias => $val) {
2856 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2857 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2858 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2859 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2865 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2866 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2877 * Check for empty order_by configurations and remove them; also set
2878 * template to hide them.
2880 function preProcessOrderBy(&$formValues) {
2881 // Object to show/hide form elements
2882 $_showHide = &new CRM_Core_ShowHideBlocks('', '');
2884 $_showHide->addShow('optionField_1');
2886 // Cycle through order_by options; skip any empty ones, and hide them as well
2889 if (!empty($formValues['order_bys'])) {
2890 foreach ($formValues['order_bys'] as $order_by) {
2891 if ($order_by['column'] && $order_by['column'] != '-') {
2892 $_showHide->addShow('optionField_' . $n);
2893 $orderBys[$n] = $order_by;
2898 for ($i = $n; $i <= 5; $i++
) {
2900 $_showHide->addHide('optionField_' . $i);
2904 // overwrite order_by options with modified values
2905 if (!empty($orderBys)) {
2906 $formValues['order_bys'] = $orderBys;
2909 $formValues['order_bys'] = array(1 => array('column' => '-'));
2912 // assign show/hide data to template
2913 $_showHide->addToTemplate();
2917 * Does table name have columns in SELECT clause?
2919 * @param string $tableName Name of table (index of $this->_columns array)
2923 function isTableSelected($tableName) {
2924 return in_array($tableName, $this->selectedTables());
2928 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
2929 * (building the array if it's unset)
2931 * @return Array $this->_selectedTables
2933 function selectedTables() {
2934 if (!$this->_selectedTables
) {
2935 $orderByColumns = array();
2936 if (is_array($this->_params
['order_bys'])) {
2937 foreach ($this->_params
['order_bys'] as $orderBy) {
2938 $orderByColumns[] = $orderBy['column'];
2942 foreach ($this->_columns
as $tableName => $table) {
2943 if (array_key_exists('fields', $table)) {
2944 foreach ($table['fields'] as $fieldName => $field) {
2945 if (CRM_Utils_Array
::value('required', $field) ||
2946 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2948 $this->_selectedTables
[] = $tableName;
2953 if (array_key_exists('order_bys', $table)) {
2954 foreach ($table['order_bys'] as $orderByName => $orderBy) {
2955 if (in_array($orderByName, $orderByColumns)) {
2956 $this->_selectedTables
[] = $tableName;
2961 if (array_key_exists('filters', $table)) {
2962 foreach ($table['filters'] as $filterName => $filter) {
2963 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
2964 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
2965 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
2967 $this->_selectedTables
[] = $tableName;
2974 return $this->_selectedTables
;
2978 * @deprecated - use getAddressColumns which is a more accurate description
2979 * and also accepts an array of options rather than a long list
2981 * function for adding address fields to construct function in reports
2982 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
2983 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
2984 * @return array address fields for construct clause
2986 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
2987 'country_id' => TRUE)) {
2988 $addressFields = array(
2989 'civicrm_address' =>
2991 'dao' => 'CRM_Core_DAO_Address',
2995 array('title' => ts('Address Name'),
2996 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
2999 array('title' => ts('Street Address'),
3000 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3002 'supplemental_address_1' =>
3003 array('title' => ts('Supplementary Address Field 1'),
3004 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3006 'supplemental_address_2' =>
3007 array('title' => ts('Supplementary Address Field 2'),
3008 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3012 'name' => 'street_number',
3013 'title' => ts('Street Number'),
3015 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3019 'name' => 'street_name',
3020 'title' => ts('Street Name'),
3022 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3026 'name' => 'street_unit',
3027 'title' => ts('Street Unit'),
3029 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3032 array('title' => ts('City'),
3033 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3036 array('title' => ts('Postal Code'),
3037 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3040 array('title' => ts('County'),
3041 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3043 'state_province_id' =>
3044 array('title' => ts('State/Province'),
3045 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3048 array('title' => ts('Country'),
3049 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3052 'grouping' => 'location-fields',
3057 $addressFields['civicrm_address']['filters'] = array(
3058 'street_number' => array('title' => ts('Street Number'),
3060 'name' => 'street_number',
3062 'street_name' => array('title' => ts('Street Name'),
3063 'name' => 'street_name',
3064 'operator' => 'like',
3066 'postal_code' => array('title' => ts('Postal Code'),
3068 'name' => 'postal_code',
3070 'city' => array('title' => ts('City'),
3071 'operator' => 'like',
3074 'county_id' => array(
3075 'name' => 'county_id',
3076 'title' => ts('County'),
3077 'type' => CRM_Utils_Type
::T_INT
,
3079 CRM_Report_Form
::OP_MULTISELECT
,
3081 CRM_Core_PseudoConstant
::county(),
3083 'state_province_id' => array(
3084 'name' => 'state_province_id',
3085 'title' => ts('State/Province'),
3086 'type' => CRM_Utils_Type
::T_INT
,
3088 CRM_Report_Form
::OP_MULTISELECT
,
3090 CRM_Core_PseudoConstant
::stateProvince(),
3092 'country_id' => array(
3093 'name' => 'country_id',
3094 'title' => ts('Country'),
3095 'type' => CRM_Utils_Type
::T_INT
,
3097 CRM_Report_Form
::OP_MULTISELECT
,
3099 CRM_Core_PseudoConstant
::country(),
3105 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3106 'street_number' => array('title' => 'Odd / Even Street Number'),
3107 'street_address' => NULL,
3109 'postal_code' => NULL,
3114 $addressFields['civicrm_address']['group_bys'] = array(
3115 'street_address' => NULL,
3117 'postal_code' => NULL,
3118 'state_province_id' =>
3119 array('title' => ts('State/Province'),
3122 array('title' => ts('Country'),
3125 array('title' => ts('County'),
3129 return $addressFields;
3133 * Do AlterDisplay processing on Address Fields
3135 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3136 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3137 $entryFound = FALSE;
3139 if (array_key_exists('civicrm_address_country_id', $row)) {
3140 if ($value = $row['civicrm_address_country_id']) {
3141 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3142 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3143 "reset=1&force=1&{$criteriaQueryParams}&" .
3144 "country_id_op=in&country_id_value={$value}",
3145 $this->_absoluteUrl
, $this->_id
3147 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3148 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3155 if (array_key_exists('civicrm_address_county_id', $row)) {
3156 if ($value = $row['civicrm_address_county_id']) {
3157 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3158 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3159 "reset=1&force=1&{$criteriaQueryParams}&" .
3160 "county_id_op=in&county_id_value={$value}",
3161 $this->_absoluteUrl
, $this->_id
3163 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3164 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3170 // handle state province
3171 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3172 if ($value = $row['civicrm_address_state_province_id']) {
3173 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3175 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3176 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3177 $this->_absoluteUrl
, $this->_id
3179 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3180 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3191 * Adjusts dates passed in to YEAR() for fiscal year.
3193 function fiscalYearOffset($fieldName) {
3194 $config = CRM_Core_Config
::singleton();
3195 $fy = $config->fiscalYearStart
;
3196 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3197 return "YEAR( $fieldName )";
3199 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3203 * Add Address into From Table if required
3205 function addAddressFromClause() {
3206 // include address field if address column is to be included
3207 if ((isset($this->_addressField
) &&
3208 $this->_addressField
3210 $this->isTableSelected('civicrm_address')
3213 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3214 ON ({$this->_aliases['civicrm_contact']}.id =
3215 {$this->_aliases['civicrm_address']}.contact_id) AND
3216 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3221 * Add Phone into From Table if required
3223 function addPhoneFromClause() {
3224 // include address field if address column is to be included
3225 if ($this->isTableSelected('civicrm_phone')
3228 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3229 ON ({$this->_aliases['civicrm_contact']}.id =
3230 {$this->_aliases['civicrm_phone']}.contact_id) AND
3231 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3236 * Get phone columns to add to array
3237 * @param array $options
3238 * - prefix Prefix to add to table (in case of more than one instance of the table)
3239 * - prefix_label Label to give columns from this phone table instance
3240 * @return array phone columns definition
3242 function getPhoneColumns($options = array()){
3243 $defaultOptions = array(
3245 'prefix_label' => '',
3248 $options = array_merge($defaultOptions,$options);
3251 $options['prefix'] . 'civicrm_phone' => array(
3252 'dao' => 'CRM_Core_DAO_Phone',
3254 $options['prefix'] . 'phone' => array(
3255 'title' => ts($options['prefix_label'] . 'Phone'),
3265 * Get address columns to add to array
3266 * @param array $options
3267 * - prefix Prefix to add to table (in case of more than one instance of the table)
3268 * - prefix_label Label to give columns from this address table instance
3269 * @return array address columns definition
3271 function getAddressColumns($options = array()){
3272 $defaultOptions = array(
3274 'prefix_label' => '',
3278 'defaults' => array(
3281 $options = array_merge($defaultOptions,$options);
3282 return $this->addAddressFields(
3283 $options['group_by'],
3284 $options['order_by'],
3285 $options['filters'],
3286 $options['defaults']
3291 function add2group($groupID) {
3292 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3293 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3294 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3296 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3297 $dao = CRM_Core_DAO
::executeQuery($sql);
3299 $contact_ids = array();
3300 // Add resulting contacts to group
3301 while ($dao->fetch()) {
3302 if ($dao->addtogroup_contact_id
) {
3303 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3307 if ( !empty($contact_ids) ) {
3308 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3309 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3312 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));