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 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( );");
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 // @ 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
713 $operations = $this->getOperationPair(
714 CRM_Utils_Array
::value('operatorType', $field),
717 $filters[$table][$fieldName] = $field;
719 switch (CRM_Utils_Array
::value('operatorType', $field)) {
720 case CRM_Report_Form
::OP_MONTH
:
721 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
722 // If there's no option list for this filter, define one.
723 $field['options'] = array(
732 9 => ts('September'),
734 11 => ts('November'),
735 12 => ts('December'),
737 // Add this option list to this column _columns. This is
738 // required so that filter statistics show properly.
739 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
741 case CRM_Report_FORM
::OP_MULTISELECT
:
742 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
743 // assume a multi-select field
744 if (!empty($field['options'])) {
745 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
746 if (count($operations) <= 1) {
749 $select = $this->addElement('select', "{$fieldName}_value", NULL,
750 $field['options'], array(
752 'style' => 'min-width:250px',
755 $select->setMultiple(TRUE);
759 case CRM_Report_FORM
::OP_SELECT
:
760 // assume a select field
761 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
762 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
765 case CRM_Report_FORM
::OP_DATE
:
766 // build datetime fields
767 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count);
771 case CRM_Report_FORM
::OP_DATETIME
:
772 // build datetime fields
773 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, TRUE, 'searchDate', true);
777 case CRM_Report_FORM
::OP_INT
:
778 case CRM_Report_FORM
::OP_FLOAT
:
779 // and a min value input box
780 $this->add('text', "{$fieldName}_min", ts('Min'));
781 // and a max value input box
782 $this->add('text', "{$fieldName}_max", ts('Max'));
784 // default type is string
785 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
786 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
788 // we need text box for value input
789 $this->add('text', "{$fieldName}_value", NULL);
794 $this->assign('filters', $filters);
797 function addOptions() {
798 if (!empty($this->_options
)) {
799 // FIXME: For now lets build all elements as checkboxes.
800 // Once we clear with the format we can build elements based on type
803 foreach ($this->_options
as $fieldName => $field) {
804 if ($field['type'] == 'select') {
805 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
807 else if ($field['type'] == 'checkbox') {
808 $options[$field['title']] = $fieldName;
809 $this->addCheckBox($fieldName, NULL,
811 NULL, NULL, NULL, $this->_fourColumnAttribute
816 $this->assign('otherOptions', $this->_options
);
819 function addChartOptions() {
820 if (!empty($this->_charts
)) {
821 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
822 $this->assign('charts', $this->_charts
);
823 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
827 function addGroupBys() {
828 $options = $freqElements = array();
830 foreach ($this->_columns
as $tableName => $table) {
831 if (array_key_exists('group_bys', $table)) {
832 foreach ($table['group_bys'] as $fieldName => $field) {
833 if (!empty($field)) {
834 $options[$field['title']] = $fieldName;
835 if (CRM_Utils_Array
::value('frequency', $field)) {
836 $freqElements[$field['title']] = $fieldName;
842 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
843 NULL, NULL, NULL, $this->_fourColumnAttribute
845 $this->assign('groupByElements', $options);
847 foreach ($freqElements as $name) {
848 $this->addElement('select', "group_bys_freq[$name]",
849 ts('Frequency'), $this->_groupByDateFreq
854 function addOrderBys() {
856 foreach ($this->_columns
as $tableName => $table) {
858 // Report developer may define any column to order by; include these as order-by options
859 if (array_key_exists('order_bys', $table)) {
860 foreach ($table['order_bys'] as $fieldName => $field) {
861 if (!empty($field)) {
862 $options[$fieldName] = $field['title'];
867 /* Add searchable custom fields as order-by options, if so requested
868 * (These are already indexed, so allowing to order on them is cheap.)
872 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
873 foreach ($table['fields'] as $fieldName => $field) {
874 if (!array_key_exists('no_display', $field)) {
875 $options[$fieldName] = $field['title'];
883 $this->assign('orderByOptions', $options);
885 if (!empty($options)) {
887 '-' => ' - none - ') +
$options;
888 for ($i = 1; $i <= 5; $i++
) {
889 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
890 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
891 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
896 function buildInstanceAndButtons() {
897 CRM_Report_Form_Instance
::buildForm($this);
899 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
901 $this->addElement('submit', $this->_instanceButtonName
, $label);
902 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
903 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
906 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
908 if ($this->_instanceForm
) {
909 $this->assign('instanceForm', TRUE);
912 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
913 $this->addElement('submit', $this->_printButtonName
, $label);
915 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
916 $this->addElement('submit', $this->_pdfButtonName
, $label);
918 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
920 if ($this->_csvSupported
) {
921 $this->addElement('submit', $this->_csvButtonName
, $label);
924 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
925 $this->addElement('select', 'groups', ts('Group'),
926 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
928 $this->assign('group', TRUE);
931 $label = ts('Add these Contacts to Group');
932 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
934 $this->addChartOptions();
935 $this->addButtons(array(
938 'name' => ts('Preview Report'),
945 function buildQuickForm() {
952 $this->addGroupBys();
954 $this->addOrderBys();
956 $this->buildInstanceAndButtons();
958 //add form rule for report
959 if (is_callable(array(
960 $this, 'formRule'))) {
961 $this->addFormRule(array(get_class($this), 'formRule'), $this);
965 // a formrule function to ensure that fields selected in group_by
966 // (if any) should only be the ones present in display/select fields criteria;
967 // note: works if and only if any custom field selected in group_by.
968 function customDataFormRule($fields, $ignoreFields = array( )) {
970 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
971 foreach ($this->_columns
as $tableName => $table) {
972 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
973 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
974 if (array_key_exists($fieldName, $fields['group_bys']) &&
975 !array_key_exists($fieldName, $fields['fields'])
977 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
979 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
980 foreach ($fields['fields'] as $fld => $val) {
981 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
982 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
993 // Note: $fieldName param allows inheriting class to build operationPairs
994 // specific to a field.
995 function getOperationPair($type = "string", $fieldName = NULL) {
996 // FIXME: At some point we should move these key-val pairs
997 // to option_group and option_value table.
1000 case CRM_Report_FORM
::OP_INT
:
1001 case CRM_Report_FORM
::OP_FLOAT
:
1002 return array('lte' => ts('Is less than or equal to'),
1003 'gte' => ts('Is greater than or equal to'),
1004 'bw' => ts('Is between'),
1005 'eq' => ts('Is equal to'),
1006 'lt' => ts('Is less than'),
1007 'gt' => ts('Is greater than'),
1008 'neq' => ts('Is not equal to'),
1009 'nbw' => ts('Is not between'),
1010 'nll' => ts('Is empty (Null)'),
1011 'nnll' => ts('Is not empty (Null)'),
1015 case CRM_Report_FORM
::OP_SELECT
:
1016 return array('eq' => ts('Is equal to'));
1018 case CRM_Report_FORM
::OP_MONTH
:
1019 case CRM_Report_FORM
::OP_MULTISELECT
:
1020 return array('in' => ts('Is one of'),
1021 'notin' => ts('Is not one of'),
1025 case CRM_Report_FORM
::OP_DATE
:
1026 return array('nll' => ts('Is empty (Null)'),
1027 'nnll' => ts('Is not empty (Null)'),
1031 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1032 // use this operator for the values, concatenated with separator. For e.g if
1033 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1034 return array('mhas' => ts('Is one of'));
1038 return array('has' => ts('Contains'),
1039 'sw' => ts('Starts with'),
1040 'ew' => ts('Ends with'),
1041 'nhas' => ts('Does not contain'),
1042 'eq' => ts('Is equal to'),
1043 'neq' => ts('Is not equal to'),
1044 'nll' => ts('Is empty (Null)'),
1045 'nnll' => ts('Is not empty (Null)'),
1050 function buildTagFilter() {
1051 $contactTags = CRM_Core_BAO_Tag
::getTags();
1052 if (!empty($contactTags)) {
1053 $this->_columns
['civicrm_tag'] = array(
1054 'dao' => 'CRM_Core_DAO_Tag',
1060 'title' => ts('Tag'),
1062 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1063 'options' => $contactTags,
1071 * Adds group filters to _columns (called from _Constuct
1073 function buildGroupFilter() {
1074 $this->_columns
['civicrm_group']['filters'] = array(
1077 'name' => 'group_id',
1078 'title' => ts('Group'),
1079 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1081 'options' => CRM_Core_PseudoConstant
::group(),
1084 if (empty($this->_columns
['civicrm_group']['dao'])) {
1085 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1087 if (empty($this->_columns
['civicrm_group']['alias'])) {
1088 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1092 function getSQLOperator($operator = "like") {
1093 switch ($operator) {
1126 return 'IS NOT NULL';
1134 function whereClause(&$field, $op,
1138 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1144 if (($min !== NULL && strlen($min) > 0) ||
1145 ($max !== NULL && strlen($max) > 0)
1147 $min = CRM_Utils_Type
::escape($min, $type);
1148 $max = CRM_Utils_Type
::escape($max, $type);
1152 $clauses[] = "( {$field['dbAlias']} >= $min )";
1155 $clauses[] = "( {$field['dbAlias']} < $min )";
1160 $clauses[] = "( {$field['dbAlias']} <= $max )";
1163 $clauses[] = "( {$field['dbAlias']} > $max )";
1167 if (!empty($clauses)) {
1169 $clause = implode(' AND ', $clauses);
1172 $clause = implode(' OR ', $clauses);
1180 if ($value !== NULL && strlen($value) > 0) {
1181 $value = CRM_Utils_Type
::escape($value, $type);
1182 if (strpos($value, '%') === FALSE) {
1183 $value = "'%{$value}%'";
1186 $value = "'{$value}'";
1188 $sqlOP = $this->getSQLOperator($op);
1189 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1195 if ($value !== NULL && is_array($value) && count($value) > 0) {
1196 $sqlOP = $this->getSQLOperator($op);
1197 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1198 //cycle through selections and esacape values
1199 foreach ($value as $key => $selection) {
1200 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1202 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1205 // for numerical values
1206 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1208 if ($op == 'notin') {
1209 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1212 $clause = "( " . $clause . " )";
1218 // mhas == multiple has
1219 if ($value !== NULL && count($value) > 0) {
1220 $sqlOP = $this->getSQLOperator($op);
1221 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1227 if ($value !== NULL && strlen($value) > 0) {
1228 $value = CRM_Utils_Type
::escape($value, $type);
1229 if (strpos($value, '%') === FALSE) {
1231 $value = "'{$value}%'";
1234 $value = "'%{$value}'";
1238 $value = "'{$value}'";
1240 $sqlOP = $this->getSQLOperator($op);
1241 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1247 $sqlOP = $this->getSQLOperator($op);
1248 $clause = "( {$field['dbAlias']} $sqlOP )";
1252 if ($value !== NULL && strlen($value) > 0) {
1253 if (isset($field['clause'])) {
1254 // FIXME: we not doing escape here. Better solution is to use two
1255 // different types - data-type and filter-type
1256 eval("\$clause = \"{$field['clause']}\";");
1259 $value = CRM_Utils_Type
::escape($value, $type);
1260 $sqlOP = $this->getSQLOperator($op);
1261 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1262 $value = "'{$value}'";
1264 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1270 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1271 $clause = $this->whereGroupClause($field, $value, $op);
1273 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1274 // not using left join in query because if any contact
1275 // belongs to more than one tag, results duplicate
1277 $clause = $this->whereTagClause($field, $value, $op);
1283 function dateClause($fieldName,
1284 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1287 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1288 $sqlOP = $this->getSQLOperator($relative);
1289 return "( {$fieldName} {$sqlOP} )";
1292 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1295 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1296 $clauses[] = "( {$fieldName} >= $from )";
1300 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1301 $clauses[] = "( {$fieldName} <= {$to} )";
1304 if (!empty($clauses)) {
1305 return implode(' AND ', $clauses);
1311 * @todo - could not find any instances where this is called
1312 * @param unknown_type $relative
1313 * @param String $from
1314 * @param String_type $to
1315 * @return string|NULL
1317 function dateDisplay($relative, $from, $to) {
1318 list($from, $to) = $this->getFromTo($relative, $from, $to);
1321 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1324 $clauses[] = 'Past';
1328 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1331 $clauses[] = 'Today';
1334 if (!empty($clauses)) {
1335 return implode(' - ', $clauses);
1341 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1342 if (empty($totime)) {
1345 //FIX ME not working for relative
1347 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1348 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1349 $from = substr($dateRange['from'], 0, 8);
1350 //Take only Date Part, Sometime Time part is also present in 'to'
1351 $to = substr($dateRange['to'], 0, 8);
1353 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1354 $to = CRM_Utils_Date
::processDate($to, $totime);
1355 return array($from, $to);
1358 function alterDisplay(&$rows) {
1359 // custom code to alter rows
1362 function alterCustomDataDisplay(&$rows) {
1363 // custom code to alter rows having custom values
1364 if (empty($this->_customGroupExtends
)) {
1368 $customFieldIds = array();
1369 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1370 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1371 $customFieldIds[$fieldAlias] = $fieldId;
1374 if (empty($customFieldIds)) {
1378 $customFields = $fieldValueMap = array();
1379 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1381 // skip for type date and ContactReference since date format is already handled
1383 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1384 FROM civicrm_custom_field cf
1385 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1386 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1387 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1388 cg.is_active = 1 AND
1389 cf.is_active = 1 AND
1390 cf.is_searchable = 1 AND
1391 cf.data_type NOT IN ('ContactReference', 'Date') AND
1392 cf.id IN (" . implode(",", $customFieldIds) . ")";
1394 $dao = CRM_Core_DAO
::executeQuery($query);
1395 while ($dao->fetch()) {
1396 foreach ($customFieldCols as $key) {
1397 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1399 if ($dao->option_group_id
) {
1400 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1405 $entryFound = FALSE;
1406 foreach ($rows as $rowNum => $row) {
1407 foreach ($row as $tableCol => $val) {
1408 if (array_key_exists($tableCol, $customFields)) {
1409 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1414 // skip looking further in rows, if first row itself doesn't
1415 // have the column we need
1422 function formatCustomValues($value, $customField, $fieldValueMap) {
1423 if (CRM_Utils_System
::isNull($value)) {
1427 $htmlType = $customField['html_type'];
1429 switch ($customField['data_type']) {
1431 if ($value == '1') {
1432 $retValue = ts('Yes');
1435 $retValue = ts('No');
1440 $retValue = CRM_Utils_System
::formatWikiURL($value);
1452 if ($htmlType == 'Text') {
1453 $retValue = (float)$value;
1457 if ($htmlType == 'Text') {
1467 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1472 if (in_array($htmlType, array(
1473 'Text', 'TextArea'))) {
1477 case 'StateProvince':
1480 switch ($htmlType) {
1481 case 'Multi-Select Country':
1482 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1483 $customData = array();
1484 foreach ($value as $val) {
1486 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1489 $retValue = implode(', ', $customData);
1492 case 'Select Country':
1493 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1496 case 'Select State/Province':
1497 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1500 case 'Multi-Select State/Province':
1501 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1502 $customData = array();
1503 foreach ($value as $val) {
1505 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1508 $retValue = implode(', ', $customData);
1513 case 'Autocomplete-Select':
1514 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1518 case 'AdvMulti-Select':
1519 case 'Multi-Select':
1520 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1521 $customData = array();
1522 foreach ($value as $val) {
1524 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1527 $retValue = implode(', ', $customData);
1542 function removeDuplicates(&$rows) {
1543 if (empty($this->_noRepeats
)) {
1546 $checkList = array();
1548 foreach ($rows as $key => $list) {
1549 foreach ($list as $colName => $colVal) {
1550 if (array_key_exists($colName, $checkList) &&
1551 $checkList[$colName] == $colVal) {
1552 $rows[$key][$colName] = "";
1554 if (in_array($colName, $this->_noRepeats
)) {
1555 $checkList[$colName] = $colVal;
1561 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1562 foreach ($row as $colName => $colVal) {
1563 if (in_array($colName, $fields)) {
1564 $row[$colName] = $row[$colName];
1566 elseif (isset($this->_columnHeaders
[$colName])) {
1568 $row[$colName] = "Subtotal";
1572 unset($row[$colName]);
1578 function grandTotal(&$rows) {
1579 if (!$this->_rollup ||
($this->_rollup
== '') ||
1580 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1584 $lastRow = array_pop($rows);
1586 $this->_grandFlag
= FALSE;
1587 foreach ($this->_columnHeaders
as $fld => $val) {
1588 if (!in_array($fld, $this->_statFields
)) {
1589 if (!$this->_grandFlag
) {
1590 $lastRow[$fld] = "Grand Total";
1591 $this->_grandFlag
= TRUE;
1594 $lastRow[$fld] = "";
1599 $this->assign('grandStat', $lastRow);
1603 function formatDisplay(&$rows, $pager = TRUE) {
1604 // set pager based on if any limit was applied in the query.
1609 // allow building charts if any
1610 if (!empty($this->_params
['charts']) && !empty($rows)) {
1611 $this->buildChart($rows);
1612 $this->assign('chartEnabled', TRUE);
1613 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1614 $this->assign('chartId', $this->_chartId
);
1617 // unset columns not to be displayed.
1618 foreach ($this->_columnHeaders
as $key => $value) {
1619 if (is_array($value) && isset($value['no_display'])) {
1620 unset($this->_columnHeaders
[$key]);
1624 // unset columns not to be displayed.
1625 if (!empty($rows)) {
1626 foreach ($this->_noDisplay
as $noDisplayField) {
1627 foreach ($rows as $rowNum => $row) {
1628 unset($this->_columnHeaders
[$noDisplayField]);
1633 // build array of section totals
1634 $this->sectionTotals();
1636 // process grand-total row
1637 $this->grandTotal($rows);
1639 // use this method for formatting rows for display purpose.
1640 $this->alterDisplay($rows);
1641 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1643 // use this method for formatting custom rows for display purpose.
1644 $this->alterCustomDataDisplay($rows);
1647 function buildChart(&$rows) {
1648 // override this method for building charts.
1651 // select() method below has been added recently (v3.3), and many of the report templates might
1652 // still be having their own select() method. We should fix them as and when encountered and move
1653 // towards generalizing the select() method below.
1657 foreach ($this->_columns
as $tableName => $table) {
1658 if (array_key_exists('fields', $table)) {
1659 foreach ($table['fields'] as $fieldName => $field) {
1660 if ($tableName == 'civicrm_address') {
1661 $this->_addressField
= TRUE;
1663 if ($tableName == 'civicrm_email') {
1664 $this->_emailField
= TRUE;
1666 if ($tableName == 'civicrm_phone') {
1667 $this->_phoneField
= TRUE;
1670 if (CRM_Utils_Array
::value('required', $field) ||
1671 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1674 // 1. In many cases we want select clause to be built in slightly different way
1675 // for a particular field of a particular type.
1676 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1678 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1679 if ($selectClause) {
1680 $select[] = $selectClause;
1684 // include statistics columns only if set
1685 if (CRM_Utils_Array
::value('statistics', $field)) {
1686 foreach ($field['statistics'] as $stat => $label) {
1687 $alias = "{$tableName}_{$fieldName}_{$stat}";
1688 switch (strtolower($stat)) {
1691 $select[] = "$stat({$field['dbAlias']}) as $alias";
1692 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1693 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1694 $this->_statFields
[] = $alias;
1695 $this->_selectAliases
[] = $alias;
1699 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1700 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1701 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1702 $this->_statFields
[] = $alias;
1703 $this->_selectAliases
[] = $alias;
1707 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1708 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1709 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1710 $this->_statFields
[] = $alias;
1711 $this->_selectAliases
[] = $alias;
1717 $alias = "{$tableName}_{$fieldName}";
1718 $select[] = "{$field['dbAlias']} as $alias";
1719 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1720 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1721 $this->_selectAliases
[] = $alias;
1727 // select for group bys
1728 if (array_key_exists('group_bys', $table)) {
1729 foreach ($table['group_bys'] as $fieldName => $field) {
1731 if ($tableName == 'civicrm_address') {
1732 $this->_addressField
= TRUE;
1734 if ($tableName == 'civicrm_email') {
1735 $this->_emailField
= TRUE;
1737 if ($tableName == 'civicrm_phone') {
1738 $this->_phoneField
= TRUE;
1740 // 1. In many cases we want select clause to be built in slightly different way
1741 // for a particular field of a particular type.
1742 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1744 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1745 if ($selectClause) {
1746 $select[] = $selectClause;
1750 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1751 && !empty($this->_params
['group_bys_freq'])) {
1752 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1754 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1755 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1756 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1757 $field['title'] = 'Week';
1761 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1762 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1763 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1764 $field['title'] = 'Year';
1768 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1769 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1770 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1771 $field['title'] = 'Month';
1775 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1776 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1777 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1778 $field['title'] = 'Quarter';
1781 // for graphs and charts -
1782 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1783 $this->_interval
= $field['title'];
1784 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1785 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1786 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1788 // just to make sure these values are transfered to rows.
1789 // since we 'll need them for calculation purpose,
1790 // e.g making subtotals look nicer or graphs
1791 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1792 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1799 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1802 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1807 $whereClauses = $havingClauses = array();
1808 foreach ($this->_columns
as $tableName => $table) {
1809 if (array_key_exists('filters', $table)) {
1810 foreach ($table['filters'] as $fieldName => $field) {
1812 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1813 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1814 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1815 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1816 if (is_array($value) && !empty($value)) {
1817 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1821 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1822 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1823 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1824 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1825 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1826 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1830 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1832 $clause = $this->whereClause($field,
1834 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1835 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1836 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1841 if (!empty($clause)) {
1842 if (CRM_Utils_Array
::value('having', $field)) {
1843 $havingClauses[] = $clause;
1846 $whereClauses[] = $clause;
1853 if (empty($whereClauses)) {
1854 $this->_where
= "WHERE ( 1 ) ";
1855 $this->_having
= "";
1858 $this->_where
= "WHERE " . implode(' AND ', $whereClauses);
1861 if ($this->_aclWhere
) {
1862 $this->_where
.= " AND {$this->_aclWhere} ";
1865 if (!empty($havingClauses)) {
1866 // use this clause to construct group by clause.
1867 $this->_having
= "HAVING " . implode(' AND ', $havingClauses);
1871 function processReportMode() {
1872 $buttonName = $this->controller
->getButtonName();
1874 $output = CRM_Utils_Request
::retrieve(
1877 CRM_Core_DAO
::$_nullObject
1881 CRM_Utils_Request
::retrieve(
1884 CRM_Core_DAO
::$_nullObject
1887 $this->_absoluteUrl
= FALSE;
1889 $this->assign('printOnly', FALSE);
1891 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1892 $this->assign('printOnly', TRUE);
1894 $this->assign('outputMode', 'print');
1895 $this->_outputMode
= 'print';
1896 if ($this->_sendmail
) {
1897 $this->_absoluteUrl
= TRUE;
1900 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1901 $this->assign('printOnly', TRUE);
1903 $this->assign('outputMode', 'pdf');
1904 $this->_outputMode
= 'pdf';
1905 $this->_absoluteUrl
= TRUE;
1907 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
1908 $this->assign('printOnly', TRUE);
1910 $this->assign('outputMode', 'csv');
1911 $this->_outputMode
= 'csv';
1912 $this->_absoluteUrl
= TRUE;
1914 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
1915 $this->assign('outputMode', 'group');
1916 $this->_outputMode
= 'group';
1918 elseif ($output == 'create_report' && $this->_criteriaForm
) {
1919 $this->assign('outputMode', 'create_report');
1920 $this->_outputMode
= 'create_report';
1923 $this->assign('outputMode', 'html');
1924 $this->_outputMode
= 'html';
1927 // Get today's date to include in printed reports
1929 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
1930 $this->assign('reportDate', $reportDate);
1934 function beginPostProcess() {
1935 $this->_params
= $this->controller
->exportValues($this->_name
);
1937 if (empty($this->_params
) &&
1940 $this->_params
= $this->_formValues
;
1943 // hack to fix params when submitted from dashboard, CRM-8532
1944 // fields array is missing because form building etc is skipped
1945 // in dashboard mode for report
1946 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
1947 $this->_params
= $this->_formValues
;
1950 $this->_formValues
= $this->_params
;
1951 if (CRM_Core_Permission
::check('administer Reports') &&
1952 isset($this->_id
) &&
1953 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
1954 $this->_chartButtonName
== $this->controller
->getButtonName()
1957 $this->assign('updateReportButton', TRUE);
1959 $this->processReportMode();
1962 function buildQuery($applyLimit = TRUE) {
1965 $this->customDataFrom();
1970 // order_by columns not selected for display need to be included in SELECT
1971 $unselectedSectionColumns = $this->unselectedSectionColumns();
1972 foreach ($unselectedSectionColumns as $alias => $section) {
1973 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
1976 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
1979 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
1981 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
1985 function groupBy() {
1986 $groupBys = array();
1987 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
1988 is_array($this->_params
['group_bys']) &&
1989 !empty($this->_params
['group_bys'])
1991 foreach ($this->_columns
as $tableName => $table) {
1992 if (array_key_exists('group_bys', $table)) {
1993 foreach ($table['group_bys'] as $fieldName => $field) {
1994 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
1995 $groupBys[] = $field['dbAlias'];
2002 if (!empty($groupBys)) {
2003 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2007 function orderBy() {
2008 $this->_orderBy
= "";
2009 $this->_sections
= array();
2010 $this->storeOrderByArray();
2011 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2012 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2014 $this->assign('sections', $this->_sections
);
2017 * In some cases other functions want to know which fields are selected for ordering by
2018 * Separating this into a separate function allows it to be called separately from constructing
2019 * the order by clause
2021 function storeOrderByArray() {
2022 $orderBys = array();
2024 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2025 is_array($this->_params
['order_bys']) &&
2026 !empty($this->_params
['order_bys'])
2029 // Proces order_bys in user-specified order
2030 foreach ($this->_params
['order_bys'] as $orderBy) {
2031 $orderByField = array();
2032 foreach ($this->_columns
as $tableName => $table) {
2033 if (array_key_exists('order_bys', $table)) {
2034 // For DAO columns defined in $this->_columns
2035 $fields = $table['order_bys'];
2037 elseif (array_key_exists('extends', $table)) {
2038 // For custom fields referenced in $this->_customGroupExtends
2039 $fields = $table['fields'];
2041 if (!empty($fields) && is_array($fields)) {
2042 foreach ($fields as $fieldName => $field) {
2043 if ($fieldName == $orderBy['column']) {
2044 $orderByField = $field;
2045 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2052 if (!empty($orderByField)) {
2053 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2055 // Record any section headers for assignment to the template
2056 if (CRM_Utils_Array
::value('section', $orderBy)) {
2057 $this->_sections
[$orderByField['tplField']] = $orderByField;
2063 $this->_orderByArray
= $orderBys;
2065 $this->assign('sections', $this->_sections
);
2068 function unselectedSectionColumns() {
2069 $selectColumns = array();
2070 foreach ($this->_columns
as $tableName => $table) {
2071 if (array_key_exists('fields', $table)) {
2072 foreach ($table['fields'] as $fieldName => $field) {
2073 if (CRM_Utils_Array
::value('required', $field) ||
2074 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2077 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2082 if (is_array($this->_sections
)) {
2083 return array_diff_key($this->_sections
, $selectColumns);
2090 function buildRows($sql, &$rows) {
2091 $dao = CRM_Core_DAO
::executeQuery($sql);
2092 if (!is_array($rows)) {
2096 // use this method to modify $this->_columnHeaders
2097 $this->modifyColumnHeaders();
2099 $unselectedSectionColumns = $this->unselectedSectionColumns();
2101 while ($dao->fetch()) {
2103 foreach ($this->_columnHeaders
as $key => $value) {
2104 if (property_exists($dao, $key)) {
2105 $row[$key] = $dao->$key;
2109 // section headers not selected for display need to be added to row
2110 foreach ($unselectedSectionColumns as $key => $values) {
2111 if (property_exists($dao, $key)) {
2112 $row[$key] = $dao->$key;
2121 * When "order by" fields are marked as sections, this assigns to the template
2122 * an array of total counts for each section. This data is used by the Smarty
2123 * plugin {sectionTotal}
2125 function sectionTotals() {
2127 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2128 if (empty($this->_selectAliases
)) {
2132 if (!empty($this->_sections
)) {
2133 // build the query with no LIMIT clause
2134 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2135 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2137 // pull section aliases out of $this->_sections
2138 $sectionAliases = array_keys($this->_sections
);
2141 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2142 $ifnulls[] = "ifnull($alias, '') as $alias";
2145 /* Group (un-limited) report by all aliases and get counts. This might
2146 * be done more efficiently when the contents of $sql are known, ie. by
2147 * overriding this method in the report class.
2151 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2153 // initialize array of total counts
2155 $dao = CRM_Core_DAO
::executeQuery($query);
2156 while ($dao->fetch()) {
2158 // let $this->_alterDisplay translate any integer ids to human-readable values.
2159 $rows[0] = $dao->toArray();
2160 $this->alterDisplay($rows);
2163 // add totals for all permutations of section values
2166 $aliasCount = count($sectionAliases);
2167 foreach ($sectionAliases as $alias) {
2168 $values[] = $row[$alias];
2169 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2170 if ($i == $aliasCount) {
2171 // the last alias is the lowest-level section header; use count as-is
2172 $totals[$key] = $dao->ct
;
2175 // other aliases are higher level; roll count into their total
2176 $totals[$key] +
= $dao->ct
;
2180 $this->assign('sectionTotals', $totals);
2184 function modifyColumnHeaders() {
2185 // use this method to modify $this->_columnHeaders
2188 function doTemplateAssignment(&$rows) {
2189 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2190 $this->assign_by_ref('rows', $rows);
2191 $this->assign('statistics', $this->statistics($rows));
2194 // override this method to build your own statistics
2195 function statistics(&$rows) {
2196 $statistics = array();
2198 $count = count($rows);
2200 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2204 $this->countStat($statistics, $count);
2206 $this->groupByStat($statistics);
2208 $this->filterStat($statistics);
2213 function countStat(&$statistics, $count) {
2214 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2218 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2219 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2220 'value' => $this->_rowsFound
,
2225 function groupByStat(&$statistics) {
2226 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2227 is_array($this->_params
['group_bys']) &&
2228 !empty($this->_params
['group_bys'])
2230 foreach ($this->_columns
as $tableName => $table) {
2231 if (array_key_exists('group_bys', $table)) {
2232 foreach ($table['group_bys'] as $fieldName => $field) {
2233 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2234 $combinations[] = $field['title'];
2239 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2240 'value' => implode(' & ', $combinations),
2245 function filterStat(&$statistics) {
2246 foreach ($this->_columns
as $tableName => $table) {
2247 if (array_key_exists('filters', $table)) {
2248 foreach ($table['filters'] as $fieldName => $field) {
2249 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2252 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2253 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2254 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2255 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2256 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2258 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2259 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2261 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2262 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2265 $statistics['filters'][] = array(
2266 'title' => $field['title'],
2267 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2270 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2271 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2273 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2274 $statistics['filters'][] = array(
2275 'title' => $field['title'],
2276 'value' => $pair[$rel],
2281 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2284 $pair = $this->getOperationPair(
2285 CRM_Utils_Array
::value('operatorType', $field),
2288 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2289 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2290 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2291 if (in_array($op, array(
2292 'bw', 'nbw')) && ($min ||
$max)) {
2293 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2295 elseif ($op == 'nll' ||
$op == 'nnll') {
2296 $value = $pair[$op];
2298 elseif (is_array($val) && (!empty($val))) {
2299 $options = $field['options'];
2300 foreach ($val as $key => $valIds) {
2301 if (isset($options[$valIds])) {
2302 $val[$key] = $options[$valIds];
2305 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : $pair[$op];
2306 $val = implode(', ', $val);
2307 $value = "{$pair[$op]} " . $val;
2309 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2310 is_array($field['options']) && !empty($field['options'])
2312 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2315 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2319 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2329 function endPostProcess(&$rows = NULL) {
2330 if ($this->_outputMode
== 'print' ||
2331 $this->_outputMode
== 'pdf' ||
2335 $content = $this->compileContent();
2336 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2340 if ($this->_sendmail
) {
2341 $config = CRM_Core_Config
::singleton();
2342 $attachments = array();
2344 if ($this->_outputMode
== 'csv') {
2345 $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'];
2347 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2348 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2349 file_put_contents($csvFullFilename, $csvContent);
2350 $attachments[] = array(
2351 'fullPath' => $csvFullFilename,
2352 'mime_type' => 'text/csv',
2353 'cleanName' => 'CiviReport.csv',
2356 if ($this->_outputMode
== 'pdf') {
2357 // generate PDF content
2358 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2359 file_put_contents($pdfFullFilename,
2360 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2361 TRUE, array('orientation' => 'landscape')
2364 // generate Email Content
2365 $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'];
2367 $attachments[] = array(
2368 'fullPath' => $pdfFullFilename,
2369 'mime_type' => 'application/pdf',
2370 'cleanName' => 'CiviReport.pdf',
2374 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2375 $this->_outputMode
, $attachments
2377 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2380 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2383 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2385 elseif ($this->_outputMode
== 'print') {
2389 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2390 $config = CRM_Core_Config
::singleton();
2391 //get chart image name
2392 $chartImg = $this->_chartId
. '.png';
2393 //get image url path
2394 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2395 $uploadUrl .= $chartImg;
2396 //get image doc path to overwrite
2397 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2399 $chart = imagecreatefrompng($uploadUrl);
2400 //convert it into formattd png
2401 header('Content-type: image/png');
2402 //overwrite with same image
2403 imagepng($chart, $uploadImg);
2405 imagedestroy($chart);
2407 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2409 CRM_Utils_System
::civiExit();
2411 elseif ($this->_outputMode
== 'csv') {
2412 CRM_Report_Utils_Report
::export2csv($this, $rows);
2414 elseif ($this->_outputMode
== 'group') {
2415 $group = $this->_params
['groups'];
2416 $this->add2group($group);
2418 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2419 CRM_Report_Form_Instance
::postProcess($this);
2421 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2422 $this->_outputMode
== 'create_report' ) {
2423 $this->_createNew
= TRUE;
2424 CRM_Report_Form_Instance
::postProcess($this);
2429 * Get Template file name - use default form template if a specific one has not been set up for this report
2432 function getTemplateFileName(){
2433 $defaultTpl = parent
::getTemplateFileName();
2434 $template = CRM_Core_Smarty
::singleton();
2435 if (!$template->template_exists($defaultTpl)) {
2436 $defaultTpl = 'CRM/Report/Form.tpl';
2442 * Compile the report content
2444 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2446 function compileContent(){
2447 $templateFile = $this->getTemplateFileName();
2448 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2452 function postProcess() {
2453 // get ready with post process params
2454 $this->beginPostProcess();
2457 $sql = $this->buildQuery();
2459 // build array of result based on column headers. This method also allows
2460 // modifying column headers before using it to build result set i.e $rows.
2462 $this->buildRows($sql, $rows);
2464 // format result set.
2465 $this->formatDisplay($rows);
2467 // assign variables to templates
2468 $this->doTemplateAssignment($rows);
2470 // do print / pdf / instance stuff if needed
2471 $this->endPostProcess($rows);
2474 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2475 // lets do the pager if in html mode
2476 $this->_limit
= NULL;
2477 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2478 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2480 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2482 if (!$pageId && !empty($_POST)) {
2483 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2484 $pageId = max((int)@$_POST['crmPID_B'], 1);
2486 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2487 $pageId = max((int)@$_POST['crmPID'], 1);
2489 unset($_POST['crmPID_B'], $_POST['crmPID']);
2492 $pageId = $pageId ?
$pageId : 1;
2493 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2494 $offset = ($pageId - 1) * $rowCount;
2496 $this->_limit
= " LIMIT $offset, " . $rowCount;
2497 return array($offset, $rowCount);
2501 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2502 if ($this->_limit
&& ($this->_limit
!= '')) {
2503 $sql = "SELECT FOUND_ROWS();";
2504 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2506 'total' => $this->_rowsFound
,
2507 'rowCount' => $rowCount,
2508 'status' => ts('Records') . ' %%StatusMessage%%',
2509 'buttonBottom' => 'PagerBottomButton',
2510 'buttonTop' => 'PagerTopButton',
2511 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2514 $pager = new CRM_Utils_Pager($params);
2515 $this->assign_by_ref('pager', $pager);
2519 function whereGroupClause($field, $value, $op) {
2521 $smartGroupQuery = "";
2523 $group = new CRM_Contact_DAO_Group();
2524 $group->is_active
= 1;
2526 $smartGroups = array();
2527 while ($group->fetch()) {
2528 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2529 $smartGroups[] = $group->id
;
2533 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2535 $smartGroupQuery = '';
2536 if (!empty($smartGroups)) {
2537 $smartGroups = implode(',', $smartGroups);
2538 $smartGroupQuery = " UNION DISTINCT
2539 SELECT DISTINCT smartgroup_contact.contact_id
2540 FROM civicrm_group_contact_cache smartgroup_contact
2541 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2544 $sqlOp = $this->getSQLOperator($op);
2545 if (!is_array($value)) {
2546 $value = array($value);
2548 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2550 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2551 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2552 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2553 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2554 {$smartGroupQuery} ) ";
2557 function whereTagClause($field, $value, $op) {
2558 // not using left join in query because if any contact
2559 // belongs to more than one tag, results duplicate
2561 $sqlOp = $this->getSQLOperator($op);
2562 if (!is_array($value)) {
2563 $value = array($value);
2565 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2567 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2568 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2569 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2570 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2573 function buildACLClause($tableAlias = 'contact_a') {
2574 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2577 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2578 if (empty($this->_customGroupExtends
)) {
2581 if (!is_array($this->_customGroupExtends
)) {
2582 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2584 $customGroupWhere = '';
2585 if (!empty($permCustomGroupIds)) {
2586 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2589 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2590 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2591 FROM civicrm_custom_group cg
2592 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2593 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2595 cg.is_active = 1 AND
2596 cf.is_active = 1 AND
2597 cf.is_searchable = 1
2598 ORDER BY cg.weight, cf.weight";
2599 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2602 while ($customDAO->fetch()) {
2603 if ($customDAO->table_name
!= $curTable) {
2604 $curTable = $customDAO->table_name
;
2605 $curFields = $curFilters = array();
2608 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2609 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2610 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2611 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2614 'fields', 'filters', 'group_bys') as $colKey) {
2615 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2616 $this->_columns
[$curTable][$colKey] = array();
2620 $fieldName = 'custom_' . $customDAO->cf_id
;
2623 // this makes aliasing work in favor
2624 $curFields[$fieldName] = array(
2625 'name' => $customDAO->column_name
,
2626 'title' => $customDAO->label
,
2627 'dataType' => $customDAO->data_type
,
2628 'htmlType' => $customDAO->html_type
,
2631 if ($this->_customGroupFilters
) {
2632 // this makes aliasing work in favor
2633 $curFilters[$fieldName] = array(
2634 'name' => $customDAO->column_name
,
2635 'title' => $customDAO->label
,
2636 'dataType' => $customDAO->data_type
,
2637 'htmlType' => $customDAO->html_type
,
2641 switch ($customDAO->data_type
) {
2644 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2645 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2646 // CRM-6946, show time part for datetime date fields
2647 if ($customDAO->time_format
) {
2648 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2653 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2654 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2658 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2662 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2663 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2667 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2668 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2672 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2673 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2677 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2679 if (!empty($customDAO->option_group_id
)) {
2680 if (in_array($customDAO->html_type
, array(
2681 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2682 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2685 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2687 if ($this->_customGroupFilters
) {
2688 $curFilters[$fieldName]['options'] = array();
2689 $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')));
2690 while ($ogDAO->fetch()) {
2691 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2697 case 'StateProvince':
2698 if (in_array($customDAO->html_type
, array(
2699 'Multi-Select State/Province'))) {
2700 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2703 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2705 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2709 if (in_array($customDAO->html_type
, array(
2710 'Multi-Select Country'))) {
2711 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2714 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2716 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2719 case 'ContactReference':
2720 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2721 $curFilters[$fieldName]['name'] = 'display_name';
2722 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2724 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2725 $curFields[$fieldName]['name'] = 'display_name';
2726 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2730 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2731 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2734 if (!array_key_exists('type', $curFields[$fieldName])) {
2735 $curFields[$fieldName]['type'] = $curFilters[$fieldName]['type'];
2739 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2741 if ($this->_customGroupFilters
) {
2742 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2744 if ($this->_customGroupGroupBy
) {
2745 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2750 function customDataFrom() {
2751 if (empty($this->_customGroupExtends
)) {
2754 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2756 foreach ($this->_columns
as $table => $prop) {
2757 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2758 $extendsTable = $mapper[$prop['extends']];
2760 // check field is in params
2761 if (!$this->isFieldSelected($prop)) {
2766 LEFT JOIN $table {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2767 // handle for ContactReference
2768 if (array_key_exists('fields', $prop)) {
2769 foreach ($prop['fields'] as $fieldName => $field) {
2770 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2771 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2773 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2781 function isFieldSelected($prop) {
2786 if (!empty($this->_params
['fields'])) {
2787 foreach (array_keys($prop['fields']) as $fieldAlias) {
2788 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2789 if ($customFieldId) {
2790 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2794 //might be survey response field.
2795 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2796 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2804 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2805 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2806 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2812 if (!empty($this->_params
['order_bys'])) {
2813 foreach (array_keys($prop['fields']) as $fieldAlias) {
2814 foreach ($this->_params
['order_bys'] as $orderBy) {
2815 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2822 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2823 foreach ($prop['filters'] as $fieldAlias => $val) {
2825 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2826 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2827 (!empty($this->_params
[$fieldAlias . '_' . $attach]) ||
$this->_params
[$fieldAlias . '_' . $attach] == '0')
2832 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2833 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2844 * Check for empty order_by configurations and remove them; also set
2845 * template to hide them.
2847 function preProcessOrderBy(&$formValues) {
2848 // Object to show/hide form elements
2849 $_showHide = &new CRM_Core_ShowHideBlocks('', '');
2851 $_showHide->addShow('optionField_1');
2853 // Cycle through order_by options; skip any empty ones, and hide them as well
2856 if (!empty($formValues['order_bys'])) {
2857 foreach ($formValues['order_bys'] as $order_by) {
2858 if ($order_by['column'] && $order_by['column'] != '-') {
2859 $_showHide->addShow('optionField_' . $n);
2860 $orderBys[$n] = $order_by;
2865 for ($i = $n; $i <= 5; $i++
) {
2867 $_showHide->addHide('optionField_' . $i);
2871 // overwrite order_by options with modified values
2872 if (!empty($orderBys)) {
2873 $formValues['order_bys'] = $orderBys;
2876 $formValues['order_bys'] = array(1 => array('column' => '-'));
2879 // assign show/hide data to template
2880 $_showHide->addToTemplate();
2884 * Does table name have columns in SELECT clause?
2886 * @param string $tableName Name of table (index of $this->_columns array)
2890 function isTableSelected($tableName) {
2891 return in_array($tableName, $this->selectedTables());
2895 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
2896 * (building the array if it's unset)
2898 * @return Array $this->_selectedTables
2900 function selectedTables() {
2901 if (!$this->_selectedTables
) {
2902 $orderByColumns = array();
2903 if (is_array($this->_params
['order_bys'])) {
2904 foreach ($this->_params
['order_bys'] as $orderBy) {
2905 $orderByColumns[] = $orderBy['column'];
2909 foreach ($this->_columns
as $tableName => $table) {
2910 if (array_key_exists('fields', $table)) {
2911 foreach ($table['fields'] as $fieldName => $field) {
2912 if (CRM_Utils_Array
::value('required', $field) ||
2913 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2915 $this->_selectedTables
[] = $tableName;
2920 if (array_key_exists('order_bys', $table)) {
2921 foreach ($table['order_bys'] as $orderByName => $orderBy) {
2922 if (in_array($orderByName, $orderByColumns)) {
2923 $this->_selectedTables
[] = $tableName;
2928 if (array_key_exists('filters', $table)) {
2929 foreach ($table['filters'] as $filterName => $filter) {
2930 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
2931 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
2932 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
2934 $this->_selectedTables
[] = $tableName;
2941 return $this->_selectedTables
;
2945 * function for adding address fields to construct function in reports
2946 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
2947 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
2948 * @return array address fields for construct clause
2950 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
2951 'country_id' => TRUE)) {
2952 $addressFields = array(
2953 'civicrm_address' =>
2955 'dao' => 'CRM_Core_DAO_Address',
2959 array('title' => ts('Address Name'),
2960 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
2963 array('title' => ts('Street Address'),
2964 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
2966 'supplemental_address_1' =>
2967 array('title' => ts('Supplementary Address Field 1'),
2968 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
2970 'supplemental_address_2' =>
2971 array('title' => ts('Supplementary Address Field 2'),
2972 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
2976 'name' => 'street_number',
2977 'title' => ts('Street Number'),
2979 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
2983 'name' => 'street_name',
2984 'title' => ts('Street Name'),
2986 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
2990 'name' => 'street_unit',
2991 'title' => ts('Street Unit'),
2993 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
2996 array('title' => ts('City'),
2997 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3000 array('title' => ts('Postal Code'),
3001 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3004 array('title' => ts('County'),
3005 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3007 'state_province_id' =>
3008 array('title' => ts('State/Province'),
3009 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3012 array('title' => ts('Country'),
3013 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3016 'grouping' => 'location-fields',
3021 $addressFields['civicrm_address']['filters'] = array(
3022 'street_number' => array('title' => ts('Street Number'),
3024 'name' => 'street_number',
3026 'street_name' => array('title' => ts('Street Name'),
3027 'name' => 'street_name',
3028 'operator' => 'like',
3030 'postal_code' => array('title' => ts('Postal Code'),
3032 'name' => 'postal_code',
3034 'city' => array('title' => ts('City'),
3035 'operator' => 'like',
3038 'county_id' => array(
3039 'name' => 'county_id',
3040 'title' => ts('County'),
3041 'type' => CRM_Utils_Type
::T_INT
,
3043 CRM_Report_Form
::OP_MULTISELECT
,
3045 CRM_Core_PseudoConstant
::county(),
3047 'state_province_id' => array(
3048 'name' => 'state_province_id',
3049 'title' => ts('State/Province'),
3050 'type' => CRM_Utils_Type
::T_INT
,
3052 CRM_Report_Form
::OP_MULTISELECT
,
3054 CRM_Core_PseudoConstant
::stateProvince(),
3056 'country_id' => array(
3057 'name' => 'country_id',
3058 'title' => ts('Country'),
3059 'type' => CRM_Utils_Type
::T_INT
,
3061 CRM_Report_Form
::OP_MULTISELECT
,
3063 CRM_Core_PseudoConstant
::country(),
3069 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3070 'street_number' => array('title' => 'Odd / Even Street Number'),
3071 'street_address' => NULL,
3073 'postal_code' => NULL,
3078 $addressFields['civicrm_address']['group_bys'] = array(
3079 'street_address' => NULL,
3081 'postal_code' => NULL,
3082 'state_province_id' =>
3083 array('title' => ts('State/Province'),
3086 array('title' => ts('Country'),
3089 array('title' => ts('County'),
3093 return $addressFields;
3097 * Do AlterDisplay processing on Address Fields
3099 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3100 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3101 $entryFound = FALSE;
3103 if (array_key_exists('civicrm_address_country_id', $row)) {
3104 if ($value = $row['civicrm_address_country_id']) {
3105 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3106 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3107 "reset=1&force=1&{$criteriaQueryParams}&" .
3108 "country_id_op=in&country_id_value={$value}",
3109 $this->_absoluteUrl
, $this->_id
3111 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3112 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3119 if (array_key_exists('civicrm_address_county_id', $row)) {
3120 if ($value = $row['civicrm_address_county_id']) {
3121 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3122 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3123 "reset=1&force=1&{$criteriaQueryParams}&" .
3124 "county_id_op=in&county_id_value={$value}",
3125 $this->_absoluteUrl
, $this->_id
3127 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3128 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3134 // handle state province
3135 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3136 if ($value = $row['civicrm_address_state_province_id']) {
3137 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3139 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3140 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3141 $this->_absoluteUrl
, $this->_id
3143 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3144 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3155 * Adjusts dates passed in to YEAR() for fiscal year.
3157 function fiscalYearOffset($fieldName) {
3158 $config = CRM_Core_Config
::singleton();
3159 $fy = $config->fiscalYearStart
;
3160 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3161 return "YEAR( $fieldName )";
3163 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3167 * Add Address into From Table if required
3169 function addAddressFromClause() {
3170 // include address field if address column is to be included
3171 if ((isset($this->_addressField
) &&
3172 $this->_addressField
3174 $this->isTableSelected('civicrm_address')
3177 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3178 ON ({$this->_aliases['civicrm_contact']}.id =
3179 {$this->_aliases['civicrm_address']}.contact_id) AND
3180 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3184 function add2group($groupID) {
3185 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3186 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3187 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3189 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3190 $dao = CRM_Core_DAO
::executeQuery($sql);
3192 $contact_ids = array();
3193 // Add resulting contacts to group
3194 while ($dao->fetch()) {
3195 if ($dao->addtogroup_contact_id
) {
3196 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3200 if ( !empty($contact_ids) ) {
3201 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3202 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3205 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));