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;
231 public $_whereClauses = array();
232 public $_havingClauses = array();
235 * Variable to hold the currency alias
237 protected $_currencyColumn = NULL;
242 function __construct() {
243 parent
::__construct();
246 if ($this->_tagFilter
) {
247 $this->buildTagFilter();
249 if ($this->_exposeContactID
) {
250 if (array_key_exists('civicrm_contact', $this->_columns
)) {
251 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
253 'title' => 'Contact ID',
259 if ($this->_groupFilter
) {
260 $this->buildGroupFilter();
263 // Get all custom groups
264 $allGroups = CRM_Core_PseudoConstant
::customGroup();
266 // Get the custom groupIds for which the user have VIEW permission
267 require_once 'CRM/ACL/API.php';
268 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
270 // do not allow custom data for reports if user don't have
271 // permission to access custom data.
272 if (!empty($this->_customGroupExtends
) && !CRM_Core_Permission
::check('access all custom data') && empty($permCustomGroupIds)) {
273 $this->_customGroupExtends
= array();
276 // merge custom data columns to _columns list, if any
277 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
279 // add / modify display columns, filters ..etc
280 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
282 //assign currencyColumn variable to tpl
283 $this->assign('currencyColumn', $this->_currencyColumn
);
286 function preProcessCommon() {
288 CRM_Utils_Request
::retrieve(
291 CRM_Core_DAO
::$_nullObject
294 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
296 $this->assign('section', $this->_section
);
297 CRM_Core_Region
::instance('page-header')->add(array(
298 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
301 $this->_id
= $this->get('instanceId');
303 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
305 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
309 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
310 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
311 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
314 $this->assign('instanceId', $this->_id
);
315 $params = array('id' => $this->_id
);
316 $this->_instanceValues
= array();
317 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_Instance',
319 $this->_instanceValues
321 if (empty($this->_instanceValues
)) {
322 CRM_Core_Error
::fatal("Report could not be loaded.");
325 if (!empty($this->_instanceValues
['permission']) &&
326 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
327 CRM_Core_Permission
::check('administer Reports')
330 CRM_Utils_System
::permissionDenied();
331 CRM_Utils_System
::civiExit();
334 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
336 $this->_formValues
= unserialize($formValues);
339 $this->_formValues
= NULL;
342 // lets always do a force if reset is found in the url.
343 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
348 $this->assign('mode', 'instance');
351 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
352 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
353 if (($instanceCount > 0) && $optionValueID) {
354 $this->assign('instanceUrl',
355 CRM_Utils_System
::url('civicrm/report/list',
356 "reset=1&ovid=$optionValueID"
360 if ($optionValueID) {
361 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
365 $this->assign('mode', 'template');
368 // lets display the Report Settings section
369 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
371 // Do not display Report Settings section if administer Reports permission is absent OR
372 // if report instance is reserved and administer reserved reports absent
373 if (!CRM_Core_Permission
::check('administer Reports') ||
374 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
375 $this->_instanceForm
= FALSE;
378 $this->assign('criteriaForm', FALSE);
379 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
380 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
381 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
382 $this->assign('criteriaForm', TRUE);
383 $this->_criteriaForm
= TRUE;
387 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
388 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
389 $this->_printButtonName
= $this->getButtonName('submit', 'print');
390 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
391 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
392 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
393 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
396 function addBreadCrumb() {
400 'title' => ts('Report Templates'),
401 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
405 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
408 function preProcess() {
409 $this->preProcessCommon();
412 $this->addBreadCrumb();
415 foreach ($this->_columns
as $tableName => $table) {
417 if (!isset($table['alias'])) {
418 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
421 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
424 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
426 // higher preference to bao object
427 if (array_key_exists('bao', $table)) {
428 require_once str_replace('_', DIRECTORY_SEPARATOR
, $table['bao'] . '.php');
429 eval("\$expFields = {$table['bao']}::exportableFields( );");
432 require_once str_replace('_', DIRECTORY_SEPARATOR
, $table['dao'] . '.php');
433 eval("\$expFields = {$table['dao']}::export( );");
436 $doNotCopy = array('required');
438 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
439 foreach ($fieldGroups as $fieldGrp) {
440 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
441 foreach ($table[$fieldGrp] as $fieldName => $field) {
442 // $name is the field name used to reference the BAO/DAO export fields array
443 $name = isset($field['name']) ?
$field['name'] : $fieldName;
445 // Sometimes the field name key in the BAO/DAO export fields array is
446 // different from the actual database field name.
447 // Unset $field['name'] so that actual database field name can be obtained
448 // from the BAO/DAO export fields array.
449 unset($field['name']);
451 if (array_key_exists($name, $expFields)) {
452 foreach ($doNotCopy as $dnc) {
453 // unset the values we don't want to be copied.
454 unset($expFields[$name][$dnc]);
457 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
460 foreach ($expFields[$name] as $property => $val) {
461 if (!array_key_exists($property, $field)) {
462 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
469 if (CRM_Utils_Array
::value('no_repeat', $field)) {
470 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
472 if (CRM_Utils_Array
::value('no_display', $field)) {
473 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
476 // set alias = table-name, unless already set
477 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
478 $this->_columns
[$tableName]['alias'] : $tableName
480 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
482 // set name = fieldName, unless already set
483 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
484 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
487 // set dbAlias = alias.name, unless already set
488 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
489 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
492 if (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName]) &&
493 !isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'])
495 if (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
496 array(CRM_Utils_Type
::T_MONEY
, CRM_Utils_Type
::T_FLOAT
)
498 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
500 elseif (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
501 array(CRM_Utils_Type
::T_INT
)
503 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
510 // copy filters to a separate handy variable
511 if (array_key_exists('filters', $table)) {
512 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
515 if (array_key_exists('group_bys', $table)) {
516 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
519 if (array_key_exists('fields', $table)) {
520 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
525 $this->setDefaultValues(FALSE);
528 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
529 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
530 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
531 CRM_Report_Utils_Get
::processChart($this->_defaults
);
534 $this->_formValues
= $this->_defaults
;
535 $this->postProcess();
539 function setDefaultValues($freeze = TRUE) {
540 $freezeGroup = array();
542 // FIXME: generalizing form field naming conventions would reduce
543 // lots of lines below.
544 foreach ($this->_columns
as $tableName => $table) {
545 if (array_key_exists('fields', $table)) {
546 foreach ($table['fields'] as $fieldName => $field) {
547 if (!array_key_exists('no_display', $field)) {
548 if (isset($field['required'])) {
550 $this->_defaults
['fields'][$fieldName] = 1;
553 // find element object, so that we could use quickform's freeze method
554 // for required elements
555 $obj = $this->getElementFromGroup("fields", $fieldName);
557 $freezeGroup[] = $obj;
561 elseif (isset($field['default'])) {
562 $this->_defaults
['fields'][$fieldName] = $field['default'];
568 if (array_key_exists('group_bys', $table)) {
569 foreach ($table['group_bys'] as $fieldName => $field) {
570 if (isset($field['default'])) {
571 if (CRM_Utils_Array
::value('frequency', $field)) {
572 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
574 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
578 if (array_key_exists('filters', $table)) {
579 foreach ($table['filters'] as $fieldName => $field) {
580 if (isset($field['default'])) {
581 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
582 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
585 $this->_defaults
["{$fieldName}_value"] = $field['default'];
588 //assign default value as "in" for multiselect
589 //operator, To freeze the select element
590 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
591 $this->_defaults
["{$fieldName}_op"] = 'in';
593 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
594 $this->_defaults
["{$fieldName}_op"] = 'mhas';
596 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
597 $this->_defaults
["{$fieldName}_op"] = $op;
603 array_key_exists('order_bys', $table) &&
604 is_array($table['order_bys'])
606 if (!array_key_exists('order_bys', $this->_defaults
)) {
607 $this->_defaults
['order_bys'] = array();
609 foreach ($table['order_bys'] as $fieldName => $field) {
611 CRM_Utils_Array
::value('default', $field) ||
612 CRM_Utils_Array
::value('default_order', $field) ||
613 CRM_Utils_Array
::value('default_is_section', $field) ||
614 CRM_Utils_Array
::value('default_weight', $field)
617 'column' => $fieldName,
618 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
619 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
622 if (CRM_Utils_Array
::value('default_weight', $field)) {
623 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
626 array_unshift($this->_defaults
['order_bys'], $order_by);
632 foreach ($this->_options
as $fieldName => $field) {
633 if (isset($field['default'])) {
634 $this->_defaults
['options'][$fieldName] = $field['default'];
639 if (!empty($this->_submitValues
)) {
640 $this->preProcessOrderBy($this->_submitValues
);
643 $this->preProcessOrderBy($this->_defaults
);
646 // lets finish freezing task here itself
647 if (!empty($freezeGroup)) {
648 foreach ($freezeGroup as $elem) {
653 if ($this->_formValues
) {
654 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
657 if ($this->_instanceValues
) {
658 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
661 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
663 return $this->_defaults
;
666 function getElementFromGroup($group, $grpFieldName) {
667 $eleObj = $this->getElement($group);
668 foreach ($eleObj->_elements
as $index => $obj) {
669 if ($grpFieldName == $obj->_attributes
['name']) {
676 function addColumns() {
679 foreach ($this->_columns
as $tableName => $table) {
680 if (array_key_exists('fields', $table)) {
681 foreach ($table['fields'] as $fieldName => $field) {
682 if (!array_key_exists('no_display', $field)) {
683 if (isset($field['grouping'])) {
684 $tableName = $field['grouping'];
686 elseif (isset($table['grouping'])) {
687 $tableName = $table['grouping'];
689 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
691 if (isset($table['group_title'])) {
692 $colGroups[$tableName]['group_title'] = $table['group_title'];
695 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
701 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
702 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
704 $this->assign('colGroups', $colGroups);
707 function addFilters() {
708 $options = $filters = array();
710 foreach ($this->_filters
as $table => $attributes) {
711 foreach ($attributes as $fieldName => $field) {
712 // get ready with option value pair
713 // @ 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
715 $operations = $this->getOperationPair(
716 CRM_Utils_Array
::value('operatorType', $field),
719 $filters[$table][$fieldName] = $field;
721 switch (CRM_Utils_Array
::value('operatorType', $field)) {
722 case CRM_Report_Form
::OP_MONTH
:
723 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
724 // If there's no option list for this filter, define one.
725 $field['options'] = array(
734 9 => ts('September'),
736 11 => ts('November'),
737 12 => ts('December'),
739 // Add this option list to this column _columns. This is
740 // required so that filter statistics show properly.
741 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
743 case CRM_Report_FORM
::OP_MULTISELECT
:
744 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
745 // assume a multi-select field
746 if (!empty($field['options'])) {
747 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
748 if (count($operations) <= 1) {
751 $select = $this->addElement('select', "{$fieldName}_value", NULL,
752 $field['options'], array(
754 'style' => 'min-width:250px',
757 $select->setMultiple(TRUE);
761 case CRM_Report_FORM
::OP_SELECT
:
762 // assume a select field
763 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
764 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
767 case CRM_Report_FORM
::OP_DATE
:
768 // build datetime fields
769 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count);
773 case CRM_Report_FORM
::OP_DATETIME
:
774 // build datetime fields
775 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, TRUE, 'searchDate', true);
779 case CRM_Report_FORM
::OP_INT
:
780 case CRM_Report_FORM
::OP_FLOAT
:
781 // and a min value input box
782 $this->add('text', "{$fieldName}_min", ts('Min'));
783 // and a max value input box
784 $this->add('text', "{$fieldName}_max", ts('Max'));
786 // default type is string
787 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
788 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
790 // we need text box for value input
791 $this->add('text', "{$fieldName}_value", NULL);
796 $this->assign('filters', $filters);
799 function addOptions() {
800 if (!empty($this->_options
)) {
801 // FIXME: For now lets build all elements as checkboxes.
802 // Once we clear with the format we can build elements based on type
805 foreach ($this->_options
as $fieldName => $field) {
806 if ($field['type'] == 'select') {
807 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
809 else if ($field['type'] == 'checkbox') {
810 $options[$field['title']] = $fieldName;
811 $this->addCheckBox($fieldName, NULL,
813 NULL, NULL, NULL, $this->_fourColumnAttribute
818 $this->assign('otherOptions', $this->_options
);
821 function addChartOptions() {
822 if (!empty($this->_charts
)) {
823 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
824 $this->assign('charts', $this->_charts
);
825 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
829 function addGroupBys() {
830 $options = $freqElements = array();
832 foreach ($this->_columns
as $tableName => $table) {
833 if (array_key_exists('group_bys', $table)) {
834 foreach ($table['group_bys'] as $fieldName => $field) {
835 if (!empty($field)) {
836 $options[$field['title']] = $fieldName;
837 if (CRM_Utils_Array
::value('frequency', $field)) {
838 $freqElements[$field['title']] = $fieldName;
844 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
845 NULL, NULL, NULL, $this->_fourColumnAttribute
847 $this->assign('groupByElements', $options);
849 foreach ($freqElements as $name) {
850 $this->addElement('select', "group_bys_freq[$name]",
851 ts('Frequency'), $this->_groupByDateFreq
856 function addOrderBys() {
858 foreach ($this->_columns
as $tableName => $table) {
860 // Report developer may define any column to order by; include these as order-by options
861 if (array_key_exists('order_bys', $table)) {
862 foreach ($table['order_bys'] as $fieldName => $field) {
863 if (!empty($field)) {
864 $options[$fieldName] = $field['title'];
869 /* Add searchable custom fields as order-by options, if so requested
870 * (These are already indexed, so allowing to order on them is cheap.)
874 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
875 foreach ($table['fields'] as $fieldName => $field) {
876 if (!array_key_exists('no_display', $field)) {
877 $options[$fieldName] = $field['title'];
885 $this->assign('orderByOptions', $options);
887 if (!empty($options)) {
889 '-' => ' - none - ') +
$options;
890 for ($i = 1; $i <= 5; $i++
) {
891 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
892 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
893 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
898 function buildInstanceAndButtons() {
899 CRM_Report_Form_Instance
::buildForm($this);
901 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
903 $this->addElement('submit', $this->_instanceButtonName
, $label);
904 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
905 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
908 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
910 if ($this->_instanceForm
) {
911 $this->assign('instanceForm', TRUE);
914 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
915 $this->addElement('submit', $this->_printButtonName
, $label);
917 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
918 $this->addElement('submit', $this->_pdfButtonName
, $label);
920 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
922 if ($this->_csvSupported
) {
923 $this->addElement('submit', $this->_csvButtonName
, $label);
926 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
927 $this->addElement('select', 'groups', ts('Group'),
928 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
930 $this->assign('group', TRUE);
933 $label = ts('Add these Contacts to Group');
934 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
936 $this->addChartOptions();
937 $this->addButtons(array(
940 'name' => ts('Preview Report'),
947 function buildQuickForm() {
954 $this->addGroupBys();
956 $this->addOrderBys();
958 $this->buildInstanceAndButtons();
960 //add form rule for report
961 if (is_callable(array(
962 $this, 'formRule'))) {
963 $this->addFormRule(array(get_class($this), 'formRule'), $this);
967 // a formrule function to ensure that fields selected in group_by
968 // (if any) should only be the ones present in display/select fields criteria;
969 // note: works if and only if any custom field selected in group_by.
970 function customDataFormRule($fields, $ignoreFields = array( )) {
972 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
973 foreach ($this->_columns
as $tableName => $table) {
974 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
975 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
976 if (array_key_exists($fieldName, $fields['group_bys']) &&
977 !array_key_exists($fieldName, $fields['fields'])
979 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
981 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
982 foreach ($fields['fields'] as $fld => $val) {
983 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
984 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
995 // Note: $fieldName param allows inheriting class to build operationPairs
996 // specific to a field.
997 function getOperationPair($type = "string", $fieldName = NULL) {
998 // FIXME: At some point we should move these key-val pairs
999 // to option_group and option_value table.
1002 case CRM_Report_FORM
::OP_INT
:
1003 case CRM_Report_FORM
::OP_FLOAT
:
1004 return array('lte' => ts('Is less than or equal to'),
1005 'gte' => ts('Is greater than or equal to'),
1006 'bw' => ts('Is between'),
1007 'eq' => ts('Is equal to'),
1008 'lt' => ts('Is less than'),
1009 'gt' => ts('Is greater than'),
1010 'neq' => ts('Is not equal to'),
1011 'nbw' => ts('Is not between'),
1012 'nll' => ts('Is empty (Null)'),
1013 'nnll' => ts('Is not empty (Null)'),
1017 case CRM_Report_FORM
::OP_SELECT
:
1018 return array('eq' => ts('Is equal to'));
1020 case CRM_Report_FORM
::OP_MONTH
:
1021 case CRM_Report_FORM
::OP_MULTISELECT
:
1022 return array('in' => ts('Is one of'),
1023 'notin' => ts('Is not one of'),
1027 case CRM_Report_FORM
::OP_DATE
:
1028 return array('nll' => ts('Is empty (Null)'),
1029 'nnll' => ts('Is not empty (Null)'),
1033 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1034 // use this operator for the values, concatenated with separator. For e.g if
1035 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1036 return array('mhas' => ts('Is one of'));
1040 return array('has' => ts('Contains'),
1041 'sw' => ts('Starts with'),
1042 'ew' => ts('Ends with'),
1043 'nhas' => ts('Does not contain'),
1044 'eq' => ts('Is equal to'),
1045 'neq' => ts('Is not equal to'),
1046 'nll' => ts('Is empty (Null)'),
1047 'nnll' => ts('Is not empty (Null)'),
1052 function buildTagFilter() {
1053 $contactTags = CRM_Core_BAO_Tag
::getTags();
1054 if (!empty($contactTags)) {
1055 $this->_columns
['civicrm_tag'] = array(
1056 'dao' => 'CRM_Core_DAO_Tag',
1062 'title' => ts('Tag'),
1064 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1065 'options' => $contactTags,
1073 * Adds group filters to _columns (called from _Constuct
1075 function buildGroupFilter() {
1076 $this->_columns
['civicrm_group']['filters'] = array(
1079 'name' => 'group_id',
1080 'title' => ts('Group'),
1081 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1083 'options' => CRM_Core_PseudoConstant
::group(),
1086 if (empty($this->_columns
['civicrm_group']['dao'])) {
1087 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1089 if (empty($this->_columns
['civicrm_group']['alias'])) {
1090 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1094 function getSQLOperator($operator = "like") {
1095 switch ($operator) {
1128 return 'IS NOT NULL';
1136 function whereClause(&$field, $op,
1140 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1146 if (($min !== NULL && strlen($min) > 0) ||
1147 ($max !== NULL && strlen($max) > 0)
1149 $min = CRM_Utils_Type
::escape($min, $type);
1150 $max = CRM_Utils_Type
::escape($max, $type);
1154 $clauses[] = "( {$field['dbAlias']} >= $min )";
1157 $clauses[] = "( {$field['dbAlias']} < $min )";
1162 $clauses[] = "( {$field['dbAlias']} <= $max )";
1165 $clauses[] = "( {$field['dbAlias']} > $max )";
1169 if (!empty($clauses)) {
1171 $clause = implode(' AND ', $clauses);
1174 $clause = implode(' OR ', $clauses);
1182 if ($value !== NULL && strlen($value) > 0) {
1183 $value = CRM_Utils_Type
::escape($value, $type);
1184 if (strpos($value, '%') === FALSE) {
1185 $value = "'%{$value}%'";
1188 $value = "'{$value}'";
1190 $sqlOP = $this->getSQLOperator($op);
1191 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1197 if ($value !== NULL && is_array($value) && count($value) > 0) {
1198 $sqlOP = $this->getSQLOperator($op);
1199 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1200 //cycle through selections and esacape values
1201 foreach ($value as $key => $selection) {
1202 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1204 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1207 // for numerical values
1208 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1210 if ($op == 'notin') {
1211 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1214 $clause = "( " . $clause . " )";
1220 // mhas == multiple has
1221 if ($value !== NULL && count($value) > 0) {
1222 $sqlOP = $this->getSQLOperator($op);
1223 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1229 if ($value !== NULL && strlen($value) > 0) {
1230 $value = CRM_Utils_Type
::escape($value, $type);
1231 if (strpos($value, '%') === FALSE) {
1233 $value = "'{$value}%'";
1236 $value = "'%{$value}'";
1240 $value = "'{$value}'";
1242 $sqlOP = $this->getSQLOperator($op);
1243 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1249 $sqlOP = $this->getSQLOperator($op);
1250 $clause = "( {$field['dbAlias']} $sqlOP )";
1254 if ($value !== NULL && strlen($value) > 0) {
1255 if (isset($field['clause'])) {
1256 // FIXME: we not doing escape here. Better solution is to use two
1257 // different types - data-type and filter-type
1258 eval("\$clause = \"{$field['clause']}\";");
1261 $value = CRM_Utils_Type
::escape($value, $type);
1262 $sqlOP = $this->getSQLOperator($op);
1263 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1264 $value = "'{$value}'";
1266 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1272 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1273 $clause = $this->whereGroupClause($field, $value, $op);
1275 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1276 // not using left join in query because if any contact
1277 // belongs to more than one tag, results duplicate
1279 $clause = $this->whereTagClause($field, $value, $op);
1285 function dateClause($fieldName,
1286 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1289 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1290 $sqlOP = $this->getSQLOperator($relative);
1291 return "( {$fieldName} {$sqlOP} )";
1294 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1297 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1298 $clauses[] = "( {$fieldName} >= $from )";
1302 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1303 $clauses[] = "( {$fieldName} <= {$to} )";
1306 if (!empty($clauses)) {
1307 return implode(' AND ', $clauses);
1313 * @todo - could not find any instances where this is called
1314 * @param unknown_type $relative
1315 * @param String $from
1316 * @param String_type $to
1317 * @return string|NULL
1319 function dateDisplay($relative, $from, $to) {
1320 list($from, $to) = $this->getFromTo($relative, $from, $to);
1323 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1326 $clauses[] = 'Past';
1330 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1333 $clauses[] = 'Today';
1336 if (!empty($clauses)) {
1337 return implode(' - ', $clauses);
1343 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1344 if (empty($totime)) {
1347 //FIX ME not working for relative
1349 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1350 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1351 $from = substr($dateRange['from'], 0, 8);
1352 //Take only Date Part, Sometime Time part is also present in 'to'
1353 $to = substr($dateRange['to'], 0, 8);
1355 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1356 $to = CRM_Utils_Date
::processDate($to, $totime);
1357 return array($from, $to);
1360 function alterDisplay(&$rows) {
1361 // custom code to alter rows
1364 function alterCustomDataDisplay(&$rows) {
1365 // custom code to alter rows having custom values
1366 if (empty($this->_customGroupExtends
)) {
1370 $customFieldIds = array();
1371 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1372 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1373 $customFieldIds[$fieldAlias] = $fieldId;
1376 if (empty($customFieldIds)) {
1380 $customFields = $fieldValueMap = array();
1381 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1383 // skip for type date and ContactReference since date format is already handled
1385 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1386 FROM civicrm_custom_field cf
1387 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1388 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1389 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1390 cg.is_active = 1 AND
1391 cf.is_active = 1 AND
1392 cf.is_searchable = 1 AND
1393 cf.data_type NOT IN ('ContactReference', 'Date') AND
1394 cf.id IN (" . implode(",", $customFieldIds) . ")";
1396 $dao = CRM_Core_DAO
::executeQuery($query);
1397 while ($dao->fetch()) {
1398 foreach ($customFieldCols as $key) {
1399 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1401 if ($dao->option_group_id
) {
1402 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1407 $entryFound = FALSE;
1408 foreach ($rows as $rowNum => $row) {
1409 foreach ($row as $tableCol => $val) {
1410 if (array_key_exists($tableCol, $customFields)) {
1411 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1416 // skip looking further in rows, if first row itself doesn't
1417 // have the column we need
1424 function formatCustomValues($value, $customField, $fieldValueMap) {
1425 if (CRM_Utils_System
::isNull($value)) {
1429 $htmlType = $customField['html_type'];
1431 switch ($customField['data_type']) {
1433 if ($value == '1') {
1434 $retValue = ts('Yes');
1437 $retValue = ts('No');
1442 $retValue = CRM_Utils_System
::formatWikiURL($value);
1454 if ($htmlType == 'Text') {
1455 $retValue = (float)$value;
1459 if ($htmlType == 'Text') {
1469 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1474 if (in_array($htmlType, array(
1475 'Text', 'TextArea'))) {
1479 case 'StateProvince':
1482 switch ($htmlType) {
1483 case 'Multi-Select Country':
1484 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1485 $customData = array();
1486 foreach ($value as $val) {
1488 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1491 $retValue = implode(', ', $customData);
1494 case 'Select Country':
1495 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1498 case 'Select State/Province':
1499 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1502 case 'Multi-Select State/Province':
1503 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1504 $customData = array();
1505 foreach ($value as $val) {
1507 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1510 $retValue = implode(', ', $customData);
1515 case 'Autocomplete-Select':
1516 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1520 case 'AdvMulti-Select':
1521 case 'Multi-Select':
1522 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1523 $customData = array();
1524 foreach ($value as $val) {
1526 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1529 $retValue = implode(', ', $customData);
1544 function removeDuplicates(&$rows) {
1545 if (empty($this->_noRepeats
)) {
1548 $checkList = array();
1550 foreach ($rows as $key => $list) {
1551 foreach ($list as $colName => $colVal) {
1552 if (array_key_exists($colName, $checkList) &&
1553 $checkList[$colName] == $colVal) {
1554 $rows[$key][$colName] = "";
1556 if (in_array($colName, $this->_noRepeats
)) {
1557 $checkList[$colName] = $colVal;
1563 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1564 foreach ($row as $colName => $colVal) {
1565 if (in_array($colName, $fields)) {
1566 $row[$colName] = $row[$colName];
1568 elseif (isset($this->_columnHeaders
[$colName])) {
1570 $row[$colName] = "Subtotal";
1574 unset($row[$colName]);
1580 function grandTotal(&$rows) {
1581 if (!$this->_rollup ||
($this->_rollup
== '') ||
1582 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1586 $lastRow = array_pop($rows);
1588 $this->_grandFlag
= FALSE;
1589 foreach ($this->_columnHeaders
as $fld => $val) {
1590 if (!in_array($fld, $this->_statFields
)) {
1591 if (!$this->_grandFlag
) {
1592 $lastRow[$fld] = "Grand Total";
1593 $this->_grandFlag
= TRUE;
1596 $lastRow[$fld] = "";
1601 $this->assign('grandStat', $lastRow);
1605 function formatDisplay(&$rows, $pager = TRUE) {
1606 // set pager based on if any limit was applied in the query.
1611 // allow building charts if any
1612 if (!empty($this->_params
['charts']) && !empty($rows)) {
1613 $this->buildChart($rows);
1614 $this->assign('chartEnabled', TRUE);
1615 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1616 $this->assign('chartId', $this->_chartId
);
1619 // unset columns not to be displayed.
1620 foreach ($this->_columnHeaders
as $key => $value) {
1621 if (is_array($value) && isset($value['no_display'])) {
1622 unset($this->_columnHeaders
[$key]);
1626 // unset columns not to be displayed.
1627 if (!empty($rows)) {
1628 foreach ($this->_noDisplay
as $noDisplayField) {
1629 foreach ($rows as $rowNum => $row) {
1630 unset($this->_columnHeaders
[$noDisplayField]);
1635 // build array of section totals
1636 $this->sectionTotals();
1638 // process grand-total row
1639 $this->grandTotal($rows);
1641 // use this method for formatting rows for display purpose.
1642 $this->alterDisplay($rows);
1643 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1645 // use this method for formatting custom rows for display purpose.
1646 $this->alterCustomDataDisplay($rows);
1649 function buildChart(&$rows) {
1650 // override this method for building charts.
1653 // select() method below has been added recently (v3.3), and many of the report templates might
1654 // still be having their own select() method. We should fix them as and when encountered and move
1655 // towards generalizing the select() method below.
1659 foreach ($this->_columns
as $tableName => $table) {
1660 if (array_key_exists('fields', $table)) {
1661 foreach ($table['fields'] as $fieldName => $field) {
1662 if ($tableName == 'civicrm_address') {
1663 $this->_addressField
= TRUE;
1665 if ($tableName == 'civicrm_email') {
1666 $this->_emailField
= TRUE;
1668 if ($tableName == 'civicrm_phone') {
1669 $this->_phoneField
= TRUE;
1672 if (CRM_Utils_Array
::value('required', $field) ||
1673 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1676 // 1. In many cases we want select clause to be built in slightly different way
1677 // for a particular field of a particular type.
1678 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1680 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1681 if ($selectClause) {
1682 $select[] = $selectClause;
1686 // include statistics columns only if set
1687 if (CRM_Utils_Array
::value('statistics', $field)) {
1688 foreach ($field['statistics'] as $stat => $label) {
1689 $alias = "{$tableName}_{$fieldName}_{$stat}";
1690 switch (strtolower($stat)) {
1693 $select[] = "$stat({$field['dbAlias']}) as $alias";
1694 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1695 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1696 $this->_statFields
[] = $alias;
1697 $this->_selectAliases
[] = $alias;
1701 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1702 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1703 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1704 $this->_statFields
[] = $alias;
1705 $this->_selectAliases
[] = $alias;
1709 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1710 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1711 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1712 $this->_statFields
[] = $alias;
1713 $this->_selectAliases
[] = $alias;
1719 $alias = "{$tableName}_{$fieldName}";
1720 $select[] = "{$field['dbAlias']} as $alias";
1721 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1722 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1723 $this->_selectAliases
[] = $alias;
1729 // select for group bys
1730 if (array_key_exists('group_bys', $table)) {
1731 foreach ($table['group_bys'] as $fieldName => $field) {
1733 if ($tableName == 'civicrm_address') {
1734 $this->_addressField
= TRUE;
1736 if ($tableName == 'civicrm_email') {
1737 $this->_emailField
= TRUE;
1739 if ($tableName == 'civicrm_phone') {
1740 $this->_phoneField
= TRUE;
1742 // 1. In many cases we want select clause to be built in slightly different way
1743 // for a particular field of a particular type.
1744 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1746 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1747 if ($selectClause) {
1748 $select[] = $selectClause;
1752 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1753 && !empty($this->_params
['group_bys_freq'])) {
1754 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1756 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1757 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1758 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1759 $field['title'] = 'Week';
1763 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1764 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1765 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1766 $field['title'] = 'Year';
1770 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1771 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1772 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1773 $field['title'] = 'Month';
1777 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1778 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1779 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1780 $field['title'] = 'Quarter';
1783 // for graphs and charts -
1784 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1785 $this->_interval
= $field['title'];
1786 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1787 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1788 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1790 // just to make sure these values are transfered to rows.
1791 // since we 'll need them for calculation purpose,
1792 // e.g making subtotals look nicer or graphs
1793 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1794 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1801 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1804 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1809 $this->storeWhereHavingClauseArray();
1811 if (empty($this->_whereClauses
)) {
1812 $this->_where
= "WHERE ( 1 ) ";
1813 $this->_having
= "";
1816 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1819 if ($this->_aclWhere
) {
1820 $this->_where
.= " AND {$this->_aclWhere} ";
1823 if (!empty($this->_havingClauses
)) {
1824 // use this clause to construct group by clause.
1825 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1830 * Store Where clauses into an array - breaking out this step makes
1831 * over-riding more flexible as the clauses can be used in constructing a
1832 * temp table that may not be part of the final where clause or added
1833 * in other functions
1835 function storeWhereHavingClauseArray(){
1836 foreach ($this->_columns
as $tableName => $table) {
1837 if (array_key_exists('filters', $table)) {
1838 foreach ($table['filters'] as $fieldName => $field) {
1839 // respect pseudofield to filter spec so fields can be marked as
1840 // not to be handled here
1841 if(!empty($field['pseudofield'])){
1845 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1846 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1847 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1848 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1849 if (is_array($value) && !empty($value)) {
1850 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1854 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1855 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1856 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1857 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1858 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1859 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1863 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1865 $clause = $this->whereClause($field,
1867 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1868 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1869 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1874 if (!empty($clause)) {
1875 if (CRM_Utils_Array
::value('having', $field)) {
1876 $this->_havingClauses
[] = $clause;
1879 $this->_whereClauses
[] = $clause;
1887 function processReportMode() {
1888 $buttonName = $this->controller
->getButtonName();
1890 $output = CRM_Utils_Request
::retrieve(
1893 CRM_Core_DAO
::$_nullObject
1897 CRM_Utils_Request
::retrieve(
1900 CRM_Core_DAO
::$_nullObject
1903 $this->_absoluteUrl
= FALSE;
1905 $this->assign('printOnly', FALSE);
1907 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1908 $this->assign('printOnly', TRUE);
1910 $this->assign('outputMode', 'print');
1911 $this->_outputMode
= 'print';
1912 if ($this->_sendmail
) {
1913 $this->_absoluteUrl
= TRUE;
1916 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1917 $this->assign('printOnly', TRUE);
1919 $this->assign('outputMode', 'pdf');
1920 $this->_outputMode
= 'pdf';
1921 $this->_absoluteUrl
= TRUE;
1923 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
1924 $this->assign('printOnly', TRUE);
1926 $this->assign('outputMode', 'csv');
1927 $this->_outputMode
= 'csv';
1928 $this->_absoluteUrl
= TRUE;
1930 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
1931 $this->assign('outputMode', 'group');
1932 $this->_outputMode
= 'group';
1934 elseif ($output == 'create_report' && $this->_criteriaForm
) {
1935 $this->assign('outputMode', 'create_report');
1936 $this->_outputMode
= 'create_report';
1939 $this->assign('outputMode', 'html');
1940 $this->_outputMode
= 'html';
1943 // Get today's date to include in printed reports
1945 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
1946 $this->assign('reportDate', $reportDate);
1950 function beginPostProcess() {
1951 $this->_params
= $this->controller
->exportValues($this->_name
);
1953 if (empty($this->_params
) &&
1956 $this->_params
= $this->_formValues
;
1959 // hack to fix params when submitted from dashboard, CRM-8532
1960 // fields array is missing because form building etc is skipped
1961 // in dashboard mode for report
1962 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
1963 $this->_params
= $this->_formValues
;
1966 $this->_formValues
= $this->_params
;
1967 if (CRM_Core_Permission
::check('administer Reports') &&
1968 isset($this->_id
) &&
1969 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
1970 $this->_chartButtonName
== $this->controller
->getButtonName()
1973 $this->assign('updateReportButton', TRUE);
1975 $this->processReportMode();
1978 function buildQuery($applyLimit = TRUE) {
1981 $this->customDataFrom();
1986 // order_by columns not selected for display need to be included in SELECT
1987 $unselectedSectionColumns = $this->unselectedSectionColumns();
1988 foreach ($unselectedSectionColumns as $alias => $section) {
1989 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
1992 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
1995 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
1997 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2001 function groupBy() {
2002 $groupBys = array();
2003 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2004 is_array($this->_params
['group_bys']) &&
2005 !empty($this->_params
['group_bys'])
2007 foreach ($this->_columns
as $tableName => $table) {
2008 if (array_key_exists('group_bys', $table)) {
2009 foreach ($table['group_bys'] as $fieldName => $field) {
2010 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2011 $groupBys[] = $field['dbAlias'];
2018 if (!empty($groupBys)) {
2019 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2023 function orderBy() {
2024 $this->_orderBy
= "";
2025 $this->_sections
= array();
2026 $this->storeOrderByArray();
2027 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2028 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2030 $this->assign('sections', $this->_sections
);
2033 * In some cases other functions want to know which fields are selected for ordering by
2034 * Separating this into a separate function allows it to be called separately from constructing
2035 * the order by clause
2037 function storeOrderByArray() {
2038 $orderBys = array();
2040 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2041 is_array($this->_params
['order_bys']) &&
2042 !empty($this->_params
['order_bys'])
2045 // Proces order_bys in user-specified order
2046 foreach ($this->_params
['order_bys'] as $orderBy) {
2047 $orderByField = array();
2048 foreach ($this->_columns
as $tableName => $table) {
2049 if (array_key_exists('order_bys', $table)) {
2050 // For DAO columns defined in $this->_columns
2051 $fields = $table['order_bys'];
2053 elseif (array_key_exists('extends', $table)) {
2054 // For custom fields referenced in $this->_customGroupExtends
2055 $fields = $table['fields'];
2057 if (!empty($fields) && is_array($fields)) {
2058 foreach ($fields as $fieldName => $field) {
2059 if ($fieldName == $orderBy['column']) {
2060 $orderByField = $field;
2061 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2068 if (!empty($orderByField)) {
2069 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2071 // Record any section headers for assignment to the template
2072 if (CRM_Utils_Array
::value('section', $orderBy)) {
2073 $this->_sections
[$orderByField['tplField']] = $orderByField;
2079 $this->_orderByArray
= $orderBys;
2081 $this->assign('sections', $this->_sections
);
2084 function unselectedSectionColumns() {
2085 $selectColumns = array();
2086 foreach ($this->_columns
as $tableName => $table) {
2087 if (array_key_exists('fields', $table)) {
2088 foreach ($table['fields'] as $fieldName => $field) {
2089 if (CRM_Utils_Array
::value('required', $field) ||
2090 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2093 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2098 if (is_array($this->_sections
)) {
2099 return array_diff_key($this->_sections
, $selectColumns);
2106 function buildRows($sql, &$rows) {
2107 $dao = CRM_Core_DAO
::executeQuery($sql);
2108 if (!is_array($rows)) {
2112 // use this method to modify $this->_columnHeaders
2113 $this->modifyColumnHeaders();
2115 $unselectedSectionColumns = $this->unselectedSectionColumns();
2117 while ($dao->fetch()) {
2119 foreach ($this->_columnHeaders
as $key => $value) {
2120 if (property_exists($dao, $key)) {
2121 $row[$key] = $dao->$key;
2125 // section headers not selected for display need to be added to row
2126 foreach ($unselectedSectionColumns as $key => $values) {
2127 if (property_exists($dao, $key)) {
2128 $row[$key] = $dao->$key;
2137 * When "order by" fields are marked as sections, this assigns to the template
2138 * an array of total counts for each section. This data is used by the Smarty
2139 * plugin {sectionTotal}
2141 function sectionTotals() {
2143 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2144 if (empty($this->_selectAliases
)) {
2148 if (!empty($this->_sections
)) {
2149 // build the query with no LIMIT clause
2150 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2151 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2153 // pull section aliases out of $this->_sections
2154 $sectionAliases = array_keys($this->_sections
);
2157 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2158 $ifnulls[] = "ifnull($alias, '') as $alias";
2161 /* Group (un-limited) report by all aliases and get counts. This might
2162 * be done more efficiently when the contents of $sql are known, ie. by
2163 * overriding this method in the report class.
2167 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2169 // initialize array of total counts
2171 $dao = CRM_Core_DAO
::executeQuery($query);
2172 while ($dao->fetch()) {
2174 // let $this->_alterDisplay translate any integer ids to human-readable values.
2175 $rows[0] = $dao->toArray();
2176 $this->alterDisplay($rows);
2179 // add totals for all permutations of section values
2182 $aliasCount = count($sectionAliases);
2183 foreach ($sectionAliases as $alias) {
2184 $values[] = $row[$alias];
2185 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2186 if ($i == $aliasCount) {
2187 // the last alias is the lowest-level section header; use count as-is
2188 $totals[$key] = $dao->ct
;
2191 // other aliases are higher level; roll count into their total
2192 $totals[$key] +
= $dao->ct
;
2196 $this->assign('sectionTotals', $totals);
2200 function modifyColumnHeaders() {
2201 // use this method to modify $this->_columnHeaders
2204 function doTemplateAssignment(&$rows) {
2205 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2206 $this->assign_by_ref('rows', $rows);
2207 $this->assign('statistics', $this->statistics($rows));
2210 // override this method to build your own statistics
2211 function statistics(&$rows) {
2212 $statistics = array();
2214 $count = count($rows);
2216 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2220 $this->countStat($statistics, $count);
2222 $this->groupByStat($statistics);
2224 $this->filterStat($statistics);
2229 function countStat(&$statistics, $count) {
2230 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2234 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2235 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2236 'value' => $this->_rowsFound
,
2241 function groupByStat(&$statistics) {
2242 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2243 is_array($this->_params
['group_bys']) &&
2244 !empty($this->_params
['group_bys'])
2246 foreach ($this->_columns
as $tableName => $table) {
2247 if (array_key_exists('group_bys', $table)) {
2248 foreach ($table['group_bys'] as $fieldName => $field) {
2249 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2250 $combinations[] = $field['title'];
2255 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2256 'value' => implode(' & ', $combinations),
2261 function filterStat(&$statistics) {
2262 foreach ($this->_columns
as $tableName => $table) {
2263 if (array_key_exists('filters', $table)) {
2264 foreach ($table['filters'] as $fieldName => $field) {
2265 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2268 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2269 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2270 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2271 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2272 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2274 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2275 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2277 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2278 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2281 $statistics['filters'][] = array(
2282 'title' => $field['title'],
2283 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2286 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2287 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2289 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2290 $statistics['filters'][] = array(
2291 'title' => $field['title'],
2292 'value' => $pair[$rel],
2297 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2300 $pair = $this->getOperationPair(
2301 CRM_Utils_Array
::value('operatorType', $field),
2304 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2305 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2306 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2307 if (in_array($op, array(
2308 'bw', 'nbw')) && ($min ||
$max)) {
2309 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2311 elseif ($op == 'nll' ||
$op == 'nnll') {
2312 $value = $pair[$op];
2314 elseif (is_array($val) && (!empty($val))) {
2315 $options = $field['options'];
2316 foreach ($val as $key => $valIds) {
2317 if (isset($options[$valIds])) {
2318 $val[$key] = $options[$valIds];
2321 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : $pair[$op];
2322 $val = implode(', ', $val);
2323 $value = "{$pair[$op]} " . $val;
2325 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2326 is_array($field['options']) && !empty($field['options'])
2328 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2331 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2335 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2345 function endPostProcess(&$rows = NULL) {
2346 if ($this->_outputMode
== 'print' ||
2347 $this->_outputMode
== 'pdf' ||
2351 $content = $this->compileContent();
2352 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2356 if ($this->_sendmail
) {
2357 $config = CRM_Core_Config
::singleton();
2358 $attachments = array();
2360 if ($this->_outputMode
== 'csv') {
2361 $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'];
2363 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2364 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2365 file_put_contents($csvFullFilename, $csvContent);
2366 $attachments[] = array(
2367 'fullPath' => $csvFullFilename,
2368 'mime_type' => 'text/csv',
2369 'cleanName' => 'CiviReport.csv',
2372 if ($this->_outputMode
== 'pdf') {
2373 // generate PDF content
2374 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2375 file_put_contents($pdfFullFilename,
2376 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2377 TRUE, array('orientation' => 'landscape')
2380 // generate Email Content
2381 $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'];
2383 $attachments[] = array(
2384 'fullPath' => $pdfFullFilename,
2385 'mime_type' => 'application/pdf',
2386 'cleanName' => 'CiviReport.pdf',
2390 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2391 $this->_outputMode
, $attachments
2393 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2396 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2399 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2401 elseif ($this->_outputMode
== 'print') {
2405 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2406 $config = CRM_Core_Config
::singleton();
2407 //get chart image name
2408 $chartImg = $this->_chartId
. '.png';
2409 //get image url path
2410 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2411 $uploadUrl .= $chartImg;
2412 //get image doc path to overwrite
2413 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2415 $chart = imagecreatefrompng($uploadUrl);
2416 //convert it into formattd png
2417 header('Content-type: image/png');
2418 //overwrite with same image
2419 imagepng($chart, $uploadImg);
2421 imagedestroy($chart);
2423 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2425 CRM_Utils_System
::civiExit();
2427 elseif ($this->_outputMode
== 'csv') {
2428 CRM_Report_Utils_Report
::export2csv($this, $rows);
2430 elseif ($this->_outputMode
== 'group') {
2431 $group = $this->_params
['groups'];
2432 $this->add2group($group);
2434 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2435 CRM_Report_Form_Instance
::postProcess($this);
2437 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2438 $this->_outputMode
== 'create_report' ) {
2439 $this->_createNew
= TRUE;
2440 CRM_Report_Form_Instance
::postProcess($this);
2445 * Get Template file name - use default form template if a specific one has not been set up for this report
2448 function getTemplateFileName(){
2449 $defaultTpl = parent
::getTemplateFileName();
2450 $template = CRM_Core_Smarty
::singleton();
2451 if (!$template->template_exists($defaultTpl)) {
2452 $defaultTpl = 'CRM/Report/Form.tpl';
2458 * Compile the report content
2460 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2462 function compileContent(){
2463 $templateFile = $this->getTemplateFileName();
2464 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2468 function postProcess() {
2469 // get ready with post process params
2470 $this->beginPostProcess();
2473 $sql = $this->buildQuery();
2475 // build array of result based on column headers. This method also allows
2476 // modifying column headers before using it to build result set i.e $rows.
2478 $this->buildRows($sql, $rows);
2480 // format result set.
2481 $this->formatDisplay($rows);
2483 // assign variables to templates
2484 $this->doTemplateAssignment($rows);
2486 // do print / pdf / instance stuff if needed
2487 $this->endPostProcess($rows);
2490 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2491 // lets do the pager if in html mode
2492 $this->_limit
= NULL;
2493 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2494 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2496 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2498 if (!$pageId && !empty($_POST)) {
2499 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2500 $pageId = max((int)@$_POST['crmPID_B'], 1);
2502 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2503 $pageId = max((int)@$_POST['crmPID'], 1);
2505 unset($_POST['crmPID_B'], $_POST['crmPID']);
2508 $pageId = $pageId ?
$pageId : 1;
2509 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2510 $offset = ($pageId - 1) * $rowCount;
2512 $this->_limit
= " LIMIT $offset, " . $rowCount;
2513 return array($offset, $rowCount);
2517 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2518 if ($this->_limit
&& ($this->_limit
!= '')) {
2519 $sql = "SELECT FOUND_ROWS();";
2520 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2522 'total' => $this->_rowsFound
,
2523 'rowCount' => $rowCount,
2524 'status' => ts('Records') . ' %%StatusMessage%%',
2525 'buttonBottom' => 'PagerBottomButton',
2526 'buttonTop' => 'PagerTopButton',
2527 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2530 $pager = new CRM_Utils_Pager($params);
2531 $this->assign_by_ref('pager', $pager);
2535 function whereGroupClause($field, $value, $op) {
2537 $smartGroupQuery = "";
2539 $group = new CRM_Contact_DAO_Group();
2540 $group->is_active
= 1;
2542 $smartGroups = array();
2543 while ($group->fetch()) {
2544 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2545 $smartGroups[] = $group->id
;
2549 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2551 $smartGroupQuery = '';
2552 if (!empty($smartGroups)) {
2553 $smartGroups = implode(',', $smartGroups);
2554 $smartGroupQuery = " UNION DISTINCT
2555 SELECT DISTINCT smartgroup_contact.contact_id
2556 FROM civicrm_group_contact_cache smartgroup_contact
2557 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2560 $sqlOp = $this->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_group']}.contact_id
2568 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2569 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2570 {$smartGroupQuery} ) ";
2573 function whereTagClause($field, $value, $op) {
2574 // not using left join in query because if any contact
2575 // belongs to more than one tag, results duplicate
2577 $sqlOp = $this->getSQLOperator($op);
2578 if (!is_array($value)) {
2579 $value = array($value);
2581 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2583 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2584 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2585 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2586 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2589 function buildACLClause($tableAlias = 'contact_a') {
2590 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2593 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2594 if (empty($this->_customGroupExtends
)) {
2597 if (!is_array($this->_customGroupExtends
)) {
2598 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2600 $customGroupWhere = '';
2601 if (!empty($permCustomGroupIds)) {
2602 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2605 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2606 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2607 FROM civicrm_custom_group cg
2608 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2609 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2611 cg.is_active = 1 AND
2612 cf.is_active = 1 AND
2613 cf.is_searchable = 1
2614 ORDER BY cg.weight, cf.weight";
2615 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2618 while ($customDAO->fetch()) {
2619 if ($customDAO->table_name
!= $curTable) {
2620 $curTable = $customDAO->table_name
;
2621 $curFields = $curFilters = array();
2624 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2625 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2626 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2627 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2630 'fields', 'filters', 'group_bys') as $colKey) {
2631 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2632 $this->_columns
[$curTable][$colKey] = array();
2636 $fieldName = 'custom_' . $customDAO->cf_id
;
2639 // this makes aliasing work in favor
2640 $curFields[$fieldName] = array(
2641 'name' => $customDAO->column_name
,
2642 'title' => $customDAO->label
,
2643 'dataType' => $customDAO->data_type
,
2644 'htmlType' => $customDAO->html_type
,
2647 if ($this->_customGroupFilters
) {
2648 // this makes aliasing work in favor
2649 $curFilters[$fieldName] = array(
2650 'name' => $customDAO->column_name
,
2651 'title' => $customDAO->label
,
2652 'dataType' => $customDAO->data_type
,
2653 'htmlType' => $customDAO->html_type
,
2657 switch ($customDAO->data_type
) {
2660 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2661 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2662 // CRM-6946, show time part for datetime date fields
2663 if ($customDAO->time_format
) {
2664 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2669 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2670 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2674 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2678 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2679 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2683 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2684 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2688 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2689 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2693 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2695 if (!empty($customDAO->option_group_id
)) {
2696 if (in_array($customDAO->html_type
, array(
2697 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2698 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2701 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2703 if ($this->_customGroupFilters
) {
2704 $curFilters[$fieldName]['options'] = array();
2705 $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')));
2706 while ($ogDAO->fetch()) {
2707 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2713 case 'StateProvince':
2714 if (in_array($customDAO->html_type
, array(
2715 'Multi-Select State/Province'))) {
2716 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2719 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2721 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2725 if (in_array($customDAO->html_type
, array(
2726 'Multi-Select Country'))) {
2727 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2730 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2732 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2735 case 'ContactReference':
2736 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2737 $curFilters[$fieldName]['name'] = 'display_name';
2738 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2740 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2741 $curFields[$fieldName]['name'] = 'display_name';
2742 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2746 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2747 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2750 if (!array_key_exists('type', $curFields[$fieldName])) {
2751 $curFields[$fieldName]['type'] = $curFilters[$fieldName]['type'];
2755 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2757 if ($this->_customGroupFilters
) {
2758 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2760 if ($this->_customGroupGroupBy
) {
2761 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2766 function customDataFrom() {
2767 if (empty($this->_customGroupExtends
)) {
2770 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2772 foreach ($this->_columns
as $table => $prop) {
2773 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2774 $extendsTable = $mapper[$prop['extends']];
2776 // check field is in params
2777 if (!$this->isFieldSelected($prop)) {
2782 LEFT JOIN $table {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2783 // handle for ContactReference
2784 if (array_key_exists('fields', $prop)) {
2785 foreach ($prop['fields'] as $fieldName => $field) {
2786 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2787 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2789 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2797 function isFieldSelected($prop) {
2802 if (!empty($this->_params
['fields'])) {
2803 foreach (array_keys($prop['fields']) as $fieldAlias) {
2804 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2805 if ($customFieldId) {
2806 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2810 //might be survey response field.
2811 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2812 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2820 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2821 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2822 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2828 if (!empty($this->_params
['order_bys'])) {
2829 foreach (array_keys($prop['fields']) as $fieldAlias) {
2830 foreach ($this->_params
['order_bys'] as $orderBy) {
2831 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2838 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2839 foreach ($prop['filters'] as $fieldAlias => $val) {
2841 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2842 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2843 (!empty($this->_params
[$fieldAlias . '_' . $attach]) ||
$this->_params
[$fieldAlias . '_' . $attach] == '0')
2848 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2849 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2860 * Check for empty order_by configurations and remove them; also set
2861 * template to hide them.
2863 function preProcessOrderBy(&$formValues) {
2864 // Object to show/hide form elements
2865 $_showHide = &new CRM_Core_ShowHideBlocks('', '');
2867 $_showHide->addShow('optionField_1');
2869 // Cycle through order_by options; skip any empty ones, and hide them as well
2872 if (!empty($formValues['order_bys'])) {
2873 foreach ($formValues['order_bys'] as $order_by) {
2874 if ($order_by['column'] && $order_by['column'] != '-') {
2875 $_showHide->addShow('optionField_' . $n);
2876 $orderBys[$n] = $order_by;
2881 for ($i = $n; $i <= 5; $i++
) {
2883 $_showHide->addHide('optionField_' . $i);
2887 // overwrite order_by options with modified values
2888 if (!empty($orderBys)) {
2889 $formValues['order_bys'] = $orderBys;
2892 $formValues['order_bys'] = array(1 => array('column' => '-'));
2895 // assign show/hide data to template
2896 $_showHide->addToTemplate();
2900 * Does table name have columns in SELECT clause?
2902 * @param string $tableName Name of table (index of $this->_columns array)
2906 function isTableSelected($tableName) {
2907 return in_array($tableName, $this->selectedTables());
2911 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
2912 * (building the array if it's unset)
2914 * @return Array $this->_selectedTables
2916 function selectedTables() {
2917 if (!$this->_selectedTables
) {
2918 $orderByColumns = array();
2919 if (is_array($this->_params
['order_bys'])) {
2920 foreach ($this->_params
['order_bys'] as $orderBy) {
2921 $orderByColumns[] = $orderBy['column'];
2925 foreach ($this->_columns
as $tableName => $table) {
2926 if (array_key_exists('fields', $table)) {
2927 foreach ($table['fields'] as $fieldName => $field) {
2928 if (CRM_Utils_Array
::value('required', $field) ||
2929 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2931 $this->_selectedTables
[] = $tableName;
2936 if (array_key_exists('order_bys', $table)) {
2937 foreach ($table['order_bys'] as $orderByName => $orderBy) {
2938 if (in_array($orderByName, $orderByColumns)) {
2939 $this->_selectedTables
[] = $tableName;
2944 if (array_key_exists('filters', $table)) {
2945 foreach ($table['filters'] as $filterName => $filter) {
2946 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
2947 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
2948 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
2950 $this->_selectedTables
[] = $tableName;
2957 return $this->_selectedTables
;
2961 * function for adding address fields to construct function in reports
2962 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
2963 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
2964 * @return array address fields for construct clause
2966 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
2967 'country_id' => TRUE)) {
2968 $addressFields = array(
2969 'civicrm_address' =>
2971 'dao' => 'CRM_Core_DAO_Address',
2975 array('title' => ts('Address Name'),
2976 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
2979 array('title' => ts('Street Address'),
2980 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
2982 'supplemental_address_1' =>
2983 array('title' => ts('Supplementary Address Field 1'),
2984 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
2986 'supplemental_address_2' =>
2987 array('title' => ts('Supplementary Address Field 2'),
2988 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
2992 'name' => 'street_number',
2993 'title' => ts('Street Number'),
2995 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
2999 'name' => 'street_name',
3000 'title' => ts('Street Name'),
3002 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3006 'name' => 'street_unit',
3007 'title' => ts('Street Unit'),
3009 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3012 array('title' => ts('City'),
3013 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3016 array('title' => ts('Postal Code'),
3017 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3020 array('title' => ts('County'),
3021 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3023 'state_province_id' =>
3024 array('title' => ts('State/Province'),
3025 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3028 array('title' => ts('Country'),
3029 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3032 'grouping' => 'location-fields',
3037 $addressFields['civicrm_address']['filters'] = array(
3038 'street_number' => array('title' => ts('Street Number'),
3040 'name' => 'street_number',
3042 'street_name' => array('title' => ts('Street Name'),
3043 'name' => 'street_name',
3044 'operator' => 'like',
3046 'postal_code' => array('title' => ts('Postal Code'),
3048 'name' => 'postal_code',
3050 'city' => array('title' => ts('City'),
3051 'operator' => 'like',
3054 'county_id' => array(
3055 'name' => 'county_id',
3056 'title' => ts('County'),
3057 'type' => CRM_Utils_Type
::T_INT
,
3059 CRM_Report_Form
::OP_MULTISELECT
,
3061 CRM_Core_PseudoConstant
::county(),
3063 'state_province_id' => array(
3064 'name' => 'state_province_id',
3065 'title' => ts('State/Province'),
3066 'type' => CRM_Utils_Type
::T_INT
,
3068 CRM_Report_Form
::OP_MULTISELECT
,
3070 CRM_Core_PseudoConstant
::stateProvince(),
3072 'country_id' => array(
3073 'name' => 'country_id',
3074 'title' => ts('Country'),
3075 'type' => CRM_Utils_Type
::T_INT
,
3077 CRM_Report_Form
::OP_MULTISELECT
,
3079 CRM_Core_PseudoConstant
::country(),
3085 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3086 'street_number' => array('title' => 'Odd / Even Street Number'),
3087 'street_address' => NULL,
3089 'postal_code' => NULL,
3094 $addressFields['civicrm_address']['group_bys'] = array(
3095 'street_address' => NULL,
3097 'postal_code' => NULL,
3098 'state_province_id' =>
3099 array('title' => ts('State/Province'),
3102 array('title' => ts('Country'),
3105 array('title' => ts('County'),
3109 return $addressFields;
3113 * Do AlterDisplay processing on Address Fields
3115 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3116 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3117 $entryFound = FALSE;
3119 if (array_key_exists('civicrm_address_country_id', $row)) {
3120 if ($value = $row['civicrm_address_country_id']) {
3121 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3122 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3123 "reset=1&force=1&{$criteriaQueryParams}&" .
3124 "country_id_op=in&country_id_value={$value}",
3125 $this->_absoluteUrl
, $this->_id
3127 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3128 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3135 if (array_key_exists('civicrm_address_county_id', $row)) {
3136 if ($value = $row['civicrm_address_county_id']) {
3137 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3138 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3139 "reset=1&force=1&{$criteriaQueryParams}&" .
3140 "county_id_op=in&county_id_value={$value}",
3141 $this->_absoluteUrl
, $this->_id
3143 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3144 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3150 // handle state province
3151 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3152 if ($value = $row['civicrm_address_state_province_id']) {
3153 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3155 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3156 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3157 $this->_absoluteUrl
, $this->_id
3159 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3160 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3171 * Adjusts dates passed in to YEAR() for fiscal year.
3173 function fiscalYearOffset($fieldName) {
3174 $config = CRM_Core_Config
::singleton();
3175 $fy = $config->fiscalYearStart
;
3176 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3177 return "YEAR( $fieldName )";
3179 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3183 * Add Address into From Table if required
3185 function addAddressFromClause() {
3186 // include address field if address column is to be included
3187 if ((isset($this->_addressField
) &&
3188 $this->_addressField
3190 $this->isTableSelected('civicrm_address')
3193 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3194 ON ({$this->_aliases['civicrm_contact']}.id =
3195 {$this->_aliases['civicrm_address']}.contact_id) AND
3196 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3200 function add2group($groupID) {
3201 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3202 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3203 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3205 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3206 $dao = CRM_Core_DAO
::executeQuery($sql);
3208 $contact_ids = array();
3209 // Add resulting contacts to group
3210 while ($dao->fetch()) {
3211 if ($dao->addtogroup_contact_id
) {
3212 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3216 if ( !empty($contact_ids) ) {
3217 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3218 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3221 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));