5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
33 * @copyright CiviCRM LLC (c) 2004-2013
37 class CRM_Report_Form
extends CRM_Core_Form
{
38 CONST ROW_COUNT_LIMIT
= 50;
41 * Operator types - used for displaying filter elements
51 OP_MULTISELECT_SEPARATOR
= 66,
55 * The id of the report instance
62 * The id of the report template
66 protected $_templateID;
74 protected $_noFields = FALSE;
77 * The set of all columns in the report. An associative array
78 * with column name as the key and attribues as the value
82 protected $_columns = array();
85 * The set of filters in the report
89 protected $_filters = array();
92 * The set of optional columns in the report
96 protected $_options = array();
98 protected $_defaults = array();
101 * By default most reports hide contact id.
102 * Setting this to true makes it available
104 protected $_exposeContactID = TRUE;
107 * Set of statistic fields
111 protected $_statFields = array();
114 * Set of statistics data
118 protected $_statistics = array();
121 * List of fields not to be repeated during display
125 protected $_noRepeats = array();
128 * List of fields not to be displayed
132 protected $_noDisplay = array();
135 * Object type that a custom group extends
139 protected $_customGroupExtends = NULL;
140 protected $_customGroupFilters = TRUE;
141 protected $_customGroupGroupBy = FALSE;
147 protected $_tagFilter = FALSE;
150 * build groups filter
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * An attribute for checkbox/radio form field layout
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
174 protected $_force = 1;
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_rowsFound = NULL;
194 protected $_selectAliases = array();
195 protected $_rollup = NULL;
196 protected $_limit = NULL;
197 protected $_sections = NULL;
198 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
199 protected $_absoluteUrl = FALSE;
202 * To what frequency group-by a date column
206 protected $_groupByDateFreq = array(
208 'YEARWEEK' => 'Week',
209 'QUARTER' => 'Quarter',
214 * Variables to hold the acl inner join and where clause
216 protected $_aclFrom = NULL;
217 protected $_aclWhere = NULL;
220 * Array of DAO tables having columns included in SELECT or ORDER BY clause
224 protected $_selectedTables;
226 public $_having = NULL;
227 public $_select = NULL;
228 public $_columnHeaders = array();
229 public $_orderBy = NULL;
230 public $_groupBy = NULL;
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
::customGroup();
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 static 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 self
::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( );");
430 require_once str_replace('_', DIRECTORY_SEPARATOR
, $table['dao'] . '.php');
431 eval("\$expFields = {$table['dao']}::export( );");
434 $doNotCopy = array('required');
436 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
437 foreach ($fieldGroups as $fieldGrp) {
438 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
439 foreach ($table[$fieldGrp] as $fieldName => $field) {
440 // $name is the field name used to reference the BAO/DAO export fields array
441 $name = isset($field['name']) ?
$field['name'] : $fieldName;
443 // Sometimes the field name key in the BAO/DAO export fields array is
444 // different from the actual database field name.
445 // Unset $field['name'] so that actual database field name can be obtained
446 // from the BAO/DAO export fields array.
447 unset($field['name']);
449 if (array_key_exists($name, $expFields)) {
450 foreach ($doNotCopy as $dnc) {
451 // unset the values we don't want to be copied.
452 unset($expFields[$name][$dnc]);
455 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
458 foreach ($expFields[$name] as $property => $val) {
459 if (!array_key_exists($property, $field)) {
460 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
467 if (CRM_Utils_Array
::value('no_repeat', $field)) {
468 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
470 if (CRM_Utils_Array
::value('no_display', $field)) {
471 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
474 // set alias = table-name, unless already set
475 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
476 $this->_columns
[$tableName]['alias'] : $tableName
478 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
480 // set name = fieldName, unless already set
481 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
482 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
485 // set dbAlias = alias.name, unless already set
486 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
487 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
490 if (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName]) &&
491 !isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'])
493 if (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
494 array(CRM_Utils_Type
::T_MONEY
, CRM_Utils_Type
::T_FLOAT
)
496 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
498 elseif (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
499 array(CRM_Utils_Type
::T_INT
)
501 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
508 // copy filters to a separate handy variable
509 if (array_key_exists('filters', $table)) {
510 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
513 if (array_key_exists('group_bys', $table)) {
514 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
517 if (array_key_exists('fields', $table)) {
518 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
523 $this->setDefaultValues(FALSE);
526 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
527 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
528 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
529 CRM_Report_Utils_Get
::processChart($this->_defaults
);
532 $this->_formValues
= $this->_defaults
;
533 $this->postProcess();
537 function setDefaultValues($freeze = TRUE) {
538 $freezeGroup = array();
540 // FIXME: generalizing form field naming conventions would reduce
541 // lots of lines below.
542 foreach ($this->_columns
as $tableName => $table) {
543 if (array_key_exists('fields', $table)) {
544 foreach ($table['fields'] as $fieldName => $field) {
545 if (!array_key_exists('no_display', $field)) {
546 if (isset($field['required'])) {
548 $this->_defaults
['fields'][$fieldName] = 1;
551 // find element object, so that we could use quickform's freeze method
552 // for required elements
553 $obj = $this->getElementFromGroup("fields", $fieldName);
555 $freezeGroup[] = $obj;
559 elseif (isset($field['default'])) {
560 $this->_defaults
['fields'][$fieldName] = $field['default'];
566 if (array_key_exists('group_bys', $table)) {
567 foreach ($table['group_bys'] as $fieldName => $field) {
568 if (isset($field['default'])) {
569 if (CRM_Utils_Array
::value('frequency', $field)) {
570 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
572 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
576 if (array_key_exists('filters', $table)) {
577 foreach ($table['filters'] as $fieldName => $field) {
578 if (isset($field['default'])) {
579 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
580 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
583 $this->_defaults
["{$fieldName}_value"] = $field['default'];
586 //assign default value as "in" for multiselect
587 //operator, To freeze the select element
588 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
589 $this->_defaults
["{$fieldName}_op"] = 'in';
591 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
592 $this->_defaults
["{$fieldName}_op"] = 'mhas';
594 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
595 $this->_defaults
["{$fieldName}_op"] = $op;
601 array_key_exists('order_bys', $table) &&
602 is_array($table['order_bys'])
604 if (!array_key_exists('order_bys', $this->_defaults
)) {
605 $this->_defaults
['order_bys'] = array();
607 foreach ($table['order_bys'] as $fieldName => $field) {
609 CRM_Utils_Array
::value('default', $field) ||
610 CRM_Utils_Array
::value('default_order', $field) ||
611 CRM_Utils_Array
::value('default_is_section', $field) ||
612 CRM_Utils_Array
::value('default_weight', $field)
615 'column' => $fieldName,
616 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
617 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
620 if (CRM_Utils_Array
::value('default_weight', $field)) {
621 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
624 array_unshift($this->_defaults
['order_bys'], $order_by);
630 foreach ($this->_options
as $fieldName => $field) {
631 if (isset($field['default'])) {
632 $this->_defaults
['options'][$fieldName] = $field['default'];
637 if (!empty($this->_submitValues
)) {
638 $this->preProcessOrderBy($this->_submitValues
);
641 $this->preProcessOrderBy($this->_defaults
);
644 // lets finish freezing task here itself
645 if (!empty($freezeGroup)) {
646 foreach ($freezeGroup as $elem) {
651 if ($this->_formValues
) {
652 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
655 if ($this->_instanceValues
) {
656 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
659 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
661 return $this->_defaults
;
664 function getElementFromGroup($group, $grpFieldName) {
665 $eleObj = $this->getElement($group);
666 foreach ($eleObj->_elements
as $index => $obj) {
667 if ($grpFieldName == $obj->_attributes
['name']) {
674 function addColumns() {
677 foreach ($this->_columns
as $tableName => $table) {
678 if (array_key_exists('fields', $table)) {
679 foreach ($table['fields'] as $fieldName => $field) {
680 if (!array_key_exists('no_display', $field)) {
681 if (isset($field['grouping'])) {
682 $tableName = $field['grouping'];
684 elseif (isset($table['grouping'])) {
685 $tableName = $table['grouping'];
687 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
689 if (isset($table['group_title'])) {
690 $colGroups[$tableName]['group_title'] = $table['group_title'];
693 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
699 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
700 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
702 $this->assign('colGroups', $colGroups);
705 function addFilters() {
706 $options = $filters = array();
708 foreach ($this->_filters
as $table => $attributes) {
709 foreach ($attributes as $fieldName => $field) {
710 // get ready with option value pair
711 $operations = self
::getOperationPair(
712 CRM_Utils_Array
::value('operatorType', $field),
716 $filters[$table][$fieldName] = $field;
718 switch (CRM_Utils_Array
::value('operatorType', $field)) {
719 case CRM_Report_Form
::OP_MONTH
:
720 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
721 // If there's no option list for this filter, define one.
722 $field['options'] = array(
731 9 => ts('September'),
733 11 => ts('November'),
734 12 => ts('December'),
736 // Add this option list to this column _columns. This is
737 // required so that filter statistics show properly.
738 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
740 case CRM_Report_FORM
::OP_MULTISELECT
:
741 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
742 // assume a multi-select field
743 if (!empty($field['options'])) {
744 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
745 if (count($operations) <= 1) {
748 $select = $this->addElement('select', "{$fieldName}_value", NULL,
749 $field['options'], array(
751 'style' => 'min-width:250px',
754 $select->setMultiple(TRUE);
758 case CRM_Report_FORM
::OP_SELECT
:
759 // assume a select field
760 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
761 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
764 case CRM_Report_FORM
::OP_DATE
:
765 // build datetime fields
766 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count);
770 case CRM_Report_FORM
::OP_DATETIME
:
771 // build datetime fields
772 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, TRUE, 'searchDate', true);
776 case CRM_Report_FORM
::OP_INT
:
777 case CRM_Report_FORM
::OP_FLOAT
:
778 // and a min value input box
779 $this->add('text', "{$fieldName}_min", ts('Min'));
780 // and a max value input box
781 $this->add('text', "{$fieldName}_max", ts('Max'));
783 // default type is string
784 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
785 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
787 // we need text box for value input
788 $this->add('text', "{$fieldName}_value", NULL);
793 $this->assign('filters', $filters);
796 function addOptions() {
797 if (!empty($this->_options
)) {
798 // FIXME: For now lets build all elements as checkboxes.
799 // Once we clear with the format we can build elements based on type
802 foreach ($this->_options
as $fieldName => $field) {
803 if ($field['type'] == 'select') {
804 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
807 $options[$field['title']] = $fieldName;
811 $this->addCheckBox("options", $field['title'],
813 NULL, NULL, NULL, $this->_fourColumnAttribute
818 function addChartOptions() {
819 if (!empty($this->_charts
)) {
820 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
821 $this->assign('charts', $this->_charts
);
822 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
826 function addGroupBys() {
827 $options = $freqElements = array();
829 foreach ($this->_columns
as $tableName => $table) {
830 if (array_key_exists('group_bys', $table)) {
831 foreach ($table['group_bys'] as $fieldName => $field) {
832 if (!empty($field)) {
833 $options[$field['title']] = $fieldName;
834 if (CRM_Utils_Array
::value('frequency', $field)) {
835 $freqElements[$field['title']] = $fieldName;
841 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
842 NULL, NULL, NULL, $this->_fourColumnAttribute
844 $this->assign('groupByElements', $options);
846 foreach ($freqElements as $name) {
847 $this->addElement('select', "group_bys_freq[$name]",
848 ts('Frequency'), $this->_groupByDateFreq
853 function addOrderBys() {
855 foreach ($this->_columns
as $tableName => $table) {
857 // Report developer may define any column to order by; include these as order-by options
858 if (array_key_exists('order_bys', $table)) {
859 foreach ($table['order_bys'] as $fieldName => $field) {
860 if (!empty($field)) {
861 $options[$fieldName] = $field['title'];
866 /* Add searchable custom fields as order-by options, if so requested
867 * (These are already indexed, so allowing to order on them is cheap.)
871 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
872 foreach ($table['fields'] as $fieldName => $field) {
873 if (!array_key_exists('no_display', $field)) {
874 $options[$fieldName] = $field['title'];
882 $this->assign('orderByOptions', $options);
884 if (!empty($options)) {
886 '-' => ' - none - ') +
$options;
887 for ($i = 1; $i <= 5; $i++
) {
888 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
889 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
890 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
895 function buildInstanceAndButtons() {
896 CRM_Report_Form_Instance
::buildForm($this);
898 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
900 $this->addElement('submit', $this->_instanceButtonName
, $label);
901 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
902 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
905 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
907 if ($this->_instanceForm
) {
908 $this->assign('instanceForm', TRUE);
911 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
912 $this->addElement('submit', $this->_printButtonName
, $label);
914 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
915 $this->addElement('submit', $this->_pdfButtonName
, $label);
917 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
919 if ($this->_csvSupported
) {
920 $this->addElement('submit', $this->_csvButtonName
, $label);
923 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
924 $this->addElement('select', 'groups', ts('Group'),
925 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
927 $this->assign('group', TRUE);
930 $label = ts('Add these Contacts to Group');
931 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
933 $this->addChartOptions();
934 $this->addButtons(array(
937 'name' => ts('Preview Report'),
944 function buildQuickForm() {
951 $this->addGroupBys();
953 $this->addOrderBys();
955 $this->buildInstanceAndButtons();
957 //add form rule for report
958 if (is_callable(array(
959 $this, 'formRule'))) {
960 $this->addFormRule(array(get_class($this), 'formRule'), $this);
964 // a formrule function to ensure that fields selected in group_by
965 // (if any) should only be the ones present in display/select fields criteria;
966 // note: works if and only if any custom field selected in group_by.
967 function customDataFormRule($fields, $ignoreFields = array( )) {
969 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
970 foreach ($this->_columns
as $tableName => $table) {
971 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
972 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
973 if (array_key_exists($fieldName, $fields['group_bys']) &&
974 !array_key_exists($fieldName, $fields['fields'])
976 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
978 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
979 foreach ($fields['fields'] as $fld => $val) {
980 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
981 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
992 // Note: $fieldName param allows inheriting class to build operationPairs
993 // specific to a field.
994 static function getOperationPair($type = "string", $fieldName = NULL) {
995 // FIXME: At some point we should move these key-val pairs
996 // to option_group and option_value table.
999 case CRM_Report_FORM
::OP_INT
:
1000 case CRM_Report_FORM
::OP_FLOAT
:
1001 return array('lte' => ts('Is less than or equal to'),
1002 'gte' => ts('Is greater than or equal to'),
1003 'bw' => ts('Is between'),
1004 'eq' => ts('Is equal to'),
1005 'lt' => ts('Is less than'),
1006 'gt' => ts('Is greater than'),
1007 'neq' => ts('Is not equal to'),
1008 'nbw' => ts('Is not between'),
1009 'nll' => ts('Is empty (Null)'),
1010 'nnll' => ts('Is not empty (Null)'),
1014 case CRM_Report_FORM
::OP_SELECT
:
1015 return array('eq' => ts('Is equal to'));
1017 case CRM_Report_FORM
::OP_MONTH
:
1018 case CRM_Report_FORM
::OP_MULTISELECT
:
1019 return array('in' => ts('Is one of'),
1020 'notin' => ts('Is not one of'),
1024 case CRM_Report_FORM
::OP_DATE
:
1025 return array('nll' => ts('Is empty (Null)'),
1026 'nnll' => ts('Is not empty (Null)'),
1030 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1031 // use this operator for the values, concatenated with separator. For e.g if
1032 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1033 return array('mhas' => ts('Is one of'));
1037 return array('has' => ts('Contains'),
1038 'sw' => ts('Starts with'),
1039 'ew' => ts('Ends with'),
1040 'nhas' => ts('Does not contain'),
1041 'eq' => ts('Is equal to'),
1042 'neq' => ts('Is not equal to'),
1043 'nll' => ts('Is empty (Null)'),
1044 'nnll' => ts('Is not empty (Null)'),
1049 function buildTagFilter() {
1050 $contactTags = CRM_Core_BAO_Tag
::getTags();
1051 if (!empty($contactTags)) {
1052 $this->_columns
['civicrm_tag'] = array(
1053 'dao' => 'CRM_Core_DAO_Tag',
1059 'title' => ts('Tag'),
1061 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1062 'options' => $contactTags,
1070 * Adds group filters to _columns (called from _Constuct
1072 function buildGroupFilter() {
1073 $this->_columns
['civicrm_group']['filters'] = array(
1076 'name' => 'group_id',
1077 'title' => ts('Group'),
1078 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1080 'options' => CRM_Core_PseudoConstant
::group(),
1083 if (empty($this->_columns
['civicrm_group']['dao'])) {
1084 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1086 if (empty($this->_columns
['civicrm_group']['alias'])) {
1087 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1091 static function getSQLOperator($operator = "like") {
1092 switch ($operator) {
1125 return 'IS NOT NULL';
1133 function whereClause(&$field, $op,
1137 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1143 if (($min !== NULL && strlen($min) > 0) ||
1144 ($max !== NULL && strlen($max) > 0)
1146 $min = CRM_Utils_Type
::escape($min, $type);
1147 $max = CRM_Utils_Type
::escape($max, $type);
1151 $clauses[] = "( {$field['dbAlias']} >= $min )";
1154 $clauses[] = "( {$field['dbAlias']} < $min )";
1159 $clauses[] = "( {$field['dbAlias']} <= $max )";
1162 $clauses[] = "( {$field['dbAlias']} > $max )";
1166 if (!empty($clauses)) {
1168 $clause = implode(' AND ', $clauses);
1171 $clause = implode(' OR ', $clauses);
1179 if ($value !== NULL && strlen($value) > 0) {
1180 $value = CRM_Utils_Type
::escape($value, $type);
1181 if (strpos($value, '%') === FALSE) {
1182 $value = "'%{$value}%'";
1185 $value = "'{$value}'";
1187 $sqlOP = self
::getSQLOperator($op);
1188 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1194 if ($value !== NULL && is_array($value) && count($value) > 0) {
1195 $sqlOP = self
::getSQLOperator($op);
1196 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1197 //cycle through selections and esacape values
1198 foreach ($value as $key => $selection) {
1199 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1201 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1204 // for numerical values
1205 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1207 if ($op == 'notin') {
1208 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1211 $clause = "( " . $clause . " )";
1217 // mhas == multiple has
1218 if ($value !== NULL && count($value) > 0) {
1219 $sqlOP = self
::getSQLOperator($op);
1220 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1226 if ($value !== NULL && strlen($value) > 0) {
1227 $value = CRM_Utils_Type
::escape($value, $type);
1228 if (strpos($value, '%') === FALSE) {
1230 $value = "'{$value}%'";
1233 $value = "'%{$value}'";
1237 $value = "'{$value}'";
1239 $sqlOP = self
::getSQLOperator($op);
1240 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1246 $sqlOP = self
::getSQLOperator($op);
1247 $clause = "( {$field['dbAlias']} $sqlOP )";
1251 if ($value !== NULL && strlen($value) > 0) {
1252 if (isset($field['clause'])) {
1253 // FIXME: we not doing escape here. Better solution is to use two
1254 // different types - data-type and filter-type
1255 eval("\$clause = \"{$field['clause']}\";");
1258 $value = CRM_Utils_Type
::escape($value, $type);
1259 $sqlOP = self
::getSQLOperator($op);
1260 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1261 $value = "'{$value}'";
1263 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1269 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1270 $clause = $this->whereGroupClause($field, $value, $op);
1272 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1273 // not using left join in query because if any contact
1274 // belongs to more than one tag, results duplicate
1276 $clause = $this->whereTagClause($field, $value, $op);
1282 function dateClause($fieldName,
1283 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1286 if (in_array($relative, array_keys(self
::getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1287 $sqlOP = self
::getSQLOperator($relative);
1288 return "( {$fieldName} {$sqlOP} )";
1291 list($from, $to) = self
::getFromTo($relative, $from, $to, $fromTime, $toTime);
1294 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1295 $clauses[] = "( {$fieldName} >= $from )";
1299 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1300 $clauses[] = "( {$fieldName} <= {$to} )";
1303 if (!empty($clauses)) {
1304 return implode(' AND ', $clauses);
1310 static function dateDisplay($relative, $from, $to) {
1311 list($from, $to) = self
::getFromTo($relative, $from, $to);
1314 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1317 $clauses[] = 'Past';
1321 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1324 $clauses[] = 'Today';
1327 if (!empty($clauses)) {
1328 return implode(' - ', $clauses);
1334 static function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1335 if (empty($totime)) {
1338 //FIX ME not working for relative
1340 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1341 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1342 $from = substr($dateRange['from'], 0, 8);
1343 //Take only Date Part, Sometime Time part is also present in 'to'
1344 $to = substr($dateRange['to'], 0, 8);
1346 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1347 $to = CRM_Utils_Date
::processDate($to, $totime);
1348 return array($from, $to);
1351 function alterDisplay(&$rows) {
1352 // custom code to alter rows
1355 function alterCustomDataDisplay(&$rows) {
1356 // custom code to alter rows having custom values
1357 if (empty($this->_customGroupExtends
)) {
1361 $customFieldIds = array();
1362 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1363 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1364 $customFieldIds[$fieldAlias] = $fieldId;
1367 if (empty($customFieldIds)) {
1371 $customFields = $fieldValueMap = array();
1372 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1374 // skip for type date and ContactReference since date format is already handled
1376 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1377 FROM civicrm_custom_field cf
1378 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1379 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1380 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1381 cg.is_active = 1 AND
1382 cf.is_active = 1 AND
1383 cf.is_searchable = 1 AND
1384 cf.data_type NOT IN ('ContactReference', 'Date') AND
1385 cf.id IN (" . implode(",", $customFieldIds) . ")";
1387 $dao = CRM_Core_DAO
::executeQuery($query);
1388 while ($dao->fetch()) {
1389 foreach ($customFieldCols as $key) {
1390 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1392 if ($dao->option_group_id
) {
1393 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1398 $entryFound = FALSE;
1399 foreach ($rows as $rowNum => $row) {
1400 foreach ($row as $tableCol => $val) {
1401 if (array_key_exists($tableCol, $customFields)) {
1402 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1407 // skip looking further in rows, if first row itself doesn't
1408 // have the column we need
1415 function formatCustomValues($value, $customField, $fieldValueMap) {
1416 if (CRM_Utils_System
::isNull($value)) {
1420 $htmlType = $customField['html_type'];
1422 switch ($customField['data_type']) {
1424 if ($value == '1') {
1425 $retValue = ts('Yes');
1428 $retValue = ts('No');
1433 $retValue = CRM_Utils_System
::formatWikiURL($value);
1445 if ($htmlType == 'Text') {
1446 $retValue = (float)$value;
1450 if ($htmlType == 'Text') {
1460 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1465 if (in_array($htmlType, array(
1466 'Text', 'TextArea'))) {
1470 case 'StateProvince':
1473 switch ($htmlType) {
1474 case 'Multi-Select Country':
1475 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1476 $customData = array();
1477 foreach ($value as $val) {
1479 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1482 $retValue = implode(', ', $customData);
1485 case 'Select Country':
1486 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1489 case 'Select State/Province':
1490 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1493 case 'Multi-Select State/Province':
1494 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1495 $customData = array();
1496 foreach ($value as $val) {
1498 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1501 $retValue = implode(', ', $customData);
1506 case 'Autocomplete-Select':
1507 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1511 case 'AdvMulti-Select':
1512 case 'Multi-Select':
1513 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1514 $customData = array();
1515 foreach ($value as $val) {
1517 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1520 $retValue = implode(', ', $customData);
1535 function removeDuplicates(&$rows) {
1536 if (empty($this->_noRepeats
)) {
1539 $checkList = array();
1541 foreach ($rows as $key => $list) {
1542 foreach ($list as $colName => $colVal) {
1543 if (array_key_exists($colName, $checkList) &&
1544 $checkList[$colName] == $colVal) {
1545 $rows[$key][$colName] = "";
1547 if (in_array($colName, $this->_noRepeats
)) {
1548 $checkList[$colName] = $colVal;
1554 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1555 foreach ($row as $colName => $colVal) {
1556 if (in_array($colName, $fields)) {
1557 $row[$colName] = $row[$colName];
1559 elseif (isset($this->_columnHeaders
[$colName])) {
1561 $row[$colName] = "Subtotal";
1565 unset($row[$colName]);
1571 function grandTotal(&$rows) {
1572 if (!$this->_rollup ||
($this->_rollup
== '') ||
1573 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1577 $lastRow = array_pop($rows);
1579 $this->_grandFlag
= FALSE;
1580 foreach ($this->_columnHeaders
as $fld => $val) {
1581 if (!in_array($fld, $this->_statFields
)) {
1582 if (!$this->_grandFlag
) {
1583 $lastRow[$fld] = "Grand Total";
1584 $this->_grandFlag
= TRUE;
1587 $lastRow[$fld] = "";
1592 $this->assign('grandStat', $lastRow);
1596 function formatDisplay(&$rows, $pager = TRUE) {
1597 // set pager based on if any limit was applied in the query.
1602 // allow building charts if any
1603 if (!empty($this->_params
['charts']) && !empty($rows)) {
1604 $this->buildChart($rows);
1605 $this->assign('chartEnabled', TRUE);
1606 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1607 $this->assign('chartId', $this->_chartId
);
1610 // unset columns not to be displayed.
1611 foreach ($this->_columnHeaders
as $key => $value) {
1612 if (is_array($value) && isset($value['no_display'])) {
1613 unset($this->_columnHeaders
[$key]);
1617 // unset columns not to be displayed.
1618 if (!empty($rows)) {
1619 foreach ($this->_noDisplay
as $noDisplayField) {
1620 foreach ($rows as $rowNum => $row) {
1621 unset($this->_columnHeaders
[$noDisplayField]);
1626 // build array of section totals
1627 $this->sectionTotals();
1629 // process grand-total row
1630 $this->grandTotal($rows);
1632 // use this method for formatting rows for display purpose.
1633 $this->alterDisplay($rows);
1634 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1636 // use this method for formatting custom rows for display purpose.
1637 $this->alterCustomDataDisplay($rows);
1640 function buildChart(&$rows) {
1641 // override this method for building charts.
1644 // select() method below has been added recently (v3.3), and many of the report templates might
1645 // still be having their own select() method. We should fix them as and when encountered and move
1646 // towards generalizing the select() method below.
1650 foreach ($this->_columns
as $tableName => $table) {
1651 if (array_key_exists('fields', $table)) {
1652 foreach ($table['fields'] as $fieldName => $field) {
1653 if ($tableName == 'civicrm_address') {
1654 $this->_addressField
= TRUE;
1656 if ($tableName == 'civicrm_email') {
1657 $this->_emailField
= TRUE;
1659 if ($tableName == 'civicrm_phone') {
1660 $this->_phoneField
= TRUE;
1663 if (CRM_Utils_Array
::value('required', $field) ||
1664 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1667 // 1. In many cases we want select clause to be built in slightly different way
1668 // for a particular field of a particular type.
1669 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1671 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1672 if ($selectClause) {
1673 $select[] = $selectClause;
1677 // include statistics columns only if set
1678 if (CRM_Utils_Array
::value('statistics', $field)) {
1679 foreach ($field['statistics'] as $stat => $label) {
1680 $alias = "{$tableName}_{$fieldName}_{$stat}";
1681 switch (strtolower($stat)) {
1684 $select[] = "$stat({$field['dbAlias']}) as $alias";
1685 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1686 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1687 $this->_statFields
[] = $alias;
1688 $this->_selectAliases
[] = $alias;
1692 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1693 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1694 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1695 $this->_statFields
[] = $alias;
1696 $this->_selectAliases
[] = $alias;
1700 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1701 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1702 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1703 $this->_statFields
[] = $alias;
1704 $this->_selectAliases
[] = $alias;
1710 $alias = "{$tableName}_{$fieldName}";
1711 $select[] = "{$field['dbAlias']} as $alias";
1712 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1713 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1714 $this->_selectAliases
[] = $alias;
1720 // select for group bys
1721 if (array_key_exists('group_bys', $table)) {
1722 foreach ($table['group_bys'] as $fieldName => $field) {
1724 if ($tableName == 'civicrm_address') {
1725 $this->_addressField
= TRUE;
1727 if ($tableName == 'civicrm_email') {
1728 $this->_emailField
= TRUE;
1730 if ($tableName == 'civicrm_phone') {
1731 $this->_phoneField
= TRUE;
1733 // 1. In many cases we want select clause to be built in slightly different way
1734 // for a particular field of a particular type.
1735 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1737 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1738 if ($selectClause) {
1739 $select[] = $selectClause;
1743 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1744 && !empty($this->_params
['group_bys_freq'])) {
1745 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1747 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1748 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1749 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1750 $field['title'] = 'Week';
1754 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1755 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1756 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1757 $field['title'] = 'Year';
1761 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1762 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1763 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1764 $field['title'] = 'Month';
1768 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1769 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1770 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1771 $field['title'] = 'Quarter';
1774 // for graphs and charts -
1775 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1776 $this->_interval
= $field['title'];
1777 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1778 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1779 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1781 // just to make sure these values are transfered to rows.
1782 // since we 'll need them for calculation purpose,
1783 // e.g making subtotals look nicer or graphs
1784 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1785 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1792 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1795 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1800 $whereClauses = $havingClauses = array();
1801 foreach ($this->_columns
as $tableName => $table) {
1802 if (array_key_exists('filters', $table)) {
1803 foreach ($table['filters'] as $fieldName => $field) {
1805 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1806 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1807 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1808 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1809 if (is_array($value) && !empty($value)) {
1810 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1814 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1815 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1816 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1817 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1818 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1819 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1823 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1825 $clause = $this->whereClause($field,
1827 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1828 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1829 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1834 if (!empty($clause)) {
1835 if (CRM_Utils_Array
::value('having', $field)) {
1836 $havingClauses[] = $clause;
1839 $whereClauses[] = $clause;
1846 if (empty($whereClauses)) {
1847 $this->_where
= "WHERE ( 1 ) ";
1848 $this->_having
= "";
1851 $this->_where
= "WHERE " . implode(' AND ', $whereClauses);
1854 if ($this->_aclWhere
) {
1855 $this->_where
.= " AND {$this->_aclWhere} ";
1858 if (!empty($havingClauses)) {
1859 // use this clause to construct group by clause.
1860 $this->_having
= "HAVING " . implode(' AND ', $havingClauses);
1864 function processReportMode() {
1865 $buttonName = $this->controller
->getButtonName();
1867 $output = CRM_Utils_Request
::retrieve(
1870 CRM_Core_DAO
::$_nullObject
1874 CRM_Utils_Request
::retrieve(
1877 CRM_Core_DAO
::$_nullObject
1880 $this->_absoluteUrl
= FALSE;
1882 $this->assign('printOnly', FALSE);
1884 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1885 $this->assign('printOnly', TRUE);
1887 $this->assign('outputMode', 'print');
1888 $this->_outputMode
= 'print';
1889 if ($this->_sendmail
) {
1890 $this->_absoluteUrl
= TRUE;
1893 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1894 $this->assign('printOnly', TRUE);
1896 $this->assign('outputMode', 'pdf');
1897 $this->_outputMode
= 'pdf';
1898 $this->_absoluteUrl
= TRUE;
1900 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
1901 $this->assign('printOnly', TRUE);
1903 $this->assign('outputMode', 'csv');
1904 $this->_outputMode
= 'csv';
1905 $this->_absoluteUrl
= TRUE;
1907 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
1908 $this->assign('outputMode', 'group');
1909 $this->_outputMode
= 'group';
1911 elseif ($output == 'create_report' && $this->_criteriaForm
) {
1912 $this->assign('outputMode', 'create_report');
1913 $this->_outputMode
= 'create_report';
1916 $this->assign('outputMode', 'html');
1917 $this->_outputMode
= 'html';
1920 // Get today's date to include in printed reports
1922 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
1923 $this->assign('reportDate', $reportDate);
1927 function beginPostProcess() {
1928 $this->_params
= $this->controller
->exportValues($this->_name
);
1930 if (empty($this->_params
) &&
1933 $this->_params
= $this->_formValues
;
1936 // hack to fix params when submitted from dashboard, CRM-8532
1937 // fields array is missing because form building etc is skipped
1938 // in dashboard mode for report
1939 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
1940 $this->_params
= $this->_formValues
;
1943 $this->_formValues
= $this->_params
;
1944 if (CRM_Core_Permission
::check('administer Reports') &&
1945 isset($this->_id
) &&
1946 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
1947 $this->_chartButtonName
== $this->controller
->getButtonName()
1950 $this->assign('updateReportButton', TRUE);
1952 $this->processReportMode();
1955 function buildQuery($applyLimit = TRUE) {
1958 $this->customDataFrom();
1963 // order_by columns not selected for display need to be included in SELECT
1964 $unselectedSectionColumns = $this->unselectedSectionColumns();
1965 foreach ($unselectedSectionColumns as $alias => $section) {
1966 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
1969 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
1972 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
1974 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
1978 function groupBy() {
1979 $groupBys = array();
1980 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
1981 is_array($this->_params
['group_bys']) &&
1982 !empty($this->_params
['group_bys'])
1984 foreach ($this->_columns
as $tableName => $table) {
1985 if (array_key_exists('group_bys', $table)) {
1986 foreach ($table['group_bys'] as $fieldName => $field) {
1987 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
1988 $groupBys[] = $field['dbAlias'];
1995 if (!empty($groupBys)) {
1996 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2000 function orderBy() {
2001 $this->_orderBy
= "";
2002 $this->_sections
= array();
2003 $this->storeOrderByArray();
2004 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2005 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2007 $this->assign('sections', $this->_sections
);
2010 * In some cases other functions want to know which fields are selected for ordering by
2011 * Separating this into a separate function allows it to be called separately from constructing
2012 * the order by clause
2014 function storeOrderByArray() {
2015 $orderBys = array();
2017 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2018 is_array($this->_params
['order_bys']) &&
2019 !empty($this->_params
['order_bys'])
2022 // Proces order_bys in user-specified order
2023 foreach ($this->_params
['order_bys'] as $orderBy) {
2024 $orderByField = array();
2025 foreach ($this->_columns
as $tableName => $table) {
2026 if (array_key_exists('order_bys', $table)) {
2027 // For DAO columns defined in $this->_columns
2028 $fields = $table['order_bys'];
2030 elseif (array_key_exists('extends', $table)) {
2031 // For custom fields referenced in $this->_customGroupExtends
2032 $fields = $table['fields'];
2034 if (!empty($fields) && is_array($fields)) {
2035 foreach ($fields as $fieldName => $field) {
2036 if ($fieldName == $orderBy['column']) {
2037 $orderByField = $field;
2038 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2045 if (!empty($orderByField)) {
2046 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2048 // Record any section headers for assignment to the template
2049 if (CRM_Utils_Array
::value('section', $orderBy)) {
2050 $this->_sections
[$orderByField['tplField']] = $orderByField;
2056 $this->_orderByArray
= $orderBys;
2058 $this->assign('sections', $this->_sections
);
2061 function unselectedSectionColumns() {
2062 $selectColumns = array();
2063 foreach ($this->_columns
as $tableName => $table) {
2064 if (array_key_exists('fields', $table)) {
2065 foreach ($table['fields'] as $fieldName => $field) {
2066 if (CRM_Utils_Array
::value('required', $field) ||
2067 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2070 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2075 if (is_array($this->_sections
)) {
2076 return array_diff_key($this->_sections
, $selectColumns);
2083 function buildRows($sql, &$rows) {
2084 $dao = CRM_Core_DAO
::executeQuery($sql);
2085 if (!is_array($rows)) {
2089 // use this method to modify $this->_columnHeaders
2090 $this->modifyColumnHeaders();
2092 $unselectedSectionColumns = $this->unselectedSectionColumns();
2094 while ($dao->fetch()) {
2096 foreach ($this->_columnHeaders
as $key => $value) {
2097 if (property_exists($dao, $key)) {
2098 $row[$key] = $dao->$key;
2102 // section headers not selected for display need to be added to row
2103 foreach ($unselectedSectionColumns as $key => $values) {
2104 if (property_exists($dao, $key)) {
2105 $row[$key] = $dao->$key;
2114 * When "order by" fields are marked as sections, this assigns to the template
2115 * an array of total counts for each section. This data is used by the Smarty
2116 * plugin {sectionTotal}
2118 function sectionTotals() {
2120 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2121 if (empty($this->_selectAliases
)) {
2125 if (!empty($this->_sections
)) {
2126 // build the query with no LIMIT clause
2127 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2128 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2130 // pull section aliases out of $this->_sections
2131 $sectionAliases = array_keys($this->_sections
);
2134 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2135 $ifnulls[] = "ifnull($alias, '') as $alias";
2138 /* Group (un-limited) report by all aliases and get counts. This might
2139 * be done more efficiently when the contents of $sql are known, ie. by
2140 * overriding this method in the report class.
2144 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2146 // initialize array of total counts
2148 $dao = CRM_Core_DAO
::executeQuery($query);
2149 while ($dao->fetch()) {
2151 // let $this->_alterDisplay translate any integer ids to human-readable values.
2152 $rows[0] = $dao->toArray();
2153 $this->alterDisplay($rows);
2156 // add totals for all permutations of section values
2159 $aliasCount = count($sectionAliases);
2160 foreach ($sectionAliases as $alias) {
2161 $values[] = $row[$alias];
2162 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2163 if ($i == $aliasCount) {
2164 // the last alias is the lowest-level section header; use count as-is
2165 $totals[$key] = $dao->ct
;
2168 // other aliases are higher level; roll count into their total
2169 $totals[$key] +
= $dao->ct
;
2173 $this->assign('sectionTotals', $totals);
2177 function modifyColumnHeaders() {
2178 // use this method to modify $this->_columnHeaders
2181 function doTemplateAssignment(&$rows) {
2182 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2183 $this->assign_by_ref('rows', $rows);
2184 $this->assign('statistics', $this->statistics($rows));
2187 // override this method to build your own statistics
2188 function statistics(&$rows) {
2189 $statistics = array();
2191 $count = count($rows);
2193 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2197 $this->countStat($statistics, $count);
2199 $this->groupByStat($statistics);
2201 $this->filterStat($statistics);
2206 function countStat(&$statistics, $count) {
2207 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2211 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2212 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2213 'value' => $this->_rowsFound
,
2218 function groupByStat(&$statistics) {
2219 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2220 is_array($this->_params
['group_bys']) &&
2221 !empty($this->_params
['group_bys'])
2223 foreach ($this->_columns
as $tableName => $table) {
2224 if (array_key_exists('group_bys', $table)) {
2225 foreach ($table['group_bys'] as $fieldName => $field) {
2226 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2227 $combinations[] = $field['title'];
2232 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2233 'value' => implode(' & ', $combinations),
2238 function filterStat(&$statistics) {
2239 foreach ($this->_columns
as $tableName => $table) {
2240 if (array_key_exists('filters', $table)) {
2241 foreach ($table['filters'] as $fieldName => $field) {
2242 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2245 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2246 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2247 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2248 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2249 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2251 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2252 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2254 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2255 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2258 $statistics['filters'][] = array(
2259 'title' => $field['title'],
2261 "Between %1 and %2",
2269 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2270 array_keys(self
::getOperationPair(CRM_Report_FORM
::OP_DATE
))
2272 $pair = self
::getOperationPair(CRM_Report_FORM
::OP_DATE
);
2273 $statistics['filters'][] = array(
2274 'title' => $field['title'],
2275 'value' => $pair[$rel],
2280 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2283 $pair = self
::getOperationPair(
2284 CRM_Utils_Array
::value('operatorType', $field),
2287 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2288 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2289 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2290 if (in_array($op, array(
2291 'bw', 'nbw')) && ($min ||
$max)) {
2292 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2294 elseif ($op == 'nll' ||
$op == 'nnll') {
2295 $value = $pair[$op];
2297 elseif (is_array($val) && (!empty($val))) {
2298 $options = $field['options'];
2299 foreach ($val as $key => $valIds) {
2300 if (isset($options[$valIds])) {
2301 $val[$key] = $options[$valIds];
2304 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : $pair[$op];
2305 $val = implode(', ', $val);
2306 $value = "{$pair[$op]} " . $val;
2308 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2309 is_array($field['options']) && !empty($field['options'])
2311 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2314 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2318 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2328 function endPostProcess(&$rows = NULL) {
2329 if ($this->_outputMode
== 'print' ||
2330 $this->_outputMode
== 'pdf' ||
2334 $content = $this->compileContent();
2335 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2339 if ($this->_sendmail
) {
2340 $config = CRM_Core_Config
::singleton();
2341 $attachments = array();
2343 if ($this->_outputMode
== 'csv') {
2344 $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'];
2346 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2347 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2348 file_put_contents($csvFullFilename, $csvContent);
2349 $attachments[] = array(
2350 'fullPath' => $csvFullFilename,
2351 'mime_type' => 'text/csv',
2352 'cleanName' => 'CiviReport.csv',
2355 if ($this->_outputMode
== 'pdf') {
2356 // generate PDF content
2357 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2358 file_put_contents($pdfFullFilename,
2359 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2360 TRUE, array('orientation' => 'landscape')
2363 // generate Email Content
2364 $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'];
2366 $attachments[] = array(
2367 'fullPath' => $pdfFullFilename,
2368 'mime_type' => 'application/pdf',
2369 'cleanName' => 'CiviReport.pdf',
2373 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2374 $this->_outputMode
, $attachments
2376 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2379 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2382 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2384 elseif ($this->_outputMode
== 'print') {
2388 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2389 $config = CRM_Core_Config
::singleton();
2390 //get chart image name
2391 $chartImg = $this->_chartId
. '.png';
2392 //get image url path
2393 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2394 $uploadUrl .= $chartImg;
2395 //get image doc path to overwrite
2396 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2398 $chart = imagecreatefrompng($uploadUrl);
2399 //convert it into formattd png
2400 header('Content-type: image/png');
2401 //overwrite with same image
2402 imagepng($chart, $uploadImg);
2404 imagedestroy($chart);
2406 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2408 CRM_Utils_System
::civiExit();
2410 elseif ($this->_outputMode
== 'csv') {
2411 CRM_Report_Utils_Report
::export2csv($this, $rows);
2413 elseif ($this->_outputMode
== 'group') {
2414 $group = $this->_params
['groups'];
2415 $this->add2group($group);
2417 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2418 CRM_Report_Form_Instance
::postProcess($this);
2420 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2421 $this->_outputMode
== 'create_report' ) {
2422 $this->_createNew
= TRUE;
2423 CRM_Report_Form_Instance
::postProcess($this);
2428 * Get Template file name - use default form template if a specific one has not been set up for this report
2431 function getTemplateFileName(){
2432 $defaultTpl = parent
::getTemplateFileName();
2433 $template = CRM_Core_Smarty
::singleton();
2434 if (!$template->template_exists($defaultTpl)) {
2435 $defaultTpl = 'CRM/Report/Form.tpl';
2441 * Compile the report content
2443 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2445 function compileContent(){
2446 $templateFile = $this->getTemplateFileName();
2447 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2451 function postProcess() {
2452 // get ready with post process params
2453 $this->beginPostProcess();
2456 $sql = $this->buildQuery();
2458 // build array of result based on column headers. This method also allows
2459 // modifying column headers before using it to build result set i.e $rows.
2461 $this->buildRows($sql, $rows);
2463 // format result set.
2464 $this->formatDisplay($rows);
2466 // assign variables to templates
2467 $this->doTemplateAssignment($rows);
2469 // do print / pdf / instance stuff if needed
2470 $this->endPostProcess($rows);
2473 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2474 // lets do the pager if in html mode
2475 $this->_limit
= NULL;
2476 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2477 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2479 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2481 if (!$pageId && !empty($_POST)) {
2482 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2483 $pageId = max((int)@$_POST['crmPID_B'], 1);
2485 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2486 $pageId = max((int)@$_POST['crmPID'], 1);
2488 unset($_POST['crmPID_B'], $_POST['crmPID']);
2491 $pageId = $pageId ?
$pageId : 1;
2492 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2493 $offset = ($pageId - 1) * $rowCount;
2495 $this->_limit
= " LIMIT $offset, " . $rowCount;
2496 return array($offset, $rowCount);
2500 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2501 if ($this->_limit
&& ($this->_limit
!= '')) {
2502 $sql = "SELECT FOUND_ROWS();";
2503 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2505 'total' => $this->_rowsFound
,
2506 'rowCount' => $rowCount,
2507 'status' => ts('Records') . ' %%StatusMessage%%',
2508 'buttonBottom' => 'PagerBottomButton',
2509 'buttonTop' => 'PagerTopButton',
2510 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2513 $pager = new CRM_Utils_Pager($params);
2514 $this->assign_by_ref('pager', $pager);
2518 function whereGroupClause($field, $value, $op) {
2520 $smartGroupQuery = "";
2522 $group = new CRM_Contact_DAO_Group();
2523 $group->is_active
= 1;
2525 $smartGroups = array();
2526 while ($group->fetch()) {
2527 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2528 $smartGroups[] = $group->id
;
2532 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2534 $smartGroupQuery = '';
2535 if (!empty($smartGroups)) {
2536 $smartGroups = implode(',', $smartGroups);
2537 $smartGroupQuery = " UNION DISTINCT
2538 SELECT DISTINCT smartgroup_contact.contact_id
2539 FROM civicrm_group_contact_cache smartgroup_contact
2540 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2543 $sqlOp = self
::getSQLOperator($op);
2544 if (!is_array($value)) {
2545 $value = array($value);
2547 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2549 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2550 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2551 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2552 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2553 {$smartGroupQuery} ) ";
2556 function whereTagClause($field, $value, $op) {
2557 // not using left join in query because if any contact
2558 // belongs to more than one tag, results duplicate
2560 $sqlOp = self
::getSQLOperator($op);
2561 if (!is_array($value)) {
2562 $value = array($value);
2564 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2566 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2567 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2568 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2569 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2572 function buildACLClause($tableAlias = 'contact_a') {
2573 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2576 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2577 if (empty($this->_customGroupExtends
)) {
2580 if (!is_array($this->_customGroupExtends
)) {
2581 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2583 $customGroupWhere = '';
2584 if (!empty($permCustomGroupIds)) {
2585 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2588 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2589 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2590 FROM civicrm_custom_group cg
2591 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2592 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2594 cg.is_active = 1 AND
2595 cf.is_active = 1 AND
2596 cf.is_searchable = 1
2597 ORDER BY cg.weight, cf.weight";
2598 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2601 while ($customDAO->fetch()) {
2602 if ($customDAO->table_name
!= $curTable) {
2603 $curTable = $customDAO->table_name
;
2604 $curFields = $curFilters = array();
2607 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2608 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2609 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2610 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2613 'fields', 'filters', 'group_bys') as $colKey) {
2614 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2615 $this->_columns
[$curTable][$colKey] = array();
2619 $fieldName = 'custom_' . $customDAO->cf_id
;
2622 // this makes aliasing work in favor
2623 $curFields[$fieldName] = array(
2624 'name' => $customDAO->column_name
,
2625 'title' => $customDAO->label
,
2626 'dataType' => $customDAO->data_type
,
2627 'htmlType' => $customDAO->html_type
,
2630 if ($this->_customGroupFilters
) {
2631 // this makes aliasing work in favor
2632 $curFilters[$fieldName] = array(
2633 'name' => $customDAO->column_name
,
2634 'title' => $customDAO->label
,
2635 'dataType' => $customDAO->data_type
,
2636 'htmlType' => $customDAO->html_type
,
2640 switch ($customDAO->data_type
) {
2643 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2644 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2645 // CRM-6946, show time part for datetime date fields
2646 if ($customDAO->time_format
) {
2647 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2652 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2653 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2657 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2661 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2662 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2666 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2667 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2671 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2672 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2676 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2678 if (!empty($customDAO->option_group_id
)) {
2679 if (in_array($customDAO->html_type
, array(
2680 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2681 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2684 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2686 if ($this->_customGroupFilters
) {
2687 $curFilters[$fieldName]['options'] = array();
2688 $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')));
2689 while ($ogDAO->fetch()) {
2690 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2696 case 'StateProvince':
2697 if (in_array($customDAO->html_type
, array(
2698 'Multi-Select State/Province'))) {
2699 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2702 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2704 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2708 if (in_array($customDAO->html_type
, array(
2709 'Multi-Select Country'))) {
2710 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2713 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2715 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2718 case 'ContactReference':
2719 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2720 $curFilters[$fieldName]['name'] = 'display_name';
2721 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2723 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2724 $curFields[$fieldName]['name'] = 'display_name';
2725 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2729 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2730 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2733 if (!array_key_exists('type', $curFields[$fieldName])) {
2734 $curFields[$fieldName]['type'] = $curFilters[$fieldName]['type'];
2738 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2740 if ($this->_customGroupFilters
) {
2741 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2743 if ($this->_customGroupGroupBy
) {
2744 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2749 function customDataFrom() {
2750 if (empty($this->_customGroupExtends
)) {
2753 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2755 foreach ($this->_columns
as $table => $prop) {
2756 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2757 $extendsTable = $mapper[$prop['extends']];
2759 // check field is in params
2760 if (!$this->isFieldSelected($prop)) {
2765 LEFT JOIN $table {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2766 // handle for ContactReference
2767 if (array_key_exists('fields', $prop)) {
2768 foreach ($prop['fields'] as $fieldName => $field) {
2769 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2770 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2772 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2780 function isFieldSelected($prop) {
2785 if (!empty($this->_params
['fields'])) {
2786 foreach (array_keys($prop['fields']) as $fieldAlias) {
2787 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2788 if ($customFieldId) {
2789 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2793 //might be survey response field.
2794 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2795 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2803 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2804 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2805 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2811 if (!empty($this->_params
['order_bys'])) {
2812 foreach (array_keys($prop['fields']) as $fieldAlias) {
2813 foreach ($this->_params
['order_bys'] as $orderBy) {
2814 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2821 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2822 foreach ($prop['filters'] as $fieldAlias => $val) {
2824 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2825 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2826 (!empty($this->_params
[$fieldAlias . '_' . $attach]) ||
$this->_params
[$fieldAlias . '_' . $attach] == '0')
2831 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2832 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2843 * Check for empty order_by configurations and remove them; also set
2844 * template to hide them.
2846 function preProcessOrderBy(&$formValues) {
2847 // Object to show/hide form elements
2848 $_showHide = &new CRM_Core_ShowHideBlocks('', '');
2850 $_showHide->addShow('optionField_1');
2852 // Cycle through order_by options; skip any empty ones, and hide them as well
2855 if (!empty($formValues['order_bys'])) {
2856 foreach ($formValues['order_bys'] as $order_by) {
2857 if ($order_by['column'] && $order_by['column'] != '-') {
2858 $_showHide->addShow('optionField_' . $n);
2859 $orderBys[$n] = $order_by;
2864 for ($i = $n; $i <= 5; $i++
) {
2866 $_showHide->addHide('optionField_' . $i);
2870 // overwrite order_by options with modified values
2871 if (!empty($orderBys)) {
2872 $formValues['order_bys'] = $orderBys;
2875 $formValues['order_bys'] = array(1 => array('column' => '-'));
2878 // assign show/hide data to template
2879 $_showHide->addToTemplate();
2883 * Does table name have columns in SELECT clause?
2885 * @param string $tableName Name of table (index of $this->_columns array)
2889 function isTableSelected($tableName) {
2890 return in_array($tableName, $this->selectedTables());
2894 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
2895 * (building the array if it's unset)
2897 * @return Array $this->_selectedTables
2899 function selectedTables() {
2900 if (!$this->_selectedTables
) {
2901 $orderByColumns = array();
2902 if (is_array($this->_params
['order_bys'])) {
2903 foreach ($this->_params
['order_bys'] as $orderBy) {
2904 $orderByColumns[] = $orderBy['column'];
2908 foreach ($this->_columns
as $tableName => $table) {
2909 if (array_key_exists('fields', $table)) {
2910 foreach ($table['fields'] as $fieldName => $field) {
2911 if (CRM_Utils_Array
::value('required', $field) ||
2912 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2914 $this->_selectedTables
[] = $tableName;
2919 if (array_key_exists('order_bys', $table)) {
2920 foreach ($table['order_bys'] as $orderByName => $orderBy) {
2921 if (in_array($orderByName, $orderByColumns)) {
2922 $this->_selectedTables
[] = $tableName;
2927 if (array_key_exists('filters', $table)) {
2928 foreach ($table['filters'] as $filterName => $filter) {
2929 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
2930 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
2931 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
2933 $this->_selectedTables
[] = $tableName;
2940 return $this->_selectedTables
;
2944 * function for adding address fields to construct function in reports
2945 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
2946 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
2947 * @return array address fields for construct clause
2949 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
2950 'country_id' => TRUE)) {
2951 $addressFields = array(
2952 'civicrm_address' =>
2954 'dao' => 'CRM_Core_DAO_Address',
2958 array('title' => ts('Address Name'),
2959 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
2962 array('title' => ts('Street Address'),
2963 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
2965 'supplemental_address_1' =>
2966 array('title' => ts('Supplementary Address Field 1'),
2967 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
2969 'supplemental_address_2' =>
2970 array('title' => ts('Supplementary Address Field 2'),
2971 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
2975 'name' => 'street_number',
2976 'title' => ts('Street Number'),
2978 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
2982 'name' => 'street_name',
2983 'title' => ts('Street Name'),
2985 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
2989 'name' => 'street_unit',
2990 'title' => ts('Street Unit'),
2992 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
2995 array('title' => ts('City'),
2996 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
2999 array('title' => ts('Postal Code'),
3000 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3003 array('title' => ts('County'),
3004 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3006 'state_province_id' =>
3007 array('title' => ts('State/Province'),
3008 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3011 array('title' => ts('Country'),
3012 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3015 'grouping' => 'location-fields',
3020 $addressFields['civicrm_address']['filters'] = array(
3021 'street_number' => array('title' => ts('Street Number'),
3023 'name' => 'street_number',
3025 'street_name' => array('title' => ts('Street Name'),
3026 'name' => 'street_name',
3027 'operator' => 'like',
3029 'postal_code' => array('title' => ts('Postal Code'),
3031 'name' => 'postal_code',
3033 'city' => array('title' => ts('City'),
3034 'operator' => 'like',
3037 'county_id' => array(
3038 'name' => 'county_id',
3039 'title' => ts('County'),
3040 'type' => CRM_Utils_Type
::T_INT
,
3042 CRM_Report_Form
::OP_MULTISELECT
,
3044 CRM_Core_PseudoConstant
::county(),
3046 'state_province_id' => array(
3047 'name' => 'state_province_id',
3048 'title' => ts('State/Province'),
3049 'type' => CRM_Utils_Type
::T_INT
,
3051 CRM_Report_Form
::OP_MULTISELECT
,
3053 CRM_Core_PseudoConstant
::stateProvince(),
3055 'country_id' => array(
3056 'name' => 'country_id',
3057 'title' => ts('Country'),
3058 'type' => CRM_Utils_Type
::T_INT
,
3060 CRM_Report_Form
::OP_MULTISELECT
,
3062 CRM_Core_PseudoConstant
::country(),
3068 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3069 'street_number' => array('title' => 'Odd / Even Street Number'),
3070 'street_address' => NULL,
3072 'postal_code' => NULL,
3077 $addressFields['civicrm_address']['group_bys'] = array(
3078 'street_address' => NULL,
3080 'postal_code' => NULL,
3081 'state_province_id' =>
3082 array('title' => ts('State/Province'),
3085 array('title' => ts('Country'),
3088 array('title' => ts('County'),
3092 return $addressFields;
3096 * Do AlterDisplay processing on Address Fields
3098 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3099 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3100 $entryFound = FALSE;
3102 if (array_key_exists('civicrm_address_country_id', $row)) {
3103 if ($value = $row['civicrm_address_country_id']) {
3104 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3105 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3106 "reset=1&force=1&{$criteriaQueryParams}&" .
3107 "country_id_op=in&country_id_value={$value}",
3108 $this->_absoluteUrl
, $this->_id
3110 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3111 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3118 if (array_key_exists('civicrm_address_county_id', $row)) {
3119 if ($value = $row['civicrm_address_county_id']) {
3120 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3121 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3122 "reset=1&force=1&{$criteriaQueryParams}&" .
3123 "county_id_op=in&county_id_value={$value}",
3124 $this->_absoluteUrl
, $this->_id
3126 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3127 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3133 // handle state province
3134 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3135 if ($value = $row['civicrm_address_state_province_id']) {
3136 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3138 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3139 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3140 $this->_absoluteUrl
, $this->_id
3142 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3143 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3154 * Adjusts dates passed in to YEAR() for fiscal year.
3156 function fiscalYearOffset($fieldName) {
3157 $config = CRM_Core_Config
::singleton();
3158 $fy = $config->fiscalYearStart
;
3159 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3160 return "YEAR( $fieldName )";
3162 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3166 * Add Address into From Table if required
3168 function addAddressFromClause() {
3169 // include address field if address column is to be included
3170 if ((isset($this->_addressField
) &&
3171 $this->_addressField
3173 $this->isTableSelected('civicrm_address')
3176 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3177 ON ({$this->_aliases['civicrm_contact']}.id =
3178 {$this->_aliases['civicrm_address']}.contact_id) AND
3179 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3183 function add2group($groupID) {
3184 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3185 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3186 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3188 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3189 $dao = CRM_Core_DAO
::executeQuery($sql);
3191 $contact_ids = array();
3192 // Add resulting contacts to group
3193 while ($dao->fetch()) {
3194 if ($dao->addtogroup_contact_id
) {
3195 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3199 if ( !empty($contact_ids) ) {
3200 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3201 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3204 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));