3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 CONST ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
53 * The id of the report instance
60 * The id of the report template
64 protected $_templateID;
72 protected $_noFields = FALSE;
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attribues as the value
80 protected $_columns = array();
83 * The set of filters in the report
87 protected $_filters = array();
90 * The set of optional columns in the report
94 protected $_options = array();
96 protected $_defaults = array();
99 * By default most reports hide contact id.
100 * Setting this to true makes it available
102 protected $_exposeContactID = TRUE;
105 * Set of statistic fields
109 protected $_statFields = array();
112 * Set of statistics data
116 protected $_statistics = array();
119 * List of fields not to be repeated during display
123 protected $_noRepeats = array();
126 * List of fields not to be displayed
130 protected $_noDisplay = array();
133 * Object type that a custom group extends
137 protected $_customGroupExtends = NULL;
138 protected $_customGroupFilters = TRUE;
139 protected $_customGroupGroupBy = FALSE;
140 protected $_customGroupJoin = 'LEFT JOIN';
146 protected $_tagFilter = FALSE;
149 * build groups filter
152 protected $_groupFilter = FALSE;
159 public $_navigation = array();
161 public $_drilldownReport = array();
164 * An attribute for checkbox/radio form field layout
168 protected $_fourColumnAttribute = array(
169 '</td><td width="25%">', '</td><td width="25%">',
170 '</td><td width="25%">', '</tr><tr><td>',
173 protected $_force = 1;
175 protected $_params = NULL;
176 protected $_formValues = NULL;
177 protected $_instanceValues = NULL;
179 protected $_instanceForm = FALSE;
180 protected $_criteriaForm = FALSE;
182 protected $_instanceButtonName = NULL;
183 protected $_createNewButtonName = NULL;
184 protected $_printButtonName = NULL;
185 protected $_pdfButtonName = NULL;
186 protected $_csvButtonName = NULL;
187 protected $_groupButtonName = NULL;
188 protected $_chartButtonName = NULL;
189 protected $_csvSupported = TRUE;
190 protected $_add2groupSupported = TRUE;
191 protected $_groups = NULL;
192 protected $_grandFlag = FALSE;
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 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
206 protected $_storeResultSet = FALSE;
209 * When _storeResultSet Flag is set use this var to store result set in form of array
213 protected $_resultSet = array();
216 * To what frequency group-by a date column
220 protected $_groupByDateFreq = array(
222 'YEARWEEK' => 'Week',
223 'QUARTER' => 'Quarter',
228 * Variables to hold the acl inner join and where clause
230 protected $_aclFrom = NULL;
231 protected $_aclWhere = NULL;
234 * Array of DAO tables having columns included in SELECT or ORDER BY clause
238 protected $_selectedTables;
240 public $_having = NULL;
241 public $_select = NULL;
242 public $_columnHeaders = array();
243 public $_orderBy = NULL;
244 public $_groupBy = NULL;
245 public $_whereClauses = array();
246 public $_havingClauses = array();
249 * Variable to hold the currency alias
251 protected $_currencyColumn = NULL;
256 function __construct() {
257 parent
::__construct();
260 if ($this->_tagFilter
) {
261 $this->buildTagFilter();
263 if ($this->_exposeContactID
) {
264 if (array_key_exists('civicrm_contact', $this->_columns
)) {
265 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
267 'title' => 'Contact ID',
273 if ($this->_groupFilter
) {
274 $this->buildGroupFilter();
277 // Get all custom groups
278 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
280 // Get the custom groupIds for which the user have VIEW permission
281 require_once 'CRM/ACL/API.php';
282 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
284 // do not allow custom data for reports if user don't have
285 // permission to access custom data.
286 if (!empty($this->_customGroupExtends
) && !CRM_Core_Permission
::check('access all custom data') && empty($permCustomGroupIds)) {
287 $this->_customGroupExtends
= array();
290 // merge custom data columns to _columns list, if any
291 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
293 // add / modify display columns, filters ..etc
294 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
296 //assign currencyColumn variable to tpl
297 $this->assign('currencyColumn', $this->_currencyColumn
);
300 function preProcessCommon() {
302 CRM_Utils_Request
::retrieve(
305 CRM_Core_DAO
::$_nullObject
308 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
310 $this->assign('section', $this->_section
);
311 CRM_Core_Region
::instance('page-header')->add(array(
312 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
315 $this->_id
= $this->get('instanceId');
317 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
319 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
323 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
324 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
325 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
328 $this->assign('instanceId', $this->_id
);
329 $params = array('id' => $this->_id
);
330 $this->_instanceValues
= array();
331 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
333 $this->_instanceValues
335 if (empty($this->_instanceValues
)) {
336 CRM_Core_Error
::fatal("Report could not be loaded.");
339 if (!empty($this->_instanceValues
['permission']) &&
340 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
341 CRM_Core_Permission
::check('administer Reports')
344 CRM_Utils_System
::permissionDenied();
345 CRM_Utils_System
::civiExit();
348 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
350 $this->_formValues
= unserialize($formValues);
353 $this->_formValues
= NULL;
356 // lets always do a force if reset is found in the url.
357 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
362 $this->assign('mode', 'instance');
365 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
366 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
367 if (($instanceCount > 0) && $optionValueID) {
368 $this->assign('instanceUrl',
369 CRM_Utils_System
::url('civicrm/report/list',
370 "reset=1&ovid=$optionValueID"
374 if ($optionValueID) {
375 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
379 $this->assign('mode', 'template');
382 // lets display the Report Settings section
383 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
385 // Do not display Report Settings section if administer Reports permission is absent OR
386 // if report instance is reserved and administer reserved reports absent
387 if (!CRM_Core_Permission
::check('administer Reports') ||
388 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
389 $this->_instanceForm
= FALSE;
392 $this->assign('criteriaForm', FALSE);
393 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
394 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
395 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
396 $this->assign('criteriaForm', TRUE);
397 $this->_criteriaForm
= TRUE;
401 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
402 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
403 $this->_printButtonName
= $this->getButtonName('submit', 'print');
404 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
405 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
406 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
407 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
410 function addBreadCrumb() {
414 'title' => ts('Report Templates'),
415 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
419 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
422 function preProcess() {
423 $this->preProcessCommon();
426 $this->addBreadCrumb();
429 foreach ($this->_columns
as $tableName => $table) {
431 if (!isset($table['alias'])) {
432 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
435 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
438 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
440 // higher preference to bao object
441 if (array_key_exists('bao', $table)) {
442 $baoName = $table['bao'];
443 $expFields = $baoName::exportableFields( );
445 elseif (array_key_exists('dao', $table)){
446 $daoName = $table['dao'];
447 $expFields = $daoName::export( );
450 $expFields = array();
453 $doNotCopy = array('required');
455 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
456 foreach ($fieldGroups as $fieldGrp) {
457 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
458 foreach ($table[$fieldGrp] as $fieldName => $field) {
459 // $name is the field name used to reference the BAO/DAO export fields array
460 $name = isset($field['name']) ?
$field['name'] : $fieldName;
462 // Sometimes the field name key in the BAO/DAO export fields array is
463 // different from the actual database field name.
464 // Unset $field['name'] so that actual database field name can be obtained
465 // from the BAO/DAO export fields array.
466 unset($field['name']);
468 if (array_key_exists($name, $expFields)) {
469 foreach ($doNotCopy as $dnc) {
470 // unset the values we don't want to be copied.
471 unset($expFields[$name][$dnc]);
474 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
477 foreach ($expFields[$name] as $property => $val) {
478 if (!array_key_exists($property, $field)) {
479 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
486 if (CRM_Utils_Array
::value('no_repeat', $field)) {
487 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
489 if (CRM_Utils_Array
::value('no_display', $field)) {
490 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
493 // set alias = table-name, unless already set
494 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
495 $this->_columns
[$tableName]['alias'] : $tableName
497 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
499 // set name = fieldName, unless already set
500 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
501 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
504 // set dbAlias = alias.name, unless already set
505 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
506 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
509 if (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName]) &&
510 !isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'])
512 if (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
513 array(CRM_Utils_Type
::T_MONEY
, CRM_Utils_Type
::T_FLOAT
)
515 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
517 elseif (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
518 array(CRM_Utils_Type
::T_INT
)
520 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
527 // copy filters to a separate handy variable
528 if (array_key_exists('filters', $table)) {
529 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
532 if (array_key_exists('group_bys', $table)) {
533 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
536 if (array_key_exists('fields', $table)) {
537 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
542 $this->setDefaultValues(FALSE);
545 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
546 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
547 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
548 CRM_Report_Utils_Get
::processChart($this->_defaults
);
551 $this->_formValues
= $this->_defaults
;
552 $this->postProcess();
556 function setDefaultValues($freeze = TRUE) {
557 $freezeGroup = array();
559 // FIXME: generalizing form field naming conventions would reduce
560 // lots of lines below.
561 foreach ($this->_columns
as $tableName => $table) {
562 if (array_key_exists('fields', $table)) {
563 foreach ($table['fields'] as $fieldName => $field) {
564 if (!array_key_exists('no_display', $field)) {
565 if (isset($field['required'])) {
567 $this->_defaults
['fields'][$fieldName] = 1;
570 // find element object, so that we could use quickform's freeze method
571 // for required elements
572 $obj = $this->getElementFromGroup("fields", $fieldName);
574 $freezeGroup[] = $obj;
578 elseif (isset($field['default'])) {
579 $this->_defaults
['fields'][$fieldName] = $field['default'];
585 if (array_key_exists('group_bys', $table)) {
586 foreach ($table['group_bys'] as $fieldName => $field) {
587 if (isset($field['default'])) {
588 if (CRM_Utils_Array
::value('frequency', $field)) {
589 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
591 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
595 if (array_key_exists('filters', $table)) {
596 foreach ($table['filters'] as $fieldName => $field) {
597 if (isset($field['default'])) {
598 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
599 if(is_array($field['default'])){
600 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
601 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
602 $this->_defaults
["{$fieldName}_relative"] = 0;
605 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
609 $this->_defaults
["{$fieldName}_value"] = $field['default'];
612 //assign default value as "in" for multiselect
613 //operator, To freeze the select element
614 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
615 $this->_defaults
["{$fieldName}_op"] = 'in';
617 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
618 $this->_defaults
["{$fieldName}_op"] = 'mhas';
620 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
621 $this->_defaults
["{$fieldName}_op"] = $op;
627 array_key_exists('order_bys', $table) &&
628 is_array($table['order_bys'])
630 if (!array_key_exists('order_bys', $this->_defaults
)) {
631 $this->_defaults
['order_bys'] = array();
633 foreach ($table['order_bys'] as $fieldName => $field) {
635 CRM_Utils_Array
::value('default', $field) ||
636 CRM_Utils_Array
::value('default_order', $field) ||
637 CRM_Utils_Array
::value('default_is_section', $field) ||
638 CRM_Utils_Array
::value('default_weight', $field)
641 'column' => $fieldName,
642 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
643 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
646 if (CRM_Utils_Array
::value('default_weight', $field)) {
647 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
650 array_unshift($this->_defaults
['order_bys'], $order_by);
656 foreach ($this->_options
as $fieldName => $field) {
657 if (isset($field['default'])) {
658 $this->_defaults
['options'][$fieldName] = $field['default'];
663 if (!empty($this->_submitValues
)) {
664 $this->preProcessOrderBy($this->_submitValues
);
667 $this->preProcessOrderBy($this->_defaults
);
670 // lets finish freezing task here itself
671 if (!empty($freezeGroup)) {
672 foreach ($freezeGroup as $elem) {
677 if ($this->_formValues
) {
678 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
681 if ($this->_instanceValues
) {
682 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
685 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
687 return $this->_defaults
;
690 function getElementFromGroup($group, $grpFieldName) {
691 $eleObj = $this->getElement($group);
692 foreach ($eleObj->_elements
as $index => $obj) {
693 if ($grpFieldName == $obj->_attributes
['name']) {
700 function addColumns() {
703 foreach ($this->_columns
as $tableName => $table) {
704 if (array_key_exists('fields', $table)) {
705 foreach ($table['fields'] as $fieldName => $field) {
707 if (!array_key_exists('no_display', $field)) {
708 foreach ( array('table', 'field') as $var) {
709 if (!empty($
{$var}['grouping'])) {
710 if (!is_array($
{$var}['grouping'])) {
711 $tableName = $
{$var}['grouping'];
713 $tableName = array_keys($
{$var}['grouping']);
714 $tableName = $tableName[0];
715 $groupTitle = array_values($
{$var}['grouping']);
716 $groupTitle = $groupTitle[0];
721 if (!$groupTitle && isset($table['group_title'])) {
722 $groupTitle = $table['group_title'];
725 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
726 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
727 $colGroups[$tableName]['group_title'] = $groupTitle;
730 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
736 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
737 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
739 $this->assign('colGroups', $colGroups);
742 function addFilters() {
743 $options = $filters = array();
745 foreach ($this->_filters
as $table => $attributes) {
746 foreach ($attributes as $fieldName => $field) {
747 // get ready with option value pair
748 // @ 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
750 $operations = $this->getOperationPair(
751 CRM_Utils_Array
::value('operatorType', $field),
754 $filters[$table][$fieldName] = $field;
756 switch (CRM_Utils_Array
::value('operatorType', $field)) {
757 case CRM_Report_Form
::OP_MONTH
:
758 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
759 // If there's no option list for this filter, define one.
760 $field['options'] = array(
769 9 => ts('September'),
771 11 => ts('November'),
772 12 => ts('December'),
774 // Add this option list to this column _columns. This is
775 // required so that filter statistics show properly.
776 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
778 case CRM_Report_FORM
::OP_MULTISELECT
:
779 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
780 // assume a multi-select field
781 if (!empty($field['options'])) {
782 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
783 if (count($operations) <= 1) {
786 $select = $this->addElement('select', "{$fieldName}_value", NULL,
787 $field['options'], array(
789 'style' => 'min-width:250px',
792 $select->setMultiple(TRUE);
796 case CRM_Report_FORM
::OP_SELECT
:
797 // assume a select field
798 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
799 if (!empty($field['options']))
800 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
803 case CRM_Report_FORM
::OP_DATE
:
804 // build datetime fields
805 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
809 case CRM_Report_FORM
::OP_DATETIME
:
810 // build datetime fields
811 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
815 case CRM_Report_FORM
::OP_INT
:
816 case CRM_Report_FORM
::OP_FLOAT
:
817 // and a min value input box
818 $this->add('text', "{$fieldName}_min", ts('Min'));
819 // and a max value input box
820 $this->add('text', "{$fieldName}_max", ts('Max'));
822 // default type is string
823 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
824 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
826 // we need text box for value input
827 $this->add('text', "{$fieldName}_value", NULL);
832 $this->assign('filters', $filters);
835 function addOptions() {
836 if (!empty($this->_options
)) {
837 // FIXME: For now lets build all elements as checkboxes.
838 // Once we clear with the format we can build elements based on type
841 foreach ($this->_options
as $fieldName => $field) {
842 if ($field['type'] == 'select') {
843 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
845 else if ($field['type'] == 'checkbox') {
846 $options[$field['title']] = $fieldName;
847 $this->addCheckBox($fieldName, NULL,
849 NULL, NULL, NULL, $this->_fourColumnAttribute
854 $this->assign('otherOptions', $this->_options
);
857 function addChartOptions() {
858 if (!empty($this->_charts
)) {
859 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
860 $this->assign('charts', $this->_charts
);
861 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
865 function addGroupBys() {
866 $options = $freqElements = array();
868 foreach ($this->_columns
as $tableName => $table) {
869 if (array_key_exists('group_bys', $table)) {
870 foreach ($table['group_bys'] as $fieldName => $field) {
871 if (!empty($field)) {
872 $options[$field['title']] = $fieldName;
873 if (CRM_Utils_Array
::value('frequency', $field)) {
874 $freqElements[$field['title']] = $fieldName;
880 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
881 NULL, NULL, NULL, $this->_fourColumnAttribute
883 $this->assign('groupByElements', $options);
885 foreach ($freqElements as $name) {
886 $this->addElement('select', "group_bys_freq[$name]",
887 ts('Frequency'), $this->_groupByDateFreq
892 function addOrderBys() {
894 foreach ($this->_columns
as $tableName => $table) {
896 // Report developer may define any column to order by; include these as order-by options
897 if (array_key_exists('order_bys', $table)) {
898 foreach ($table['order_bys'] as $fieldName => $field) {
899 if (!empty($field)) {
900 $options[$fieldName] = $field['title'];
905 /* Add searchable custom fields as order-by options, if so requested
906 * (These are already indexed, so allowing to order on them is cheap.)
910 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
911 foreach ($table['fields'] as $fieldName => $field) {
912 if (!array_key_exists('no_display', $field)) {
913 $options[$fieldName] = $field['title'];
921 $this->assign('orderByOptions', $options);
923 if (!empty($options)) {
925 '-' => ' - none - ') +
$options;
926 for ($i = 1; $i <= 5; $i++
) {
927 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
928 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
929 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
934 function buildInstanceAndButtons() {
935 CRM_Report_Form_Instance
::buildForm($this);
937 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
939 $this->addElement('submit', $this->_instanceButtonName
, $label);
940 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
941 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
944 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
946 if ($this->_instanceForm
) {
947 $this->assign('instanceForm', TRUE);
950 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
951 $this->addElement('submit', $this->_printButtonName
, $label);
953 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
954 $this->addElement('submit', $this->_pdfButtonName
, $label);
956 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
958 if ($this->_csvSupported
) {
959 $this->addElement('submit', $this->_csvButtonName
, $label);
962 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
963 $this->addElement('select', 'groups', ts('Group'),
964 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
966 $this->assign('group', TRUE);
969 $label = ts('Add these Contacts to Group');
970 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
972 $this->addChartOptions();
973 $this->addButtons(array(
976 'name' => ts('Preview Report'),
983 function buildQuickForm() {
990 $this->addGroupBys();
992 $this->addOrderBys();
994 $this->buildInstanceAndButtons();
996 //add form rule for report
997 if (is_callable(array(
998 $this, 'formRule'))) {
999 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1003 // a formrule function to ensure that fields selected in group_by
1004 // (if any) should only be the ones present in display/select fields criteria;
1005 // note: works if and only if any custom field selected in group_by.
1006 function customDataFormRule($fields, $ignoreFields = array( )) {
1008 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1009 foreach ($this->_columns
as $tableName => $table) {
1010 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1011 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1012 if (array_key_exists($fieldName, $fields['group_bys']) &&
1013 !array_key_exists($fieldName, $fields['fields'])
1015 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1017 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1018 foreach ($fields['fields'] as $fld => $val) {
1019 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1020 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1031 // Note: $fieldName param allows inheriting class to build operationPairs
1032 // specific to a field.
1033 function getOperationPair($type = "string", $fieldName = NULL) {
1034 // FIXME: At some point we should move these key-val pairs
1035 // to option_group and option_value table.
1037 case CRM_Report_FORM
::OP_INT
:
1038 case CRM_Report_FORM
::OP_FLOAT
:
1040 'lte' => ts('Is less than or equal to'),
1041 'gte' => ts('Is greater than or equal to'),
1042 'bw' => ts('Is between'),
1043 'eq' => ts('Is equal to'),
1044 'lt' => ts('Is less than'),
1045 'gt' => ts('Is greater than'),
1046 'neq' => ts('Is not equal to'),
1047 'nbw' => ts('Is not between'),
1048 'nll' => ts('Is empty (Null)'),
1049 'nnll' => ts('Is not empty (Null)'),
1053 case CRM_Report_FORM
::OP_SELECT
:
1055 'eq' => ts('Is equal to'),
1058 case CRM_Report_FORM
::OP_MONTH
:
1059 case CRM_Report_FORM
::OP_MULTISELECT
:
1061 'in' => ts('Is one of'),
1062 'notin' => ts('Is not one of'),
1066 case CRM_Report_FORM
::OP_DATE
:
1068 'nll' => ts('Is empty (Null)'),
1069 'nnll' => ts('Is not empty (Null)'),
1073 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1074 // use this operator for the values, concatenated with separator. For e.g if
1075 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1077 'mhas' => ts('Is one of'),
1083 'has' => ts('Contains'),
1084 'sw' => ts('Starts with'),
1085 'ew' => ts('Ends with'),
1086 'nhas' => ts('Does not contain'),
1087 'eq' => ts('Is equal to'),
1088 'neq' => ts('Is not equal to'),
1089 'nll' => ts('Is empty (Null)'),
1090 'nnll' => ts('Is not empty (Null)'),
1095 function buildTagFilter() {
1096 $contactTags = CRM_Core_BAO_Tag
::getTags();
1097 if (!empty($contactTags)) {
1098 $this->_columns
['civicrm_tag'] = array(
1099 'dao' => 'CRM_Core_DAO_Tag',
1105 'title' => ts('Tag'),
1107 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1108 'options' => $contactTags,
1116 * Adds group filters to _columns (called from _Constuct
1118 function buildGroupFilter() {
1119 $this->_columns
['civicrm_group']['filters'] = array(
1122 'name' => 'group_id',
1123 'title' => ts('Group'),
1124 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1126 'options' => CRM_Core_PseudoConstant
::group(),
1129 if (empty($this->_columns
['civicrm_group']['dao'])) {
1130 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1132 if (empty($this->_columns
['civicrm_group']['alias'])) {
1133 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1137 function getSQLOperator($operator = "like") {
1138 switch ($operator) {
1171 return 'IS NOT NULL';
1179 function whereClause(&$field, $op,
1183 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1189 if (($min !== NULL && strlen($min) > 0) ||
1190 ($max !== NULL && strlen($max) > 0)
1192 $min = CRM_Utils_Type
::escape($min, $type);
1193 $max = CRM_Utils_Type
::escape($max, $type);
1197 $clauses[] = "( {$field['dbAlias']} >= $min )";
1200 $clauses[] = "( {$field['dbAlias']} < $min )";
1205 $clauses[] = "( {$field['dbAlias']} <= $max )";
1208 $clauses[] = "( {$field['dbAlias']} > $max )";
1212 if (!empty($clauses)) {
1214 $clause = implode(' AND ', $clauses);
1217 $clause = implode(' OR ', $clauses);
1225 if ($value !== NULL && strlen($value) > 0) {
1226 $value = CRM_Utils_Type
::escape($value, $type);
1227 if (strpos($value, '%') === FALSE) {
1228 $value = "'%{$value}%'";
1231 $value = "'{$value}'";
1233 $sqlOP = $this->getSQLOperator($op);
1234 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1240 if ($value !== NULL && is_array($value) && count($value) > 0) {
1241 $sqlOP = $this->getSQLOperator($op);
1242 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1243 //cycle through selections and esacape values
1244 foreach ($value as $key => $selection) {
1245 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1247 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1250 // for numerical values
1251 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1253 if ($op == 'notin') {
1254 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1257 $clause = "( " . $clause . " )";
1263 // mhas == multiple has
1264 if ($value !== NULL && count($value) > 0) {
1265 $sqlOP = $this->getSQLOperator($op);
1266 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1272 if ($value !== NULL && strlen($value) > 0) {
1273 $value = CRM_Utils_Type
::escape($value, $type);
1274 if (strpos($value, '%') === FALSE) {
1276 $value = "'{$value}%'";
1279 $value = "'%{$value}'";
1283 $value = "'{$value}'";
1285 $sqlOP = $this->getSQLOperator($op);
1286 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1292 $sqlOP = $this->getSQLOperator($op);
1293 $clause = "( {$field['dbAlias']} $sqlOP )";
1297 if ($value !== NULL && strlen($value) > 0) {
1298 if (isset($field['clause'])) {
1299 // FIXME: we not doing escape here. Better solution is to use two
1300 // different types - data-type and filter-type
1301 $clause = $field['clause'];
1304 $value = CRM_Utils_Type
::escape($value, $type);
1305 $sqlOP = $this->getSQLOperator($op);
1306 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1307 $value = "'{$value}'";
1309 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1315 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1316 $clause = $this->whereGroupClause($field, $value, $op);
1318 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1319 // not using left join in query because if any contact
1320 // belongs to more than one tag, results duplicate
1322 $clause = $this->whereTagClause($field, $value, $op);
1328 function dateClause($fieldName,
1329 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1332 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1333 $sqlOP = $this->getSQLOperator($relative);
1334 return "( {$fieldName} {$sqlOP} )";
1337 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1340 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1341 $clauses[] = "( {$fieldName} >= $from )";
1345 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1346 $clauses[] = "( {$fieldName} <= {$to} )";
1349 if (!empty($clauses)) {
1350 return implode(' AND ', $clauses);
1356 * @todo - could not find any instances where this is called
1357 * @param unknown_type $relative
1358 * @param String $from
1359 * @param String_type $to
1360 * @return string|NULL
1362 function dateDisplay($relative, $from, $to) {
1363 list($from, $to) = $this->getFromTo($relative, $from, $to);
1366 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1369 $clauses[] = 'Past';
1373 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1376 $clauses[] = 'Today';
1379 if (!empty($clauses)) {
1380 return implode(' - ', $clauses);
1386 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1387 if (empty($totime)) {
1390 //FIX ME not working for relative
1392 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1393 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1394 $from = substr($dateRange['from'], 0, 8);
1395 //Take only Date Part, Sometime Time part is also present in 'to'
1396 $to = substr($dateRange['to'], 0, 8);
1398 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1399 $to = CRM_Utils_Date
::processDate($to, $totime);
1400 return array($from, $to);
1403 function alterDisplay(&$rows) {
1404 // custom code to alter rows
1407 function alterCustomDataDisplay(&$rows) {
1408 // custom code to alter rows having custom values
1409 if (empty($this->_customGroupExtends
)) {
1413 $customFieldIds = array();
1414 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1415 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1416 $customFieldIds[$fieldAlias] = $fieldId;
1419 if (empty($customFieldIds)) {
1423 $customFields = $fieldValueMap = array();
1424 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1426 // skip for type date and ContactReference since date format is already handled
1428 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1429 FROM civicrm_custom_field cf
1430 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1431 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1432 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1433 cg.is_active = 1 AND
1434 cf.is_active = 1 AND
1435 cf.is_searchable = 1 AND
1436 cf.data_type NOT IN ('ContactReference', 'Date') AND
1437 cf.id IN (" . implode(",", $customFieldIds) . ")";
1439 $dao = CRM_Core_DAO
::executeQuery($query);
1440 while ($dao->fetch()) {
1441 foreach ($customFieldCols as $key) {
1442 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1444 if ($dao->option_group_id
) {
1445 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1450 $entryFound = FALSE;
1451 foreach ($rows as $rowNum => $row) {
1452 foreach ($row as $tableCol => $val) {
1453 if (array_key_exists($tableCol, $customFields)) {
1454 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1459 // skip looking further in rows, if first row itself doesn't
1460 // have the column we need
1467 function formatCustomValues($value, $customField, $fieldValueMap) {
1468 if (CRM_Utils_System
::isNull($value)) {
1472 $htmlType = $customField['html_type'];
1474 switch ($customField['data_type']) {
1476 if ($value == '1') {
1477 $retValue = ts('Yes');
1480 $retValue = ts('No');
1485 $retValue = CRM_Utils_System
::formatWikiURL($value);
1497 if ($htmlType == 'Text') {
1498 $retValue = (float)$value;
1502 if ($htmlType == 'Text') {
1512 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1517 if (in_array($htmlType, array(
1518 'Text', 'TextArea'))) {
1522 case 'StateProvince':
1525 switch ($htmlType) {
1526 case 'Multi-Select Country':
1527 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1528 $customData = array();
1529 foreach ($value as $val) {
1531 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1534 $retValue = implode(', ', $customData);
1537 case 'Select Country':
1538 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1541 case 'Select State/Province':
1542 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1545 case 'Multi-Select State/Province':
1546 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1547 $customData = array();
1548 foreach ($value as $val) {
1550 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1553 $retValue = implode(', ', $customData);
1558 case 'Autocomplete-Select':
1559 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1563 case 'AdvMulti-Select':
1564 case 'Multi-Select':
1565 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1566 $customData = array();
1567 foreach ($value as $val) {
1569 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1572 $retValue = implode(', ', $customData);
1587 function removeDuplicates(&$rows) {
1588 if (empty($this->_noRepeats
)) {
1591 $checkList = array();
1593 foreach ($rows as $key => $list) {
1594 foreach ($list as $colName => $colVal) {
1595 if (array_key_exists($colName, $checkList) &&
1596 $checkList[$colName] == $colVal) {
1597 $rows[$key][$colName] = "";
1599 if (in_array($colName, $this->_noRepeats
)) {
1600 $checkList[$colName] = $colVal;
1606 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1607 foreach ($row as $colName => $colVal) {
1608 if (in_array($colName, $fields)) {
1609 $row[$colName] = $row[$colName];
1611 elseif (isset($this->_columnHeaders
[$colName])) {
1613 $row[$colName] = "Subtotal";
1617 unset($row[$colName]);
1623 function grandTotal(&$rows) {
1624 if (!$this->_rollup ||
($this->_rollup
== '') ||
1625 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1629 $lastRow = array_pop($rows);
1631 foreach ($this->_columnHeaders
as $fld => $val) {
1632 if (!in_array($fld, $this->_statFields
)) {
1633 if (!$this->_grandFlag
) {
1634 $lastRow[$fld] = "Grand Total";
1635 $this->_grandFlag
= TRUE;
1638 $lastRow[$fld] = "";
1643 $this->assign('grandStat', $lastRow);
1647 function formatDisplay(&$rows, $pager = TRUE) {
1648 // set pager based on if any limit was applied in the query.
1653 // allow building charts if any
1654 if (!empty($this->_params
['charts']) && !empty($rows)) {
1655 $this->buildChart($rows);
1656 $this->assign('chartEnabled', TRUE);
1657 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1658 $this->assign('chartId', $this->_chartId
);
1661 // unset columns not to be displayed.
1662 foreach ($this->_columnHeaders
as $key => $value) {
1663 if (is_array($value) && isset($value['no_display'])) {
1664 unset($this->_columnHeaders
[$key]);
1668 // unset columns not to be displayed.
1669 if (!empty($rows)) {
1670 foreach ($this->_noDisplay
as $noDisplayField) {
1671 foreach ($rows as $rowNum => $row) {
1672 unset($this->_columnHeaders
[$noDisplayField]);
1677 // build array of section totals
1678 $this->sectionTotals();
1680 // process grand-total row
1681 $this->grandTotal($rows);
1683 // use this method for formatting rows for display purpose.
1684 $this->alterDisplay($rows);
1685 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1687 // use this method for formatting custom rows for display purpose.
1688 $this->alterCustomDataDisplay($rows);
1691 function buildChart(&$rows) {
1692 // override this method for building charts.
1695 // select() method below has been added recently (v3.3), and many of the report templates might
1696 // still be having their own select() method. We should fix them as and when encountered and move
1697 // towards generalizing the select() method below.
1701 foreach ($this->_columns
as $tableName => $table) {
1702 if (array_key_exists('fields', $table)) {
1703 foreach ($table['fields'] as $fieldName => $field) {
1704 if ($tableName == 'civicrm_address') {
1705 $this->_addressField
= TRUE;
1707 if ($tableName == 'civicrm_email') {
1708 $this->_emailField
= TRUE;
1710 if ($tableName == 'civicrm_phone') {
1711 $this->_phoneField
= TRUE;
1714 if (CRM_Utils_Array
::value('required', $field) ||
1715 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1718 // 1. In many cases we want select clause to be built in slightly different way
1719 // for a particular field of a particular type.
1720 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1722 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1723 if ($selectClause) {
1724 $select[] = $selectClause;
1728 // include statistics columns only if set
1729 if (CRM_Utils_Array
::value('statistics', $field)) {
1730 foreach ($field['statistics'] as $stat => $label) {
1731 $alias = "{$tableName}_{$fieldName}_{$stat}";
1732 switch (strtolower($stat)) {
1735 $select[] = "$stat({$field['dbAlias']}) as $alias";
1736 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1737 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1738 $this->_statFields
[$label] = $alias;
1739 $this->_selectAliases
[] = $alias;
1743 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1744 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1745 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1746 $this->_statFields
[$label] = $alias;
1747 $this->_selectAliases
[] = $alias;
1750 case 'count_distinct':
1751 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1752 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1753 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1754 $this->_statFields
[$label] = $alias;
1755 $this->_selectAliases
[] = $alias;
1759 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1760 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1761 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1762 $this->_statFields
[$label] = $alias;
1763 $this->_selectAliases
[] = $alias;
1769 $alias = "{$tableName}_{$fieldName}";
1770 $select[] = "{$field['dbAlias']} as $alias";
1771 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1772 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1773 $this->_selectAliases
[] = $alias;
1779 // select for group bys
1780 if (array_key_exists('group_bys', $table)) {
1781 foreach ($table['group_bys'] as $fieldName => $field) {
1783 if ($tableName == 'civicrm_address') {
1784 $this->_addressField
= TRUE;
1786 if ($tableName == 'civicrm_email') {
1787 $this->_emailField
= TRUE;
1789 if ($tableName == 'civicrm_phone') {
1790 $this->_phoneField
= TRUE;
1792 // 1. In many cases we want select clause to be built in slightly different way
1793 // for a particular field of a particular type.
1794 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1796 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1797 if ($selectClause) {
1798 $select[] = $selectClause;
1802 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1803 && !empty($this->_params
['group_bys_freq'])) {
1804 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1806 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1807 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1808 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1809 $field['title'] = 'Week';
1813 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1814 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1815 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1816 $field['title'] = 'Year';
1820 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1821 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1822 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1823 $field['title'] = 'Month';
1827 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1828 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1829 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1830 $field['title'] = 'Quarter';
1833 // for graphs and charts -
1834 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1835 $this->_interval
= $field['title'];
1836 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1837 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1838 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1840 // just to make sure these values are transfered to rows.
1841 // since we 'll need them for calculation purpose,
1842 // e.g making subtotals look nicer or graphs
1843 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1844 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1851 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1854 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1859 $this->storeWhereHavingClauseArray();
1861 if (empty($this->_whereClauses
)) {
1862 $this->_where
= "WHERE ( 1 ) ";
1863 $this->_having
= "";
1866 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1869 if ($this->_aclWhere
) {
1870 $this->_where
.= " AND {$this->_aclWhere} ";
1873 if (!empty($this->_havingClauses
)) {
1874 // use this clause to construct group by clause.
1875 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1880 * Store Where clauses into an array - breaking out this step makes
1881 * over-riding more flexible as the clauses can be used in constructing a
1882 * temp table that may not be part of the final where clause or added
1883 * in other functions
1885 function storeWhereHavingClauseArray(){
1886 foreach ($this->_columns
as $tableName => $table) {
1887 if (array_key_exists('filters', $table)) {
1888 foreach ($table['filters'] as $fieldName => $field) {
1889 // respect pseudofield to filter spec so fields can be marked as
1890 // not to be handled here
1891 if(!empty($field['pseudofield'])){
1895 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1896 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1897 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1898 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1899 if (is_array($value) && !empty($value)) {
1900 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1904 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1905 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1906 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1907 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1908 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1909 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1913 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1915 $clause = $this->whereClause($field,
1917 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1918 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1919 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1924 if (!empty($clause)) {
1925 if (CRM_Utils_Array
::value('having', $field)) {
1926 $this->_havingClauses
[] = $clause;
1929 $this->_whereClauses
[] = $clause;
1937 function processReportMode() {
1938 $buttonName = $this->controller
->getButtonName();
1940 $output = CRM_Utils_Request
::retrieve(
1943 CRM_Core_DAO
::$_nullObject
1947 CRM_Utils_Request
::retrieve(
1950 CRM_Core_DAO
::$_nullObject
1953 $this->_absoluteUrl
= FALSE;
1955 $this->assign('printOnly', FALSE);
1957 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1958 $this->assign('printOnly', TRUE);
1960 $this->assign('outputMode', 'print');
1961 $this->_outputMode
= 'print';
1962 if ($this->_sendmail
) {
1963 $this->_absoluteUrl
= TRUE;
1966 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1967 $this->assign('printOnly', TRUE);
1969 $this->assign('outputMode', 'pdf');
1970 $this->_outputMode
= 'pdf';
1971 $this->_absoluteUrl
= TRUE;
1973 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
1974 $this->assign('printOnly', TRUE);
1976 $this->assign('outputMode', 'csv');
1977 $this->_outputMode
= 'csv';
1978 $this->_absoluteUrl
= TRUE;
1980 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
1981 $this->assign('outputMode', 'group');
1982 $this->_outputMode
= 'group';
1984 elseif ($output == 'create_report' && $this->_criteriaForm
) {
1985 $this->assign('outputMode', 'create_report');
1986 $this->_outputMode
= 'create_report';
1989 $this->assign('outputMode', 'html');
1990 $this->_outputMode
= 'html';
1993 // Get today's date to include in printed reports
1995 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
1996 $this->assign('reportDate', $reportDate);
2000 function beginPostProcess() {
2001 $this->_params
= $this->controller
->exportValues($this->_name
);
2003 if (empty($this->_params
) &&
2006 $this->_params
= $this->_formValues
;
2009 // hack to fix params when submitted from dashboard, CRM-8532
2010 // fields array is missing because form building etc is skipped
2011 // in dashboard mode for report
2012 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2013 $this->_params
= $this->_formValues
;
2016 $this->_formValues
= $this->_params
;
2017 if (CRM_Core_Permission
::check('administer Reports') &&
2018 isset($this->_id
) &&
2019 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2020 $this->_chartButtonName
== $this->controller
->getButtonName()
2023 $this->assign('updateReportButton', TRUE);
2025 $this->processReportMode();
2028 function buildQuery($applyLimit = TRUE) {
2031 $this->customDataFrom();
2036 // order_by columns not selected for display need to be included in SELECT
2037 $unselectedSectionColumns = $this->unselectedSectionColumns();
2038 foreach ($unselectedSectionColumns as $alias => $section) {
2039 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2042 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2045 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2047 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2051 function groupBy() {
2052 $groupBys = array();
2053 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2054 is_array($this->_params
['group_bys']) &&
2055 !empty($this->_params
['group_bys'])
2057 foreach ($this->_columns
as $tableName => $table) {
2058 if (array_key_exists('group_bys', $table)) {
2059 foreach ($table['group_bys'] as $fieldName => $field) {
2060 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2061 $groupBys[] = $field['dbAlias'];
2068 if (!empty($groupBys)) {
2069 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2073 function orderBy() {
2074 $this->_orderBy
= "";
2075 $this->_sections
= array();
2076 $this->storeOrderByArray();
2077 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2078 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2080 $this->assign('sections', $this->_sections
);
2083 * In some cases other functions want to know which fields are selected for ordering by
2084 * Separating this into a separate function allows it to be called separately from constructing
2085 * the order by clause
2087 function storeOrderByArray() {
2088 $orderBys = array();
2090 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2091 is_array($this->_params
['order_bys']) &&
2092 !empty($this->_params
['order_bys'])
2095 // Proces order_bys in user-specified order
2096 foreach ($this->_params
['order_bys'] as $orderBy) {
2097 $orderByField = array();
2098 foreach ($this->_columns
as $tableName => $table) {
2099 if (array_key_exists('order_bys', $table)) {
2100 // For DAO columns defined in $this->_columns
2101 $fields = $table['order_bys'];
2103 elseif (array_key_exists('extends', $table)) {
2104 // For custom fields referenced in $this->_customGroupExtends
2105 $fields = $table['fields'];
2107 if (!empty($fields) && is_array($fields)) {
2108 foreach ($fields as $fieldName => $field) {
2109 if ($fieldName == $orderBy['column']) {
2110 $orderByField = $field;
2111 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2118 if (!empty($orderByField)) {
2119 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2121 // Record any section headers for assignment to the template
2122 if (CRM_Utils_Array
::value('section', $orderBy)) {
2123 $this->_sections
[$orderByField['tplField']] = $orderByField;
2129 $this->_orderByArray
= $orderBys;
2131 $this->assign('sections', $this->_sections
);
2134 function unselectedSectionColumns() {
2135 $selectColumns = array();
2136 foreach ($this->_columns
as $tableName => $table) {
2137 if (array_key_exists('fields', $table)) {
2138 foreach ($table['fields'] as $fieldName => $field) {
2139 if (CRM_Utils_Array
::value('required', $field) ||
2140 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2143 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2148 if (is_array($this->_sections
)) {
2149 return array_diff_key($this->_sections
, $selectColumns);
2156 function buildRows($sql, &$rows) {
2157 $dao = CRM_Core_DAO
::executeQuery($sql);
2158 if (!is_array($rows)) {
2162 // use this method to modify $this->_columnHeaders
2163 $this->modifyColumnHeaders();
2165 $unselectedSectionColumns = $this->unselectedSectionColumns();
2167 while ($dao->fetch()) {
2169 foreach ($this->_columnHeaders
as $key => $value) {
2170 if (property_exists($dao, $key)) {
2171 $row[$key] = $dao->$key;
2175 // section headers not selected for display need to be added to row
2176 foreach ($unselectedSectionColumns as $key => $values) {
2177 if (property_exists($dao, $key)) {
2178 $row[$key] = $dao->$key;
2187 * When "order by" fields are marked as sections, this assigns to the template
2188 * an array of total counts for each section. This data is used by the Smarty
2189 * plugin {sectionTotal}
2191 function sectionTotals() {
2193 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2194 if (empty($this->_selectAliases
)) {
2198 if (!empty($this->_sections
)) {
2199 // build the query with no LIMIT clause
2200 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2201 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2203 // pull section aliases out of $this->_sections
2204 $sectionAliases = array_keys($this->_sections
);
2207 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2208 $ifnulls[] = "ifnull($alias, '') as $alias";
2211 /* Group (un-limited) report by all aliases and get counts. This might
2212 * be done more efficiently when the contents of $sql are known, ie. by
2213 * overriding this method in the report class.
2217 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2219 // initialize array of total counts
2221 $dao = CRM_Core_DAO
::executeQuery($query);
2222 while ($dao->fetch()) {
2224 // let $this->_alterDisplay translate any integer ids to human-readable values.
2225 $rows[0] = $dao->toArray();
2226 $this->alterDisplay($rows);
2229 // add totals for all permutations of section values
2232 $aliasCount = count($sectionAliases);
2233 foreach ($sectionAliases as $alias) {
2234 $values[] = $row[$alias];
2235 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2236 if ($i == $aliasCount) {
2237 // the last alias is the lowest-level section header; use count as-is
2238 $totals[$key] = $dao->ct
;
2241 // other aliases are higher level; roll count into their total
2242 $totals[$key] +
= $dao->ct
;
2246 $this->assign('sectionTotals', $totals);
2250 function modifyColumnHeaders() {
2251 // use this method to modify $this->_columnHeaders
2254 function doTemplateAssignment(&$rows) {
2255 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2256 $this->assign_by_ref('rows', $rows);
2257 $this->assign('statistics', $this->statistics($rows));
2260 // override this method to build your own statistics
2261 function statistics(&$rows) {
2262 $statistics = array();
2264 $count = count($rows);
2266 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2270 $this->countStat($statistics, $count);
2272 $this->groupByStat($statistics);
2274 $this->filterStat($statistics);
2279 function countStat(&$statistics, $count) {
2280 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2284 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2285 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2286 'value' => $this->_rowsFound
,
2291 function groupByStat(&$statistics) {
2292 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2293 is_array($this->_params
['group_bys']) &&
2294 !empty($this->_params
['group_bys'])
2296 foreach ($this->_columns
as $tableName => $table) {
2297 if (array_key_exists('group_bys', $table)) {
2298 foreach ($table['group_bys'] as $fieldName => $field) {
2299 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2300 $combinations[] = $field['title'];
2305 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2306 'value' => implode(' & ', $combinations),
2311 function filterStat(&$statistics) {
2312 foreach ($this->_columns
as $tableName => $table) {
2313 if (array_key_exists('filters', $table)) {
2314 foreach ($table['filters'] as $fieldName => $field) {
2315 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2318 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2319 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2320 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2321 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2322 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2324 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2325 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2327 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2328 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2331 $statistics['filters'][] = array(
2332 'title' => $field['title'],
2333 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2336 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2337 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2339 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2340 $statistics['filters'][] = array(
2341 'title' => $field['title'],
2342 'value' => $pair[$rel],
2347 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2350 $pair = $this->getOperationPair(
2351 CRM_Utils_Array
::value('operatorType', $field),
2354 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2355 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2356 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2357 if (in_array($op, array(
2358 'bw', 'nbw')) && ($min ||
$max)) {
2359 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2361 elseif ($op == 'nll' ||
$op == 'nnll') {
2362 $value = $pair[$op];
2364 elseif (is_array($val) && (!empty($val))) {
2365 $options = $field['options'];
2366 foreach ($val as $key => $valIds) {
2367 if (isset($options[$valIds])) {
2368 $val[$key] = $options[$valIds];
2371 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : $pair[$op];
2372 $val = implode(', ', $val);
2373 $value = "{$pair[$op]} " . $val;
2375 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2376 is_array($field['options']) && !empty($field['options'])
2378 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2381 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2385 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2395 function endPostProcess(&$rows = NULL) {
2396 if ( $this->_storeResultSet
) {
2397 $this->_resultSet
= $rows;
2400 if ($this->_outputMode
== 'print' ||
2401 $this->_outputMode
== 'pdf' ||
2405 $content = $this->compileContent();
2406 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2410 if ($this->_sendmail
) {
2411 $config = CRM_Core_Config
::singleton();
2412 $attachments = array();
2414 if ($this->_outputMode
== 'csv') {
2415 $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'];
2417 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2418 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2419 file_put_contents($csvFullFilename, $csvContent);
2420 $attachments[] = array(
2421 'fullPath' => $csvFullFilename,
2422 'mime_type' => 'text/csv',
2423 'cleanName' => 'CiviReport.csv',
2426 if ($this->_outputMode
== 'pdf') {
2427 // generate PDF content
2428 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2429 file_put_contents($pdfFullFilename,
2430 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2431 TRUE, array('orientation' => 'landscape')
2434 // generate Email Content
2435 $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'];
2437 $attachments[] = array(
2438 'fullPath' => $pdfFullFilename,
2439 'mime_type' => 'application/pdf',
2440 'cleanName' => 'CiviReport.pdf',
2444 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2445 $this->_outputMode
, $attachments
2447 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2450 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2453 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2455 elseif ($this->_outputMode
== 'print') {
2459 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2460 $config = CRM_Core_Config
::singleton();
2461 //get chart image name
2462 $chartImg = $this->_chartId
. '.png';
2463 //get image url path
2464 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2465 $uploadUrl .= $chartImg;
2466 //get image doc path to overwrite
2467 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2469 $chart = imagecreatefrompng($uploadUrl);
2470 //convert it into formattd png
2471 header('Content-type: image/png');
2472 //overwrite with same image
2473 imagepng($chart, $uploadImg);
2475 imagedestroy($chart);
2477 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2479 CRM_Utils_System
::civiExit();
2481 elseif ($this->_outputMode
== 'csv') {
2482 CRM_Report_Utils_Report
::export2csv($this, $rows);
2484 elseif ($this->_outputMode
== 'group') {
2485 $group = $this->_params
['groups'];
2486 $this->add2group($group);
2488 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2489 CRM_Report_Form_Instance
::postProcess($this);
2491 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2492 $this->_outputMode
== 'create_report' ) {
2493 $this->_createNew
= TRUE;
2494 CRM_Report_Form_Instance
::postProcess($this);
2498 function storeResultSet() {
2499 $this->_storeResultSet
= TRUE;
2502 function getResultSet() {
2503 return $this->_resultSet
;
2507 * Get Template file name - use default form template if a specific one has not been set up for this report
2510 function getTemplateFileName(){
2511 $defaultTpl = parent
::getTemplateFileName();
2512 $template = CRM_Core_Smarty
::singleton();
2513 if (!$template->template_exists($defaultTpl)) {
2514 $defaultTpl = 'CRM/Report/Form.tpl';
2520 * Compile the report content
2522 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2524 function compileContent(){
2525 $templateFile = $this->getTemplateFileName();
2526 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2530 function postProcess() {
2531 // get ready with post process params
2532 $this->beginPostProcess();
2535 $sql = $this->buildQuery();
2537 // build array of result based on column headers. This method also allows
2538 // modifying column headers before using it to build result set i.e $rows.
2540 $this->buildRows($sql, $rows);
2542 // format result set.
2543 $this->formatDisplay($rows);
2545 // assign variables to templates
2546 $this->doTemplateAssignment($rows);
2548 // do print / pdf / instance stuff if needed
2549 $this->endPostProcess($rows);
2552 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2553 // lets do the pager if in html mode
2554 $this->_limit
= NULL;
2555 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2556 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2558 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2560 if (!$pageId && !empty($_POST)) {
2561 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2562 $pageId = max((int)@$_POST['crmPID_B'], 1);
2564 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2565 $pageId = max((int)@$_POST['crmPID'], 1);
2567 unset($_POST['crmPID_B'], $_POST['crmPID']);
2570 $pageId = $pageId ?
$pageId : 1;
2571 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2572 $offset = ($pageId - 1) * $rowCount;
2574 $this->_limit
= " LIMIT $offset, " . $rowCount;
2575 return array($offset, $rowCount);
2579 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2580 if ($this->_limit
&& ($this->_limit
!= '')) {
2581 $sql = "SELECT FOUND_ROWS();";
2582 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2584 'total' => $this->_rowsFound
,
2585 'rowCount' => $rowCount,
2586 'status' => ts('Records') . ' %%StatusMessage%%',
2587 'buttonBottom' => 'PagerBottomButton',
2588 'buttonTop' => 'PagerTopButton',
2589 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2592 $pager = new CRM_Utils_Pager($params);
2593 $this->assign_by_ref('pager', $pager);
2597 function whereGroupClause($field, $value, $op) {
2599 $smartGroupQuery = "";
2601 $group = new CRM_Contact_DAO_Group();
2602 $group->is_active
= 1;
2604 $smartGroups = array();
2605 while ($group->fetch()) {
2606 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2607 $smartGroups[] = $group->id
;
2611 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2613 $smartGroupQuery = '';
2614 if (!empty($smartGroups)) {
2615 $smartGroups = implode(',', $smartGroups);
2616 $smartGroupQuery = " UNION DISTINCT
2617 SELECT DISTINCT smartgroup_contact.contact_id
2618 FROM civicrm_group_contact_cache smartgroup_contact
2619 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2622 $sqlOp = $this->getSQLOperator($op);
2623 if (!is_array($value)) {
2624 $value = array($value);
2626 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2628 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2629 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2630 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2631 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2632 {$smartGroupQuery} ) ";
2635 function whereTagClause($field, $value, $op) {
2636 // not using left join in query because if any contact
2637 // belongs to more than one tag, results duplicate
2639 $sqlOp = $this->getSQLOperator($op);
2640 if (!is_array($value)) {
2641 $value = array($value);
2643 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2645 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2646 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2647 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2648 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2651 function buildACLClause($tableAlias = 'contact_a') {
2652 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2655 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2656 if (empty($this->_customGroupExtends
)) {
2659 if (!is_array($this->_customGroupExtends
)) {
2660 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2662 $customGroupWhere = '';
2663 if (!empty($permCustomGroupIds)) {
2664 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2667 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2668 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2669 FROM civicrm_custom_group cg
2670 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2671 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2673 cg.is_active = 1 AND
2674 cf.is_active = 1 AND
2675 cf.is_searchable = 1
2676 ORDER BY cg.weight, cf.weight";
2677 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2680 while ($customDAO->fetch()) {
2681 if ($customDAO->table_name
!= $curTable) {
2682 $curTable = $customDAO->table_name
;
2683 $curFields = $curFilters = array();
2686 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2687 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2688 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2689 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2692 'fields', 'filters', 'group_bys') as $colKey) {
2693 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2694 $this->_columns
[$curTable][$colKey] = array();
2698 $fieldName = 'custom_' . $customDAO->cf_id
;
2701 // this makes aliasing work in favor
2702 $curFields[$fieldName] = array(
2703 'name' => $customDAO->column_name
,
2704 'title' => $customDAO->label
,
2705 'dataType' => $customDAO->data_type
,
2706 'htmlType' => $customDAO->html_type
,
2709 if ($this->_customGroupFilters
) {
2710 // this makes aliasing work in favor
2711 $curFilters[$fieldName] = array(
2712 'name' => $customDAO->column_name
,
2713 'title' => $customDAO->label
,
2714 'dataType' => $customDAO->data_type
,
2715 'htmlType' => $customDAO->html_type
,
2719 switch ($customDAO->data_type
) {
2722 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2723 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2724 // CRM-6946, show time part for datetime date fields
2725 if ($customDAO->time_format
) {
2726 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2731 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2732 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2736 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2740 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2741 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2745 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2746 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2750 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2751 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2755 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2757 if (!empty($customDAO->option_group_id
)) {
2758 if (in_array($customDAO->html_type
, array(
2759 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2760 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2763 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2765 if ($this->_customGroupFilters
) {
2766 $curFilters[$fieldName]['options'] = array();
2767 $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')));
2768 while ($ogDAO->fetch()) {
2769 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2775 case 'StateProvince':
2776 if (in_array($customDAO->html_type
, array(
2777 'Multi-Select State/Province'))) {
2778 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2781 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2783 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2787 if (in_array($customDAO->html_type
, array(
2788 'Multi-Select Country'))) {
2789 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2792 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2794 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2797 case 'ContactReference':
2798 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2799 $curFilters[$fieldName]['name'] = 'display_name';
2800 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2802 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2803 $curFields[$fieldName]['name'] = 'display_name';
2804 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2808 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2809 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2812 if (!array_key_exists('type', $curFields[$fieldName])) {
2813 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2817 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2819 if ($this->_customGroupFilters
) {
2820 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2822 if ($this->_customGroupGroupBy
) {
2823 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2828 function customDataFrom() {
2829 if (empty($this->_customGroupExtends
)) {
2832 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2834 foreach ($this->_columns
as $table => $prop) {
2835 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2836 $extendsTable = $mapper[$prop['extends']];
2838 // check field is in params
2839 if (!$this->isFieldSelected($prop)) {
2843 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2845 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2846 // handle for ContactReference
2847 if (array_key_exists('fields', $prop)) {
2848 foreach ($prop['fields'] as $fieldName => $field) {
2849 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2850 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2852 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2860 function isFieldSelected($prop) {
2865 if (!empty($this->_params
['fields'])) {
2866 foreach (array_keys($prop['fields']) as $fieldAlias) {
2867 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2868 if ($customFieldId) {
2869 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2873 //might be survey response field.
2874 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2875 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2883 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2884 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2885 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2891 if (!empty($this->_params
['order_bys'])) {
2892 foreach (array_keys($prop['fields']) as $fieldAlias) {
2893 foreach ($this->_params
['order_bys'] as $orderBy) {
2894 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2901 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2902 foreach ($prop['filters'] as $fieldAlias => $val) {
2904 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2905 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2906 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2907 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2913 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2914 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2925 * Check for empty order_by configurations and remove them; also set
2926 * template to hide them.
2928 function preProcessOrderBy(&$formValues) {
2929 // Object to show/hide form elements
2930 $_showHide = new CRM_Core_ShowHideBlocks('', '');
2932 $_showHide->addShow('optionField_1');
2934 // Cycle through order_by options; skip any empty ones, and hide them as well
2937 if (!empty($formValues['order_bys'])) {
2938 foreach ($formValues['order_bys'] as $order_by) {
2939 if ($order_by['column'] && $order_by['column'] != '-') {
2940 $_showHide->addShow('optionField_' . $n);
2941 $orderBys[$n] = $order_by;
2946 for ($i = $n; $i <= 5; $i++
) {
2948 $_showHide->addHide('optionField_' . $i);
2952 // overwrite order_by options with modified values
2953 if (!empty($orderBys)) {
2954 $formValues['order_bys'] = $orderBys;
2957 $formValues['order_bys'] = array(1 => array('column' => '-'));
2960 // assign show/hide data to template
2961 $_showHide->addToTemplate();
2965 * Does table name have columns in SELECT clause?
2967 * @param string $tableName Name of table (index of $this->_columns array)
2971 function isTableSelected($tableName) {
2972 return in_array($tableName, $this->selectedTables());
2976 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
2977 * (building the array if it's unset)
2979 * @return Array $this->_selectedTables
2981 function selectedTables() {
2982 if (!$this->_selectedTables
) {
2983 $orderByColumns = array();
2984 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
2985 foreach ($this->_params
['order_bys'] as $orderBy) {
2986 $orderByColumns[] = $orderBy['column'];
2990 foreach ($this->_columns
as $tableName => $table) {
2991 if (array_key_exists('fields', $table)) {
2992 foreach ($table['fields'] as $fieldName => $field) {
2993 if (CRM_Utils_Array
::value('required', $field) ||
2994 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2996 $this->_selectedTables
[] = $tableName;
3001 if (array_key_exists('order_bys', $table)) {
3002 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3003 if (in_array($orderByName, $orderByColumns)) {
3004 $this->_selectedTables
[] = $tableName;
3009 if (array_key_exists('filters', $table)) {
3010 foreach ($table['filters'] as $filterName => $filter) {
3011 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3012 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3013 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3015 $this->_selectedTables
[] = $tableName;
3022 return $this->_selectedTables
;
3026 * @deprecated - use getAddressColumns which is a more accurate description
3027 * and also accepts an array of options rather than a long list
3029 * function for adding address fields to construct function in reports
3030 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3031 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3032 * @return array address fields for construct clause
3034 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3035 'country_id' => TRUE)) {
3036 $addressFields = array(
3037 'civicrm_address' =>
3039 'dao' => 'CRM_Core_DAO_Address',
3043 array('title' => ts('Address Name'),
3044 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3047 array('title' => ts('Street Address'),
3048 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3050 'supplemental_address_1' =>
3051 array('title' => ts('Supplementary Address Field 1'),
3052 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3054 'supplemental_address_2' =>
3055 array('title' => ts('Supplementary Address Field 2'),
3056 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3060 'name' => 'street_number',
3061 'title' => ts('Street Number'),
3063 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3067 'name' => 'street_name',
3068 'title' => ts('Street Name'),
3070 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3074 'name' => 'street_unit',
3075 'title' => ts('Street Unit'),
3077 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3080 array('title' => ts('City'),
3081 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3084 array('title' => ts('Postal Code'),
3085 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3088 array('title' => ts('County'),
3089 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3091 'state_province_id' =>
3092 array('title' => ts('State/Province'),
3093 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3096 array('title' => ts('Country'),
3097 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3100 'grouping' => 'location-fields',
3105 $addressFields['civicrm_address']['filters'] = array(
3106 'street_number' => array('title' => ts('Street Number'),
3108 'name' => 'street_number',
3110 'street_name' => array('title' => ts('Street Name'),
3111 'name' => 'street_name',
3112 'operator' => 'like',
3114 'postal_code' => array('title' => ts('Postal Code'),
3116 'name' => 'postal_code',
3118 'city' => array('title' => ts('City'),
3119 'operator' => 'like',
3122 'county_id' => array(
3123 'name' => 'county_id',
3124 'title' => ts('County'),
3125 'type' => CRM_Utils_Type
::T_INT
,
3127 CRM_Report_Form
::OP_MULTISELECT
,
3129 CRM_Core_PseudoConstant
::county(),
3131 'state_province_id' => array(
3132 'name' => 'state_province_id',
3133 'title' => ts('State/Province'),
3134 'type' => CRM_Utils_Type
::T_INT
,
3136 CRM_Report_Form
::OP_MULTISELECT
,
3138 CRM_Core_PseudoConstant
::stateProvince(),
3140 'country_id' => array(
3141 'name' => 'country_id',
3142 'title' => ts('Country'),
3143 'type' => CRM_Utils_Type
::T_INT
,
3145 CRM_Report_Form
::OP_MULTISELECT
,
3147 CRM_Core_PseudoConstant
::country(),
3153 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3154 'street_number' => array('title' => 'Odd / Even Street Number'),
3155 'street_address' => NULL,
3157 'postal_code' => NULL,
3162 $addressFields['civicrm_address']['group_bys'] = array(
3163 'street_address' => NULL,
3165 'postal_code' => NULL,
3166 'state_province_id' =>
3167 array('title' => ts('State/Province'),
3170 array('title' => ts('Country'),
3173 array('title' => ts('County'),
3177 return $addressFields;
3181 * Do AlterDisplay processing on Address Fields
3183 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3184 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3185 $entryFound = FALSE;
3187 if (array_key_exists('civicrm_address_country_id', $row)) {
3188 if ($value = $row['civicrm_address_country_id']) {
3189 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3190 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3191 "reset=1&force=1&{$criteriaQueryParams}&" .
3192 "country_id_op=in&country_id_value={$value}",
3193 $this->_absoluteUrl
, $this->_id
3195 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3196 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3203 if (array_key_exists('civicrm_address_county_id', $row)) {
3204 if ($value = $row['civicrm_address_county_id']) {
3205 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3206 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3207 "reset=1&force=1&{$criteriaQueryParams}&" .
3208 "county_id_op=in&county_id_value={$value}",
3209 $this->_absoluteUrl
, $this->_id
3211 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3212 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3218 // handle state province
3219 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3220 if ($value = $row['civicrm_address_state_province_id']) {
3221 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3223 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3224 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3225 $this->_absoluteUrl
, $this->_id
3227 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3228 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3239 * Adjusts dates passed in to YEAR() for fiscal year.
3241 function fiscalYearOffset($fieldName) {
3242 $config = CRM_Core_Config
::singleton();
3243 $fy = $config->fiscalYearStart
;
3244 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3245 return "YEAR( $fieldName )";
3247 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3251 * Add Address into From Table if required
3253 function addAddressFromClause() {
3254 // include address field if address column is to be included
3255 if ((isset($this->_addressField
) &&
3256 $this->_addressField
3258 $this->isTableSelected('civicrm_address')
3261 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3262 ON ({$this->_aliases['civicrm_contact']}.id =
3263 {$this->_aliases['civicrm_address']}.contact_id) AND
3264 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3269 * Add Phone into From Table if required
3271 function addPhoneFromClause() {
3272 // include address field if address column is to be included
3273 if ($this->isTableSelected('civicrm_phone')
3276 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3277 ON ({$this->_aliases['civicrm_contact']}.id =
3278 {$this->_aliases['civicrm_phone']}.contact_id) AND
3279 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3284 * Get phone columns to add to array
3285 * @param array $options
3286 * - prefix Prefix to add to table (in case of more than one instance of the table)
3287 * - prefix_label Label to give columns from this phone table instance
3288 * @return array phone columns definition
3290 function getPhoneColumns($options = array()){
3291 $defaultOptions = array(
3293 'prefix_label' => '',
3296 $options = array_merge($defaultOptions,$options);
3299 $options['prefix'] . 'civicrm_phone' => array(
3300 'dao' => 'CRM_Core_DAO_Phone',
3302 $options['prefix'] . 'phone' => array(
3303 'title' => ts($options['prefix_label'] . 'Phone'),
3313 * Get address columns to add to array
3314 * @param array $options
3315 * - prefix Prefix to add to table (in case of more than one instance of the table)
3316 * - prefix_label Label to give columns from this address table instance
3317 * @return array address columns definition
3319 function getAddressColumns($options = array()){
3320 $defaultOptions = array(
3322 'prefix_label' => '',
3326 'defaults' => array(
3329 $options = array_merge($defaultOptions,$options);
3330 return $this->addAddressFields(
3331 $options['group_by'],
3332 $options['order_by'],
3333 $options['filters'],
3334 $options['defaults']
3339 function add2group($groupID) {
3340 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3341 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3342 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3344 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3345 $dao = CRM_Core_DAO
::executeQuery($sql);
3347 $contact_ids = array();
3348 // Add resulting contacts to group
3349 while ($dao->fetch()) {
3350 if ($dao->addtogroup_contact_id
) {
3351 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3355 if ( !empty($contact_ids) ) {
3356 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3357 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3360 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3365 /* function used for showing charts on print screen */
3366 static function uploadChartImage() {
3367 // upload strictly for '.png' images
3368 $name = CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET');
3369 if (preg_match('/\.png$/', trim($name))) {
3371 // POST data is usually string data, but we are passing a RAW .png
3372 // so PHP is a bit confused and $_POST is empty. But it has saved
3373 // the raw bits into $HTTP_RAW_POST_DATA
3375 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3377 // prepare the directory
3378 $config = CRM_Core_Config
::singleton();
3379 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3380 if (!file_exists($defaultPath)) {
3381 mkdir($defaultPath, 0777, TRUE);
3384 // full path to the saved image including filename
3385 $destination = $defaultPath . basename($name);
3388 $jfh = fopen($destination, 'w') or die("can't open file");
3389 fwrite($jfh, $httpRawPostData);
3391 CRM_Utils_System
::civiExit();