3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 $_customGroupExtendsJoin = array();
139 protected $_customGroupFilters = TRUE;
140 protected $_customGroupGroupBy = FALSE;
141 protected $_customGroupJoin = 'LEFT JOIN';
147 protected $_tagFilter = FALSE;
150 * build groups filter
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * An attribute for checkbox/radio form field layout
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
174 protected $_force = 1;
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_grandFlag = FALSE;
194 protected $_rowsFound = NULL;
195 protected $_selectAliases = array();
196 protected $_rollup = NULL;
197 protected $_limit = NULL;
198 protected $_sections = NULL;
199 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
200 protected $_absoluteUrl = FALSE;
203 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
207 protected $_storeResultSet = FALSE;
210 * When _storeResultSet Flag is set use this var to store result set in form of array
214 protected $_resultSet = array();
217 * To what frequency group-by a date column
221 protected $_groupByDateFreq = array(
223 'YEARWEEK' => 'Week',
224 'QUARTER' => 'Quarter',
229 * Variables to hold the acl inner join and where clause
231 protected $_aclFrom = NULL;
232 protected $_aclWhere = NULL;
235 * Array of DAO tables having columns included in SELECT or ORDER BY clause
239 protected $_selectedTables;
241 public $_having = NULL;
242 public $_select = NULL;
243 public $_selectClauses = array();
244 public $_columnHeaders = array();
245 public $_orderBy = NULL;
246 public $_orderByFields = array();
247 public $_orderByArray = array();
248 public $_groupBy = NULL;
249 public $_whereClauses = array();
250 public $_havingClauses = array();
253 * Variable to hold the currency alias
255 protected $_currencyColumn = NULL;
260 function __construct() {
261 parent
::__construct();
264 if ($this->_tagFilter
) {
265 $this->buildTagFilter();
267 if ($this->_exposeContactID
) {
268 if (array_key_exists('civicrm_contact', $this->_columns
)) {
269 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
271 'title' => 'Contact ID',
277 if ($this->_groupFilter
) {
278 $this->buildGroupFilter();
281 // Get all custom groups
282 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
284 // Get the custom groupIds for which the user has VIEW permission
285 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
286 // and addCustomDataToColumns() will allow access to all custom groups.
287 $permCustomGroupIds = array();
288 if (!CRM_Core_Permission
::check('access all custom data')) {
289 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
290 // do not allow custom data for reports if user doesn't have
291 // permission to access custom data.
292 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
293 $this->_customGroupExtends
= array();
297 // merge custom data columns to _columns list, if any
298 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
300 // add / modify display columns, filters ..etc
301 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
303 //assign currencyColumn variable to tpl
304 $this->assign('currencyColumn', $this->_currencyColumn
);
307 function preProcessCommon() {
309 CRM_Utils_Request
::retrieve(
312 CRM_Core_DAO
::$_nullObject
315 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
317 $this->assign('section', $this->_section
);
318 CRM_Core_Region
::instance('page-header')->add(array(
319 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
322 $this->_id
= $this->get('instanceId');
324 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
326 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
330 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
331 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
332 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
335 $this->assign('instanceId', $this->_id
);
336 $params = array('id' => $this->_id
);
337 $this->_instanceValues
= array();
338 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
340 $this->_instanceValues
342 if (empty($this->_instanceValues
)) {
343 CRM_Core_Error
::fatal("Report could not be loaded.");
346 if (!empty($this->_instanceValues
['permission']) &&
347 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
348 CRM_Core_Permission
::check('administer Reports')
351 CRM_Utils_System
::permissionDenied();
352 CRM_Utils_System
::civiExit();
355 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
357 $this->_formValues
= unserialize($formValues);
360 $this->_formValues
= NULL;
363 // lets always do a force if reset is found in the url.
364 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
369 $this->assign('mode', 'instance');
372 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
373 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
374 if (($instanceCount > 0) && $optionValueID) {
375 $this->assign('instanceUrl',
376 CRM_Utils_System
::url('civicrm/report/list',
377 "reset=1&ovid=$optionValueID"
381 if ($optionValueID) {
382 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
386 $this->assign('mode', 'template');
389 // lets display the Report Settings section
390 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
392 // Do not display Report Settings section if administer Reports permission is absent OR
393 // if report instance is reserved and administer reserved reports absent
394 if (!CRM_Core_Permission
::check('administer Reports') ||
395 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
396 $this->_instanceForm
= FALSE;
399 $this->assign('criteriaForm', FALSE);
400 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
401 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
402 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
403 $this->assign('criteriaForm', TRUE);
404 $this->_criteriaForm
= TRUE;
408 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
409 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
410 $this->_printButtonName
= $this->getButtonName('submit', 'print');
411 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
412 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
413 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
414 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
417 function addBreadCrumb() {
421 'title' => ts('Report Templates'),
422 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
426 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
429 function preProcess() {
430 $this->preProcessCommon();
433 $this->addBreadCrumb();
436 foreach ($this->_columns
as $tableName => $table) {
438 if (!isset($table['alias'])) {
439 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
442 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
445 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
447 $daoOrBaoName = NULL;
448 // higher preference to bao object
449 if (array_key_exists('bao', $table)) {
450 $daoOrBaoName = $table['bao'];
451 $expFields = $daoOrBaoName::exportableFields( );
453 elseif (array_key_exists('dao', $table)){
454 $daoOrBaoName = $table['dao'];
455 $expFields = $daoOrBaoName::export( );
458 $expFields = array();
461 $doNotCopy = array('required');
463 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
464 foreach ($fieldGroups as $fieldGrp) {
465 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
466 foreach ($table[$fieldGrp] as $fieldName => $field) {
467 // $name is the field name used to reference the BAO/DAO export fields array
468 $name = isset($field['name']) ?
$field['name'] : $fieldName;
470 // Sometimes the field name key in the BAO/DAO export fields array is
471 // different from the actual database field name.
472 // Unset $field['name'] so that actual database field name can be obtained
473 // from the BAO/DAO export fields array.
474 unset($field['name']);
476 if (array_key_exists($name, $expFields)) {
477 foreach ($doNotCopy as $dnc) {
478 // unset the values we don't want to be copied.
479 unset($expFields[$name][$dnc]);
482 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
485 foreach ($expFields[$name] as $property => $val) {
486 if (!array_key_exists($property, $field)) {
487 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
494 if (CRM_Utils_Array
::value('no_repeat', $field)) {
495 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
497 if (CRM_Utils_Array
::value('no_display', $field)) {
498 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
501 // set alias = table-name, unless already set
502 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
503 $this->_columns
[$tableName]['alias'] : $tableName
505 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
507 // set name = fieldName, unless already set
508 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
509 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
512 // set dbAlias = alias.name, unless already set
513 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
514 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
517 // a few auto fills for filters
518 if ($fieldGrp == 'filters') {
519 // fill operator types
520 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
521 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
522 case CRM_Utils_Type
::T_MONEY
:
523 case CRM_Utils_Type
::T_FLOAT
:
524 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
526 case CRM_Utils_Type
::T_INT
:
527 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
529 case CRM_Utils_Type
::T_DATE
:
530 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
532 case CRM_Utils_Type
::T_BOOLEAN
:
533 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
534 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
535 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
536 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
541 (array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
542 ||
array_key_exists('enumValues', $this->_columns
[$tableName][$fieldGrp][$fieldName]))
544 // with multiple options operator-type is generally multi-select
545 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
546 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
548 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
559 // copy filters to a separate handy variable
560 if (array_key_exists('filters', $table)) {
561 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
564 if (array_key_exists('group_bys', $table)) {
565 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
568 if (array_key_exists('fields', $table)) {
569 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
574 $this->setDefaultValues(FALSE);
577 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
578 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
579 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
580 CRM_Report_Utils_Get
::processChart($this->_defaults
);
583 $this->_formValues
= $this->_defaults
;
584 $this->postProcess();
588 function setDefaultValues($freeze = TRUE) {
589 $freezeGroup = array();
591 // FIXME: generalizing form field naming conventions would reduce
592 // lots of lines below.
593 foreach ($this->_columns
as $tableName => $table) {
594 if (array_key_exists('fields', $table)) {
595 foreach ($table['fields'] as $fieldName => $field) {
596 if (!CRM_Utils_Array
::value('no_display', $field)) {
597 if (isset($field['required'])) {
599 $this->_defaults
['fields'][$fieldName] = 1;
602 // find element object, so that we could use quickform's freeze method
603 // for required elements
604 $obj = $this->getElementFromGroup("fields", $fieldName);
606 $freezeGroup[] = $obj;
610 elseif (isset($field['default'])) {
611 $this->_defaults
['fields'][$fieldName] = $field['default'];
617 if (array_key_exists('group_bys', $table)) {
618 foreach ($table['group_bys'] as $fieldName => $field) {
619 if (isset($field['default'])) {
620 if (CRM_Utils_Array
::value('frequency', $field)) {
621 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
623 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
627 if (array_key_exists('filters', $table)) {
628 foreach ($table['filters'] as $fieldName => $field) {
629 if (isset($field['default'])) {
630 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
631 if(is_array($field['default'])){
632 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
633 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
634 $this->_defaults
["{$fieldName}_relative"] = 0;
637 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
641 $this->_defaults
["{$fieldName}_value"] = $field['default'];
644 //assign default value as "in" for multiselect
645 //operator, To freeze the select element
646 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
647 $this->_defaults
["{$fieldName}_op"] = 'in';
649 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
650 $this->_defaults
["{$fieldName}_op"] = 'mhas';
652 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
653 $this->_defaults
["{$fieldName}_op"] = $op;
659 array_key_exists('order_bys', $table) &&
660 is_array($table['order_bys'])
662 if (!array_key_exists('order_bys', $this->_defaults
)) {
663 $this->_defaults
['order_bys'] = array();
665 foreach ($table['order_bys'] as $fieldName => $field) {
667 CRM_Utils_Array
::value('default', $field) ||
668 CRM_Utils_Array
::value('default_order', $field) ||
669 CRM_Utils_Array
::value('default_is_section', $field) ||
670 CRM_Utils_Array
::value('default_weight', $field)
673 'column' => $fieldName,
674 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
675 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
678 if (CRM_Utils_Array
::value('default_weight', $field)) {
679 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
682 array_unshift($this->_defaults
['order_bys'], $order_by);
688 foreach ($this->_options
as $fieldName => $field) {
689 if (isset($field['default'])) {
690 $this->_defaults
['options'][$fieldName] = $field['default'];
695 if (!empty($this->_submitValues
)) {
696 $this->preProcessOrderBy($this->_submitValues
);
699 $this->preProcessOrderBy($this->_defaults
);
702 // lets finish freezing task here itself
703 if (!empty($freezeGroup)) {
704 foreach ($freezeGroup as $elem) {
709 if ($this->_formValues
) {
710 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
713 if ($this->_instanceValues
) {
714 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
717 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
719 return $this->_defaults
;
722 function getElementFromGroup($group, $grpFieldName) {
723 $eleObj = $this->getElement($group);
724 foreach ($eleObj->_elements
as $index => $obj) {
725 if ($grpFieldName == $obj->_attributes
['name']) {
732 function addColumns() {
735 foreach ($this->_columns
as $tableName => $table) {
736 if (array_key_exists('fields', $table)) {
737 foreach ($table['fields'] as $fieldName => $field) {
739 if (!CRM_Utils_Array
::value('no_display', $field)) {
740 foreach ( array('table', 'field') as $var) {
741 if (!empty($
{$var}['grouping'])) {
742 if (!is_array($
{$var}['grouping'])) {
743 $tableName = $
{$var}['grouping'];
745 $tableName = array_keys($
{$var}['grouping']);
746 $tableName = $tableName[0];
747 $groupTitle = array_values($
{$var}['grouping']);
748 $groupTitle = $groupTitle[0];
753 if (!$groupTitle && isset($table['group_title'])) {
754 $groupTitle = $table['group_title'];
757 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
758 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
759 $colGroups[$tableName]['group_title'] = $groupTitle;
762 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
768 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
769 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
771 $this->assign('colGroups', $colGroups);
774 function addFilters() {
775 $options = $filters = array();
777 foreach ($this->_filters
as $table => $attributes) {
778 foreach ($attributes as $fieldName => $field) {
779 // get ready with option value pair
780 // @ 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
782 $operations = $this->getOperationPair(
783 CRM_Utils_Array
::value('operatorType', $field),
786 $filters[$table][$fieldName] = $field;
788 switch (CRM_Utils_Array
::value('operatorType', $field)) {
789 case CRM_Report_Form
::OP_MONTH
:
790 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
791 // If there's no option list for this filter, define one.
792 $field['options'] = array(
801 9 => ts('September'),
803 11 => ts('November'),
804 12 => ts('December'),
806 // Add this option list to this column _columns. This is
807 // required so that filter statistics show properly.
808 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
810 case CRM_Report_FORM
::OP_MULTISELECT
:
811 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
812 // assume a multi-select field
813 if (!empty($field['options'])) {
814 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
815 if (count($operations) <= 1) {
818 $select = $this->addElement('select', "{$fieldName}_value", NULL,
819 $field['options'], array(
821 'style' => 'min-width:250px',
824 $select->setMultiple(TRUE);
828 case CRM_Report_FORM
::OP_SELECT
:
829 // assume a select field
830 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
831 if (!empty($field['options']))
832 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
835 case CRM_Report_FORM
::OP_DATE
:
836 // build datetime fields
837 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
841 case CRM_Report_FORM
::OP_DATETIME
:
842 // build datetime fields
843 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
847 case CRM_Report_FORM
::OP_INT
:
848 case CRM_Report_FORM
::OP_FLOAT
:
849 // and a min value input box
850 $this->add('text', "{$fieldName}_min", ts('Min'));
851 // and a max value input box
852 $this->add('text', "{$fieldName}_max", ts('Max'));
854 // default type is string
855 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
856 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
858 // we need text box for value input
859 $this->add('text', "{$fieldName}_value", NULL);
864 $this->assign('filters', $filters);
867 function addOptions() {
868 if (!empty($this->_options
)) {
869 // FIXME: For now lets build all elements as checkboxes.
870 // Once we clear with the format we can build elements based on type
873 foreach ($this->_options
as $fieldName => $field) {
874 if ($field['type'] == 'select') {
875 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
877 else if ($field['type'] == 'checkbox') {
878 $options[$field['title']] = $fieldName;
879 $this->addCheckBox($fieldName, NULL,
881 NULL, NULL, NULL, $this->_fourColumnAttribute
886 $this->assign('otherOptions', $this->_options
);
889 function addChartOptions() {
890 if (!empty($this->_charts
)) {
891 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
892 $this->assign('charts', $this->_charts
);
893 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
897 function addGroupBys() {
898 $options = $freqElements = array();
900 foreach ($this->_columns
as $tableName => $table) {
901 if (array_key_exists('group_bys', $table)) {
902 foreach ($table['group_bys'] as $fieldName => $field) {
903 if (!empty($field)) {
904 $options[$field['title']] = $fieldName;
905 if (CRM_Utils_Array
::value('frequency', $field)) {
906 $freqElements[$field['title']] = $fieldName;
912 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
913 NULL, NULL, NULL, $this->_fourColumnAttribute
915 $this->assign('groupByElements', $options);
917 foreach ($freqElements as $name) {
918 $this->addElement('select', "group_bys_freq[$name]",
919 ts('Frequency'), $this->_groupByDateFreq
924 function addOrderBys() {
926 foreach ($this->_columns
as $tableName => $table) {
928 // Report developer may define any column to order by; include these as order-by options
929 if (array_key_exists('order_bys', $table)) {
930 foreach ($table['order_bys'] as $fieldName => $field) {
931 if (!empty($field)) {
932 $options[$fieldName] = $field['title'];
937 /* Add searchable custom fields as order-by options, if so requested
938 * (These are already indexed, so allowing to order on them is cheap.)
942 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
943 foreach ($table['fields'] as $fieldName => $field) {
944 if (!CRM_Utils_Array
::value('no_display', $field)) {
945 $options[$fieldName] = $field['title'];
953 $this->assign('orderByOptions', $options);
955 if (!empty($options)) {
957 '-' => ' - none - ') +
$options;
958 for ($i = 1; $i <= 5; $i++
) {
959 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
960 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
961 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
966 function buildInstanceAndButtons() {
967 CRM_Report_Form_Instance
::buildForm($this);
969 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
971 $this->addElement('submit', $this->_instanceButtonName
, $label);
972 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
973 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
976 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
978 if ($this->_instanceForm
) {
979 $this->assign('instanceForm', TRUE);
982 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
983 $this->addElement('submit', $this->_printButtonName
, $label);
985 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
986 $this->addElement('submit', $this->_pdfButtonName
, $label);
988 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
990 if ($this->_csvSupported
) {
991 $this->addElement('submit', $this->_csvButtonName
, $label);
994 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
995 $this->addElement('select', 'groups', ts('Group'),
996 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
998 $this->assign('group', TRUE);
1001 $label = ts('Add these Contacts to Group');
1002 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1004 $this->addChartOptions();
1005 $this->addButtons(array(
1008 'name' => ts('Preview Report'),
1009 'isDefault' => TRUE,
1015 function buildQuickForm() {
1016 $this->addColumns();
1018 $this->addFilters();
1020 $this->addOptions();
1022 $this->addGroupBys();
1024 $this->addOrderBys();
1026 $this->buildInstanceAndButtons();
1028 //add form rule for report
1029 if (is_callable(array(
1030 $this, 'formRule'))) {
1031 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1035 // a formrule function to ensure that fields selected in group_by
1036 // (if any) should only be the ones present in display/select fields criteria;
1037 // note: works if and only if any custom field selected in group_by.
1038 function customDataFormRule($fields, $ignoreFields = array( )) {
1040 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1041 foreach ($this->_columns
as $tableName => $table) {
1042 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1043 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1044 if (array_key_exists($fieldName, $fields['group_bys']) &&
1045 !array_key_exists($fieldName, $fields['fields'])
1047 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1049 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1050 foreach ($fields['fields'] as $fld => $val) {
1051 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1052 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1063 // Note: $fieldName param allows inheriting class to build operationPairs
1064 // specific to a field.
1065 function getOperationPair($type = "string", $fieldName = NULL) {
1066 // FIXME: At some point we should move these key-val pairs
1067 // to option_group and option_value table.
1069 case CRM_Report_FORM
::OP_INT
:
1070 case CRM_Report_FORM
::OP_FLOAT
:
1072 'lte' => ts('Is less than or equal to'),
1073 'gte' => ts('Is greater than or equal to'),
1074 'bw' => ts('Is between'),
1075 'eq' => ts('Is equal to'),
1076 'lt' => ts('Is less than'),
1077 'gt' => ts('Is greater than'),
1078 'neq' => ts('Is not equal to'),
1079 'nbw' => ts('Is not between'),
1080 'nll' => ts('Is empty (Null)'),
1081 'nnll' => ts('Is not empty (Null)'),
1085 case CRM_Report_FORM
::OP_SELECT
:
1087 'eq' => ts('Is equal to'),
1090 case CRM_Report_FORM
::OP_MONTH
:
1091 case CRM_Report_FORM
::OP_MULTISELECT
:
1093 'in' => ts('Is one of'),
1094 'notin' => ts('Is not one of'),
1098 case CRM_Report_FORM
::OP_DATE
:
1100 'nll' => ts('Is empty (Null)'),
1101 'nnll' => ts('Is not empty (Null)'),
1105 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1106 // use this operator for the values, concatenated with separator. For e.g if
1107 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1109 'mhas' => ts('Is one of'),
1115 'has' => ts('Contains'),
1116 'sw' => ts('Starts with'),
1117 'ew' => ts('Ends with'),
1118 'nhas' => ts('Does not contain'),
1119 'eq' => ts('Is equal to'),
1120 'neq' => ts('Is not equal to'),
1121 'nll' => ts('Is empty (Null)'),
1122 'nnll' => ts('Is not empty (Null)'),
1127 function buildTagFilter() {
1128 $contactTags = CRM_Core_BAO_Tag
::getTags();
1129 if (!empty($contactTags)) {
1130 $this->_columns
['civicrm_tag'] = array(
1131 'dao' => 'CRM_Core_DAO_Tag',
1137 'title' => ts('Tag'),
1139 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1140 'options' => $contactTags,
1148 * Adds group filters to _columns (called from _Constuct
1150 function buildGroupFilter() {
1151 $this->_columns
['civicrm_group']['filters'] = array(
1154 'name' => 'group_id',
1155 'title' => ts('Group'),
1156 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1158 'options' => CRM_Core_PseudoConstant
::group(),
1161 if (empty($this->_columns
['civicrm_group']['dao'])) {
1162 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1164 if (empty($this->_columns
['civicrm_group']['alias'])) {
1165 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1169 function getSQLOperator($operator = "like") {
1170 switch ($operator) {
1203 return 'IS NOT NULL';
1211 function whereClause(&$field, $op,
1215 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1221 if (($min !== NULL && strlen($min) > 0) ||
1222 ($max !== NULL && strlen($max) > 0)
1224 $min = CRM_Utils_Type
::escape($min, $type);
1225 $max = CRM_Utils_Type
::escape($max, $type);
1229 $clauses[] = "( {$field['dbAlias']} >= $min )";
1232 $clauses[] = "( {$field['dbAlias']} < $min )";
1237 $clauses[] = "( {$field['dbAlias']} <= $max )";
1240 $clauses[] = "( {$field['dbAlias']} > $max )";
1244 if (!empty($clauses)) {
1246 $clause = implode(' AND ', $clauses);
1249 $clause = implode(' OR ', $clauses);
1257 if ($value !== NULL && strlen($value) > 0) {
1258 $value = CRM_Utils_Type
::escape($value, $type);
1259 if (strpos($value, '%') === FALSE) {
1260 $value = "'%{$value}%'";
1263 $value = "'{$value}'";
1265 $sqlOP = $this->getSQLOperator($op);
1266 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1272 if ($value !== NULL && is_array($value) && count($value) > 0) {
1273 $sqlOP = $this->getSQLOperator($op);
1274 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1275 //cycle through selections and esacape values
1276 foreach ($value as $key => $selection) {
1277 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1279 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1282 // for numerical values
1283 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1285 if ($op == 'notin') {
1286 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1289 $clause = "( " . $clause . " )";
1295 // mhas == multiple has
1296 if ($value !== NULL && count($value) > 0) {
1297 $sqlOP = $this->getSQLOperator($op);
1298 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1304 if ($value !== NULL && strlen($value) > 0) {
1305 $value = CRM_Utils_Type
::escape($value, $type);
1306 if (strpos($value, '%') === FALSE) {
1308 $value = "'{$value}%'";
1311 $value = "'%{$value}'";
1315 $value = "'{$value}'";
1317 $sqlOP = $this->getSQLOperator($op);
1318 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1324 $sqlOP = $this->getSQLOperator($op);
1325 $clause = "( {$field['dbAlias']} $sqlOP )";
1329 if ($value !== NULL && strlen($value) > 0) {
1330 if (isset($field['clause'])) {
1331 // FIXME: we not doing escape here. Better solution is to use two
1332 // different types - data-type and filter-type
1333 $clause = $field['clause'];
1336 $value = CRM_Utils_Type
::escape($value, $type);
1337 $sqlOP = $this->getSQLOperator($op);
1338 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1339 $value = "'{$value}'";
1341 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1347 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1348 $clause = $this->whereGroupClause($field, $value, $op);
1350 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1351 // not using left join in query because if any contact
1352 // belongs to more than one tag, results duplicate
1354 $clause = $this->whereTagClause($field, $value, $op);
1360 function dateClause($fieldName,
1361 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1364 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1365 $sqlOP = $this->getSQLOperator($relative);
1366 return "( {$fieldName} {$sqlOP} )";
1369 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1372 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1373 $clauses[] = "( {$fieldName} >= $from )";
1377 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1378 $clauses[] = "( {$fieldName} <= {$to} )";
1381 if (!empty($clauses)) {
1382 return implode(' AND ', $clauses);
1388 * @todo - could not find any instances where this is called
1389 * @param unknown_type $relative
1390 * @param String $from
1391 * @param String_type $to
1392 * @return string|NULL
1394 function dateDisplay($relative, $from, $to) {
1395 list($from, $to) = $this->getFromTo($relative, $from, $to);
1398 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1401 $clauses[] = 'Past';
1405 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1408 $clauses[] = 'Today';
1411 if (!empty($clauses)) {
1412 return implode(' - ', $clauses);
1418 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1419 if (empty($totime)) {
1422 //FIX ME not working for relative
1424 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1425 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1426 $from = substr($dateRange['from'], 0, 8);
1427 //Take only Date Part, Sometime Time part is also present in 'to'
1428 $to = substr($dateRange['to'], 0, 8);
1430 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1431 $to = CRM_Utils_Date
::processDate($to, $totime);
1432 return array($from, $to);
1435 function alterDisplay(&$rows) {
1436 // custom code to alter rows
1439 function alterCustomDataDisplay(&$rows) {
1440 // custom code to alter rows having custom values
1441 if (empty($this->_customGroupExtends
)) {
1445 $customFieldIds = array();
1446 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1447 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1448 $customFieldIds[$fieldAlias] = $fieldId;
1451 if (empty($customFieldIds)) {
1455 $customFields = $fieldValueMap = array();
1456 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1458 // skip for type date and ContactReference since date format is already handled
1460 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1461 FROM civicrm_custom_field cf
1462 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1463 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1464 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1465 cg.is_active = 1 AND
1466 cf.is_active = 1 AND
1467 cf.is_searchable = 1 AND
1468 cf.data_type NOT IN ('ContactReference', 'Date') AND
1469 cf.id IN (" . implode(",", $customFieldIds) . ")";
1471 $dao = CRM_Core_DAO
::executeQuery($query);
1472 while ($dao->fetch()) {
1473 foreach ($customFieldCols as $key) {
1474 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1476 if ($dao->option_group_id
) {
1477 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1482 $entryFound = FALSE;
1483 foreach ($rows as $rowNum => $row) {
1484 foreach ($row as $tableCol => $val) {
1485 if (array_key_exists($tableCol, $customFields)) {
1486 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1491 // skip looking further in rows, if first row itself doesn't
1492 // have the column we need
1499 function formatCustomValues($value, $customField, $fieldValueMap) {
1500 if (CRM_Utils_System
::isNull($value)) {
1504 $htmlType = $customField['html_type'];
1506 switch ($customField['data_type']) {
1508 if ($value == '1') {
1509 $retValue = ts('Yes');
1512 $retValue = ts('No');
1517 $retValue = CRM_Utils_System
::formatWikiURL($value);
1529 if ($htmlType == 'Text') {
1530 $retValue = (float)$value;
1534 if ($htmlType == 'Text') {
1544 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1549 if (in_array($htmlType, array(
1550 'Text', 'TextArea'))) {
1554 case 'StateProvince':
1557 switch ($htmlType) {
1558 case 'Multi-Select Country':
1559 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1560 $customData = array();
1561 foreach ($value as $val) {
1563 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1566 $retValue = implode(', ', $customData);
1569 case 'Select Country':
1570 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1573 case 'Select State/Province':
1574 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1577 case 'Multi-Select State/Province':
1578 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1579 $customData = array();
1580 foreach ($value as $val) {
1582 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1585 $retValue = implode(', ', $customData);
1590 case 'Autocomplete-Select':
1591 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1595 case 'AdvMulti-Select':
1596 case 'Multi-Select':
1597 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1598 $customData = array();
1599 foreach ($value as $val) {
1601 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1604 $retValue = implode(', ', $customData);
1619 function removeDuplicates(&$rows) {
1620 if (empty($this->_noRepeats
)) {
1623 $checkList = array();
1625 foreach ($rows as $key => $list) {
1626 foreach ($list as $colName => $colVal) {
1627 if (array_key_exists($colName, $checkList) &&
1628 $checkList[$colName] == $colVal) {
1629 $rows[$key][$colName] = "";
1631 if (in_array($colName, $this->_noRepeats
)) {
1632 $checkList[$colName] = $colVal;
1638 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1639 foreach ($row as $colName => $colVal) {
1640 if (in_array($colName, $fields)) {
1641 $row[$colName] = $row[$colName];
1643 elseif (isset($this->_columnHeaders
[$colName])) {
1645 $row[$colName] = "Subtotal";
1649 unset($row[$colName]);
1655 function grandTotal(&$rows) {
1656 if (!$this->_rollup ||
($this->_rollup
== '') ||
1657 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1661 $lastRow = array_pop($rows);
1663 foreach ($this->_columnHeaders
as $fld => $val) {
1664 if (!in_array($fld, $this->_statFields
)) {
1665 if (!$this->_grandFlag
) {
1666 $lastRow[$fld] = "Grand Total";
1667 $this->_grandFlag
= TRUE;
1670 $lastRow[$fld] = "";
1675 $this->assign('grandStat', $lastRow);
1679 function formatDisplay(&$rows, $pager = TRUE) {
1680 // set pager based on if any limit was applied in the query.
1685 // allow building charts if any
1686 if (!empty($this->_params
['charts']) && !empty($rows)) {
1687 $this->buildChart($rows);
1688 $this->assign('chartEnabled', TRUE);
1689 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1690 $this->assign('chartId', $this->_chartId
);
1693 // unset columns not to be displayed.
1694 foreach ($this->_columnHeaders
as $key => $value) {
1695 if (CRM_Utils_Array
::value('no_display', $value)) {
1696 unset($this->_columnHeaders
[$key]);
1700 // unset columns not to be displayed.
1701 if (!empty($rows)) {
1702 foreach ($this->_noDisplay
as $noDisplayField) {
1703 foreach ($rows as $rowNum => $row) {
1704 unset($this->_columnHeaders
[$noDisplayField]);
1709 // build array of section totals
1710 $this->sectionTotals();
1712 // process grand-total row
1713 $this->grandTotal($rows);
1715 // use this method for formatting rows for display purpose.
1716 $this->alterDisplay($rows);
1717 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1719 // use this method for formatting custom rows for display purpose.
1720 $this->alterCustomDataDisplay($rows);
1723 function buildChart(&$rows) {
1724 // override this method for building charts.
1727 // select() method below has been added recently (v3.3), and many of the report templates might
1728 // still be having their own select() method. We should fix them as and when encountered and move
1729 // towards generalizing the select() method below.
1731 $select = $this->_selectAliases
= array();
1733 foreach ($this->_columns
as $tableName => $table) {
1734 if (array_key_exists('fields', $table)) {
1735 foreach ($table['fields'] as $fieldName => $field) {
1736 if ($tableName == 'civicrm_address') {
1737 $this->_addressField
= TRUE;
1739 if ($tableName == 'civicrm_email') {
1740 $this->_emailField
= TRUE;
1742 if ($tableName == 'civicrm_phone') {
1743 $this->_phoneField
= TRUE;
1746 if (CRM_Utils_Array
::value('required', $field) ||
1747 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1750 // 1. In many cases we want select clause to be built in slightly different way
1751 // for a particular field of a particular type.
1752 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1754 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1755 if ($selectClause) {
1756 $select[] = $selectClause;
1760 // include statistics columns only if set
1761 if (CRM_Utils_Array
::value('statistics', $field)) {
1762 foreach ($field['statistics'] as $stat => $label) {
1763 $alias = "{$tableName}_{$fieldName}_{$stat}";
1764 switch (strtolower($stat)) {
1767 $select[] = "$stat({$field['dbAlias']}) as $alias";
1768 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1769 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1770 $this->_statFields
[$label] = $alias;
1771 $this->_selectAliases
[] = $alias;
1775 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1776 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1777 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1778 $this->_statFields
[$label] = $alias;
1779 $this->_selectAliases
[] = $alias;
1782 case 'count_distinct':
1783 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1784 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1785 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1786 $this->_statFields
[$label] = $alias;
1787 $this->_selectAliases
[] = $alias;
1791 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1792 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1793 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1794 $this->_statFields
[$label] = $alias;
1795 $this->_selectAliases
[] = $alias;
1801 $alias = "{$tableName}_{$fieldName}";
1802 $select[] = "{$field['dbAlias']} as $alias";
1803 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1804 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1805 $this->_selectAliases
[] = $alias;
1811 // select for group bys
1812 if (array_key_exists('group_bys', $table)) {
1813 foreach ($table['group_bys'] as $fieldName => $field) {
1815 if ($tableName == 'civicrm_address') {
1816 $this->_addressField
= TRUE;
1818 if ($tableName == 'civicrm_email') {
1819 $this->_emailField
= TRUE;
1821 if ($tableName == 'civicrm_phone') {
1822 $this->_phoneField
= TRUE;
1824 // 1. In many cases we want select clause to be built in slightly different way
1825 // for a particular field of a particular type.
1826 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1828 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1829 if ($selectClause) {
1830 $select[] = $selectClause;
1834 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1835 && !empty($this->_params
['group_bys_freq'])) {
1836 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1838 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1839 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1840 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1841 $field['title'] = 'Week';
1845 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1846 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1847 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1848 $field['title'] = 'Year';
1852 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1853 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1854 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1855 $field['title'] = 'Month';
1859 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1860 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1861 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1862 $field['title'] = 'Quarter';
1865 // for graphs and charts -
1866 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1867 $this->_interval
= $field['title'];
1868 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1869 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1870 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1872 // just to make sure these values are transfered to rows.
1873 // since we 'll need them for calculation purpose,
1874 // e.g making subtotals look nicer or graphs
1875 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1876 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1883 $this->_selectClauses
= $select;
1884 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1887 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1892 $this->storeWhereHavingClauseArray();
1894 if (empty($this->_whereClauses
)) {
1895 $this->_where
= "WHERE ( 1 ) ";
1896 $this->_having
= "";
1899 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1902 if ($this->_aclWhere
) {
1903 $this->_where
.= " AND {$this->_aclWhere} ";
1906 if (!empty($this->_havingClauses
)) {
1907 // use this clause to construct group by clause.
1908 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1913 * Store Where clauses into an array - breaking out this step makes
1914 * over-riding more flexible as the clauses can be used in constructing a
1915 * temp table that may not be part of the final where clause or added
1916 * in other functions
1918 function storeWhereHavingClauseArray(){
1919 foreach ($this->_columns
as $tableName => $table) {
1920 if (array_key_exists('filters', $table)) {
1921 foreach ($table['filters'] as $fieldName => $field) {
1922 // respect pseudofield to filter spec so fields can be marked as
1923 // not to be handled here
1924 if(!empty($field['pseudofield'])){
1928 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1929 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1930 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1931 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1932 if (is_array($value) && !empty($value)) {
1933 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1937 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1938 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1939 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1940 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1941 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1942 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1946 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1948 $clause = $this->whereClause($field,
1950 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1951 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1952 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1957 if (!empty($clause)) {
1958 if (CRM_Utils_Array
::value('having', $field)) {
1959 $this->_havingClauses
[] = $clause;
1962 $this->_whereClauses
[] = $clause;
1970 function processReportMode() {
1971 $buttonName = $this->controller
->getButtonName();
1973 $output = CRM_Utils_Request
::retrieve(
1976 CRM_Core_DAO
::$_nullObject
1980 CRM_Utils_Request
::retrieve(
1983 CRM_Core_DAO
::$_nullObject
1986 $this->_absoluteUrl
= FALSE;
1988 $this->assign('printOnly', FALSE);
1990 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1991 $this->assign('printOnly', TRUE);
1993 $this->assign('outputMode', 'print');
1994 $this->_outputMode
= 'print';
1995 if ($this->_sendmail
) {
1996 $this->_absoluteUrl
= TRUE;
1999 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2000 $this->assign('printOnly', TRUE);
2002 $this->assign('outputMode', 'pdf');
2003 $this->_outputMode
= 'pdf';
2004 $this->_absoluteUrl
= TRUE;
2006 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2007 $this->assign('printOnly', TRUE);
2009 $this->assign('outputMode', 'csv');
2010 $this->_outputMode
= 'csv';
2011 $this->_absoluteUrl
= TRUE;
2013 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2014 $this->assign('outputMode', 'group');
2015 $this->_outputMode
= 'group';
2017 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2018 $this->assign('outputMode', 'create_report');
2019 $this->_outputMode
= 'create_report';
2022 $this->assign('outputMode', 'html');
2023 $this->_outputMode
= 'html';
2026 // Get today's date to include in printed reports
2028 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2029 $this->assign('reportDate', $reportDate);
2033 function beginPostProcess() {
2034 $this->_params
= $this->controller
->exportValues($this->_name
);
2036 if (empty($this->_params
) &&
2039 $this->_params
= $this->_formValues
;
2042 // hack to fix params when submitted from dashboard, CRM-8532
2043 // fields array is missing because form building etc is skipped
2044 // in dashboard mode for report
2045 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2046 $this->_params
= $this->_formValues
;
2049 $this->_formValues
= $this->_params
;
2050 if (CRM_Core_Permission
::check('administer Reports') &&
2051 isset($this->_id
) &&
2052 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2053 $this->_chartButtonName
== $this->controller
->getButtonName()
2056 $this->assign('updateReportButton', TRUE);
2058 $this->processReportMode();
2061 function buildQuery($applyLimit = TRUE) {
2064 $this->customDataFrom();
2069 // order_by columns not selected for display need to be included in SELECT
2070 $unselectedSectionColumns = $this->unselectedSectionColumns();
2071 foreach ($unselectedSectionColumns as $alias => $section) {
2072 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2075 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2078 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2080 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2084 function groupBy() {
2085 $groupBys = array();
2086 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2087 is_array($this->_params
['group_bys']) &&
2088 !empty($this->_params
['group_bys'])
2090 foreach ($this->_columns
as $tableName => $table) {
2091 if (array_key_exists('group_bys', $table)) {
2092 foreach ($table['group_bys'] as $fieldName => $field) {
2093 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2094 $groupBys[] = $field['dbAlias'];
2101 if (!empty($groupBys)) {
2102 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2106 function orderBy() {
2107 $this->_orderBy
= "";
2108 $this->_sections
= array();
2109 $this->storeOrderByArray();
2110 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2111 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2113 $this->assign('sections', $this->_sections
);
2117 * In some cases other functions want to know which fields are selected for ordering by
2118 * Separating this into a separate function allows it to be called separately from constructing
2119 * the order by clause
2121 function storeOrderByArray() {
2122 $orderBys = array();
2124 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2125 is_array($this->_params
['order_bys']) &&
2126 !empty($this->_params
['order_bys'])
2129 // Proces order_bys in user-specified order
2130 foreach ($this->_params
['order_bys'] as $orderBy) {
2131 $orderByField = array();
2132 foreach ($this->_columns
as $tableName => $table) {
2133 if (array_key_exists('order_bys', $table)) {
2134 // For DAO columns defined in $this->_columns
2135 $fields = $table['order_bys'];
2137 elseif (array_key_exists('extends', $table)) {
2138 // For custom fields referenced in $this->_customGroupExtends
2139 $fields = $table['fields'];
2141 if (!empty($fields) && is_array($fields)) {
2142 foreach ($fields as $fieldName => $field) {
2143 if ($fieldName == $orderBy['column']) {
2144 $orderByField = array_merge($field, $orderBy);
2145 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2152 if (!empty($orderByField)) {
2153 $this->_orderByFields
[] = $orderByField;
2154 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2156 // Record any section headers for assignment to the template
2157 if (CRM_Utils_Array
::value('section', $orderBy)) {
2158 $this->_sections
[$orderByField['tplField']] = $orderByField;
2164 $this->_orderByArray
= $orderBys;
2166 $this->assign('sections', $this->_sections
);
2169 function unselectedSectionColumns() {
2170 $selectColumns = array();
2171 foreach ($this->_columns
as $tableName => $table) {
2172 if (array_key_exists('fields', $table)) {
2173 foreach ($table['fields'] as $fieldName => $field) {
2174 if (CRM_Utils_Array
::value('required', $field) ||
2175 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2178 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2184 if (is_array($this->_sections
)) {
2185 return array_diff_key($this->_sections
, $selectColumns);
2192 function buildRows($sql, &$rows) {
2193 $dao = CRM_Core_DAO
::executeQuery($sql);
2194 if (!is_array($rows)) {
2198 // use this method to modify $this->_columnHeaders
2199 $this->modifyColumnHeaders();
2201 $unselectedSectionColumns = $this->unselectedSectionColumns();
2203 while ($dao->fetch()) {
2205 foreach ($this->_columnHeaders
as $key => $value) {
2206 if (property_exists($dao, $key)) {
2207 $row[$key] = $dao->$key;
2211 // section headers not selected for display need to be added to row
2212 foreach ($unselectedSectionColumns as $key => $values) {
2213 if (property_exists($dao, $key)) {
2214 $row[$key] = $dao->$key;
2223 * When "order by" fields are marked as sections, this assigns to the template
2224 * an array of total counts for each section. This data is used by the Smarty
2225 * plugin {sectionTotal}
2227 function sectionTotals() {
2229 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2230 if (empty($this->_selectAliases
)) {
2234 if (!empty($this->_sections
)) {
2235 // build the query with no LIMIT clause
2236 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2237 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2239 // pull section aliases out of $this->_sections
2240 $sectionAliases = array_keys($this->_sections
);
2243 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2244 $ifnulls[] = "ifnull($alias, '') as $alias";
2247 /* Group (un-limited) report by all aliases and get counts. This might
2248 * be done more efficiently when the contents of $sql are known, ie. by
2249 * overriding this method in the report class.
2253 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2255 // initialize array of total counts
2257 $dao = CRM_Core_DAO
::executeQuery($query);
2258 while ($dao->fetch()) {
2260 // let $this->_alterDisplay translate any integer ids to human-readable values.
2261 $rows[0] = $dao->toArray();
2262 $this->alterDisplay($rows);
2265 // add totals for all permutations of section values
2268 $aliasCount = count($sectionAliases);
2269 foreach ($sectionAliases as $alias) {
2270 $values[] = $row[$alias];
2271 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2272 if ($i == $aliasCount) {
2273 // the last alias is the lowest-level section header; use count as-is
2274 $totals[$key] = $dao->ct
;
2277 // other aliases are higher level; roll count into their total
2278 $totals[$key] +
= $dao->ct
;
2282 $this->assign('sectionTotals', $totals);
2286 function modifyColumnHeaders() {
2287 // use this method to modify $this->_columnHeaders
2290 function doTemplateAssignment(&$rows) {
2291 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2292 $this->assign_by_ref('rows', $rows);
2293 $this->assign('statistics', $this->statistics($rows));
2296 // override this method to build your own statistics
2297 function statistics(&$rows) {
2298 $statistics = array();
2300 $count = count($rows);
2302 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2306 $this->countStat($statistics, $count);
2308 $this->groupByStat($statistics);
2310 $this->filterStat($statistics);
2315 function countStat(&$statistics, $count) {
2316 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2320 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2321 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2322 'value' => $this->_rowsFound
,
2327 function groupByStat(&$statistics) {
2328 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2329 is_array($this->_params
['group_bys']) &&
2330 !empty($this->_params
['group_bys'])
2332 foreach ($this->_columns
as $tableName => $table) {
2333 if (array_key_exists('group_bys', $table)) {
2334 foreach ($table['group_bys'] as $fieldName => $field) {
2335 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2336 $combinations[] = $field['title'];
2341 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2342 'value' => implode(' & ', $combinations),
2347 function filterStat(&$statistics) {
2348 foreach ($this->_columns
as $tableName => $table) {
2349 if (array_key_exists('filters', $table)) {
2350 foreach ($table['filters'] as $fieldName => $field) {
2351 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2354 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2355 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2356 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2357 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2358 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2360 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2361 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2363 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2364 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2367 $statistics['filters'][] = array(
2368 'title' => $field['title'],
2369 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2372 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2373 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2375 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2376 $statistics['filters'][] = array(
2377 'title' => $field['title'],
2378 'value' => $pair[$rel],
2383 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2386 $pair = $this->getOperationPair(
2387 CRM_Utils_Array
::value('operatorType', $field),
2390 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2391 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2392 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2393 if (in_array($op, array(
2394 'bw', 'nbw')) && ($min ||
$max)) {
2395 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2397 elseif ($op == 'nll' ||
$op == 'nnll') {
2398 $value = $pair[$op];
2400 elseif (is_array($val) && (!empty($val))) {
2401 $options = CRM_Utils_Array
::value('options', $field, array());
2402 foreach ($val as $key => $valIds) {
2403 if (isset($options[$valIds])) {
2404 $val[$key] = $options[$valIds];
2407 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2408 $val = implode(', ', $val);
2409 $value = "{$pair[$op]} " . $val;
2411 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2412 is_array($field['options']) && !empty($field['options'])
2414 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2417 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2421 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2431 function endPostProcess(&$rows = NULL) {
2432 if ( $this->_storeResultSet
) {
2433 $this->_resultSet
= $rows;
2436 if ($this->_outputMode
== 'print' ||
2437 $this->_outputMode
== 'pdf' ||
2441 $content = $this->compileContent();
2442 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2446 if ($this->_sendmail
) {
2447 $config = CRM_Core_Config
::singleton();
2448 $attachments = array();
2450 if ($this->_outputMode
== 'csv') {
2451 $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'];
2453 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2454 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2455 file_put_contents($csvFullFilename, $csvContent);
2456 $attachments[] = array(
2457 'fullPath' => $csvFullFilename,
2458 'mime_type' => 'text/csv',
2459 'cleanName' => 'CiviReport.csv',
2462 if ($this->_outputMode
== 'pdf') {
2463 // generate PDF content
2464 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2465 file_put_contents($pdfFullFilename,
2466 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2467 TRUE, array('orientation' => 'landscape')
2470 // generate Email Content
2471 $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'];
2473 $attachments[] = array(
2474 'fullPath' => $pdfFullFilename,
2475 'mime_type' => 'application/pdf',
2476 'cleanName' => 'CiviReport.pdf',
2480 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2481 $this->_outputMode
, $attachments
2483 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2486 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2489 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2491 elseif ($this->_outputMode
== 'print') {
2495 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2496 $config = CRM_Core_Config
::singleton();
2497 //get chart image name
2498 $chartImg = $this->_chartId
. '.png';
2499 //get image url path
2500 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2501 $uploadUrl .= $chartImg;
2502 //get image doc path to overwrite
2503 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2505 $chart = imagecreatefrompng($uploadUrl);
2506 //convert it into formattd png
2507 header('Content-type: image/png');
2508 //overwrite with same image
2509 imagepng($chart, $uploadImg);
2511 imagedestroy($chart);
2513 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2515 CRM_Utils_System
::civiExit();
2517 elseif ($this->_outputMode
== 'csv') {
2518 CRM_Report_Utils_Report
::export2csv($this, $rows);
2520 elseif ($this->_outputMode
== 'group') {
2521 $group = $this->_params
['groups'];
2522 $this->add2group($group);
2524 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2525 CRM_Report_Form_Instance
::postProcess($this);
2527 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2528 $this->_outputMode
== 'create_report' ) {
2529 $this->_createNew
= TRUE;
2530 CRM_Report_Form_Instance
::postProcess($this);
2534 function storeResultSet() {
2535 $this->_storeResultSet
= TRUE;
2538 function getResultSet() {
2539 return $this->_resultSet
;
2543 * Get Template file name - use default form template if a specific one has not been set up for this report
2546 function getTemplateFileName(){
2547 $defaultTpl = parent
::getTemplateFileName();
2548 $template = CRM_Core_Smarty
::singleton();
2549 if (!$template->template_exists($defaultTpl)) {
2550 $defaultTpl = 'CRM/Report/Form.tpl';
2556 * Compile the report content
2558 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2560 function compileContent(){
2561 $templateFile = $this->getHookedTemplateFileName();
2562 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2566 function postProcess() {
2567 // get ready with post process params
2568 $this->beginPostProcess();
2571 $sql = $this->buildQuery();
2573 // build array of result based on column headers. This method also allows
2574 // modifying column headers before using it to build result set i.e $rows.
2576 $this->buildRows($sql, $rows);
2578 // format result set.
2579 $this->formatDisplay($rows);
2581 // assign variables to templates
2582 $this->doTemplateAssignment($rows);
2584 // do print / pdf / instance stuff if needed
2585 $this->endPostProcess($rows);
2588 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2589 // lets do the pager if in html mode
2590 $this->_limit
= NULL;
2591 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2592 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2594 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2596 if (!$pageId && !empty($_POST)) {
2597 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2598 $pageId = max((int)@$_POST['crmPID_B'], 1);
2600 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2601 $pageId = max((int)@$_POST['crmPID'], 1);
2603 unset($_POST['crmPID_B'], $_POST['crmPID']);
2606 $pageId = $pageId ?
$pageId : 1;
2607 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2608 $offset = ($pageId - 1) * $rowCount;
2610 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2611 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2613 $this->_limit
= " LIMIT $offset, $rowCount";
2614 return array($offset, $rowCount);
2618 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2619 if ($this->_limit
&& ($this->_limit
!= '')) {
2620 $sql = "SELECT FOUND_ROWS();";
2621 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2623 'total' => $this->_rowsFound
,
2624 'rowCount' => $rowCount,
2625 'status' => ts('Records') . ' %%StatusMessage%%',
2626 'buttonBottom' => 'PagerBottomButton',
2627 'buttonTop' => 'PagerTopButton',
2628 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2631 $pager = new CRM_Utils_Pager($params);
2632 $this->assign_by_ref('pager', $pager);
2636 function whereGroupClause($field, $value, $op) {
2638 $smartGroupQuery = "";
2640 $group = new CRM_Contact_DAO_Group();
2641 $group->is_active
= 1;
2643 $smartGroups = array();
2644 while ($group->fetch()) {
2645 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2646 $smartGroups[] = $group->id
;
2650 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2652 $smartGroupQuery = '';
2653 if (!empty($smartGroups)) {
2654 $smartGroups = implode(',', $smartGroups);
2655 $smartGroupQuery = " UNION DISTINCT
2656 SELECT DISTINCT smartgroup_contact.contact_id
2657 FROM civicrm_group_contact_cache smartgroup_contact
2658 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2661 $sqlOp = $this->getSQLOperator($op);
2662 if (!is_array($value)) {
2663 $value = array($value);
2665 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2667 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2668 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2669 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2670 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2671 {$smartGroupQuery} ) ";
2674 function whereTagClause($field, $value, $op) {
2675 // not using left join in query because if any contact
2676 // belongs to more than one tag, results duplicate
2678 $sqlOp = $this->getSQLOperator($op);
2679 if (!is_array($value)) {
2680 $value = array($value);
2682 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2684 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2685 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2686 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2687 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2690 function buildACLClause($tableAlias = 'contact_a') {
2691 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2694 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2695 if (empty($this->_customGroupExtends
)) {
2698 if (!is_array($this->_customGroupExtends
)) {
2699 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2701 $customGroupWhere = '';
2702 if (!empty($permCustomGroupIds)) {
2703 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2706 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2707 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2708 FROM civicrm_custom_group cg
2709 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2710 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2712 cg.is_active = 1 AND
2713 cf.is_active = 1 AND
2714 cf.is_searchable = 1
2715 ORDER BY cg.weight, cf.weight";
2716 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2719 while ($customDAO->fetch()) {
2720 if ($customDAO->table_name
!= $curTable) {
2721 $curTable = $customDAO->table_name
;
2722 $curFields = $curFilters = array();
2725 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2726 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2727 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2728 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2731 'fields', 'filters', 'group_bys') as $colKey) {
2732 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2733 $this->_columns
[$curTable][$colKey] = array();
2737 $fieldName = 'custom_' . $customDAO->cf_id
;
2740 // this makes aliasing work in favor
2741 $curFields[$fieldName] = array(
2742 'name' => $customDAO->column_name
,
2743 'title' => $customDAO->label
,
2744 'dataType' => $customDAO->data_type
,
2745 'htmlType' => $customDAO->html_type
,
2748 if ($this->_customGroupFilters
) {
2749 // this makes aliasing work in favor
2750 $curFilters[$fieldName] = array(
2751 'name' => $customDAO->column_name
,
2752 'title' => $customDAO->label
,
2753 'dataType' => $customDAO->data_type
,
2754 'htmlType' => $customDAO->html_type
,
2758 switch ($customDAO->data_type
) {
2761 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2762 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2763 // CRM-6946, show time part for datetime date fields
2764 if ($customDAO->time_format
) {
2765 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2770 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2771 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2775 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2779 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2780 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2784 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2785 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2789 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2790 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2794 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2796 if (!empty($customDAO->option_group_id
)) {
2797 if (in_array($customDAO->html_type
, array(
2798 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2799 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2802 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2804 if ($this->_customGroupFilters
) {
2805 $curFilters[$fieldName]['options'] = array();
2806 $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')));
2807 while ($ogDAO->fetch()) {
2808 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2814 case 'StateProvince':
2815 if (in_array($customDAO->html_type
, array(
2816 'Multi-Select State/Province'))) {
2817 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2820 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2822 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2826 if (in_array($customDAO->html_type
, array(
2827 'Multi-Select Country'))) {
2828 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2831 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2833 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2836 case 'ContactReference':
2837 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2838 $curFilters[$fieldName]['name'] = 'display_name';
2839 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2841 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2842 $curFields[$fieldName]['name'] = 'display_name';
2843 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2847 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2848 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2851 if (!array_key_exists('type', $curFields[$fieldName])) {
2852 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2856 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2858 if ($this->_customGroupFilters
) {
2859 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2861 if ($this->_customGroupGroupBy
) {
2862 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2867 function customDataFrom() {
2868 if (empty($this->_customGroupExtends
)) {
2871 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2873 foreach ($this->_columns
as $table => $prop) {
2874 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2875 $extendsTable = $mapper[$prop['extends']];
2877 // check field is in params
2878 if (!$this->isFieldSelected($prop)) {
2881 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
2883 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2885 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
2886 // handle for ContactReference
2887 if (array_key_exists('fields', $prop)) {
2888 foreach ($prop['fields'] as $fieldName => $field) {
2889 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2890 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2892 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2900 function isFieldSelected($prop) {
2905 if (!empty($this->_params
['fields'])) {
2906 foreach (array_keys($prop['fields']) as $fieldAlias) {
2907 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2908 if ($customFieldId) {
2909 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2913 //might be survey response field.
2914 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2915 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2923 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2924 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2925 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2931 if (!empty($this->_params
['order_bys'])) {
2932 foreach (array_keys($prop['fields']) as $fieldAlias) {
2933 foreach ($this->_params
['order_bys'] as $orderBy) {
2934 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2941 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2942 foreach ($prop['filters'] as $fieldAlias => $val) {
2944 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2945 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2946 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2947 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2953 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2954 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2965 * Check for empty order_by configurations and remove them; also set
2966 * template to hide them.
2968 function preProcessOrderBy(&$formValues) {
2969 // Object to show/hide form elements
2970 $_showHide = new CRM_Core_ShowHideBlocks('', '');
2972 $_showHide->addShow('optionField_1');
2974 // Cycle through order_by options; skip any empty ones, and hide them as well
2977 if (!empty($formValues['order_bys'])) {
2978 foreach ($formValues['order_bys'] as $order_by) {
2979 if ($order_by['column'] && $order_by['column'] != '-') {
2980 $_showHide->addShow('optionField_' . $n);
2981 $orderBys[$n] = $order_by;
2986 for ($i = $n; $i <= 5; $i++
) {
2988 $_showHide->addHide('optionField_' . $i);
2992 // overwrite order_by options with modified values
2993 if (!empty($orderBys)) {
2994 $formValues['order_bys'] = $orderBys;
2997 $formValues['order_bys'] = array(1 => array('column' => '-'));
3000 // assign show/hide data to template
3001 $_showHide->addToTemplate();
3005 * Does table name have columns in SELECT clause?
3007 * @param string $tableName Name of table (index of $this->_columns array)
3011 function isTableSelected($tableName) {
3012 return in_array($tableName, $this->selectedTables());
3016 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3017 * (building the array if it's unset)
3019 * @return Array $this->_selectedTables
3021 function selectedTables() {
3022 if (!$this->_selectedTables
) {
3023 $orderByColumns = array();
3024 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3025 foreach ($this->_params
['order_bys'] as $orderBy) {
3026 $orderByColumns[] = $orderBy['column'];
3030 foreach ($this->_columns
as $tableName => $table) {
3031 if (array_key_exists('fields', $table)) {
3032 foreach ($table['fields'] as $fieldName => $field) {
3033 if (CRM_Utils_Array
::value('required', $field) ||
3034 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3036 $this->_selectedTables
[] = $tableName;
3041 if (array_key_exists('order_bys', $table)) {
3042 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3043 if (in_array($orderByName, $orderByColumns)) {
3044 $this->_selectedTables
[] = $tableName;
3049 if (array_key_exists('filters', $table)) {
3050 foreach ($table['filters'] as $filterName => $filter) {
3051 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3052 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3053 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3055 $this->_selectedTables
[] = $tableName;
3062 return $this->_selectedTables
;
3066 * @deprecated - use getAddressColumns which is a more accurate description
3067 * and also accepts an array of options rather than a long list
3069 * function for adding address fields to construct function in reports
3070 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3071 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3072 * @return array address fields for construct clause
3074 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3075 'country_id' => TRUE)) {
3076 $addressFields = array(
3077 'civicrm_address' =>
3079 'dao' => 'CRM_Core_DAO_Address',
3083 array('title' => ts('Address Name'),
3084 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3087 array('title' => ts('Street Address'),
3088 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3090 'supplemental_address_1' =>
3091 array('title' => ts('Supplementary Address Field 1'),
3092 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3094 'supplemental_address_2' =>
3095 array('title' => ts('Supplementary Address Field 2'),
3096 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3100 'name' => 'street_number',
3101 'title' => ts('Street Number'),
3103 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3107 'name' => 'street_name',
3108 'title' => ts('Street Name'),
3110 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3114 'name' => 'street_unit',
3115 'title' => ts('Street Unit'),
3117 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3120 array('title' => ts('City'),
3121 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3124 array('title' => ts('Postal Code'),
3125 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3127 'postal_code_suffix' =>
3128 array('title' => ts('Postal Code Suffix'),
3129 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3132 array('title' => ts('County'),
3133 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3135 'state_province_id' =>
3136 array('title' => ts('State/Province'),
3137 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3140 array('title' => ts('Country'),
3141 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3144 'grouping' => 'location-fields',
3149 $addressFields['civicrm_address']['filters'] = array(
3150 'street_number' => array('title' => ts('Street Number'),
3152 'name' => 'street_number',
3154 'street_name' => array('title' => ts('Street Name'),
3155 'name' => 'street_name',
3156 'operator' => 'like',
3158 'postal_code' => array('title' => ts('Postal Code'),
3160 'name' => 'postal_code',
3162 'city' => array('title' => ts('City'),
3163 'operator' => 'like',
3166 'county_id' => array(
3167 'name' => 'county_id',
3168 'title' => ts('County'),
3169 'type' => CRM_Utils_Type
::T_INT
,
3171 CRM_Report_Form
::OP_MULTISELECT
,
3173 CRM_Core_PseudoConstant
::county(),
3175 'state_province_id' => array(
3176 'name' => 'state_province_id',
3177 'title' => ts('State/Province'),
3178 'type' => CRM_Utils_Type
::T_INT
,
3180 CRM_Report_Form
::OP_MULTISELECT
,
3182 CRM_Core_PseudoConstant
::stateProvince(),
3184 'country_id' => array(
3185 'name' => 'country_id',
3186 'title' => ts('Country'),
3187 'type' => CRM_Utils_Type
::T_INT
,
3189 CRM_Report_Form
::OP_MULTISELECT
,
3191 CRM_Core_PseudoConstant
::country(),
3197 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3198 'street_number' => array('title' => 'Odd / Even Street Number'),
3199 'street_address' => NULL,
3201 'postal_code' => NULL,
3206 $addressFields['civicrm_address']['group_bys'] = array(
3207 'street_address' => NULL,
3209 'postal_code' => NULL,
3210 'state_province_id' =>
3211 array('title' => ts('State/Province'),
3214 array('title' => ts('Country'),
3217 array('title' => ts('County'),
3221 return $addressFields;
3225 * Do AlterDisplay processing on Address Fields
3227 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3228 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3229 $entryFound = FALSE;
3231 if (array_key_exists('civicrm_address_country_id', $row)) {
3232 if ($value = $row['civicrm_address_country_id']) {
3233 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3234 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3235 "reset=1&force=1&{$criteriaQueryParams}&" .
3236 "country_id_op=in&country_id_value={$value}",
3237 $this->_absoluteUrl
, $this->_id
3239 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3240 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3247 if (array_key_exists('civicrm_address_county_id', $row)) {
3248 if ($value = $row['civicrm_address_county_id']) {
3249 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3250 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3251 "reset=1&force=1&{$criteriaQueryParams}&" .
3252 "county_id_op=in&county_id_value={$value}",
3253 $this->_absoluteUrl
, $this->_id
3255 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3256 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3262 // handle state province
3263 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3264 if ($value = $row['civicrm_address_state_province_id']) {
3265 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3267 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3268 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3269 $this->_absoluteUrl
, $this->_id
3271 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3272 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3283 * Adjusts dates passed in to YEAR() for fiscal year.
3285 function fiscalYearOffset($fieldName) {
3286 $config = CRM_Core_Config
::singleton();
3287 $fy = $config->fiscalYearStart
;
3288 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3289 return "YEAR( $fieldName )";
3291 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3295 * Add Address into From Table if required
3297 function addAddressFromClause() {
3298 // include address field if address column is to be included
3299 if ((isset($this->_addressField
) &&
3300 $this->_addressField
3302 $this->isTableSelected('civicrm_address')
3305 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3306 ON ({$this->_aliases['civicrm_contact']}.id =
3307 {$this->_aliases['civicrm_address']}.contact_id) AND
3308 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3313 * Add Phone into From Table if required
3315 function addPhoneFromClause() {
3316 // include address field if address column is to be included
3317 if ($this->isTableSelected('civicrm_phone')
3320 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3321 ON ({$this->_aliases['civicrm_contact']}.id =
3322 {$this->_aliases['civicrm_phone']}.contact_id) AND
3323 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3328 * Get phone columns to add to array
3329 * @param array $options
3330 * - prefix Prefix to add to table (in case of more than one instance of the table)
3331 * - prefix_label Label to give columns from this phone table instance
3332 * @return array phone columns definition
3334 function getPhoneColumns($options = array()){
3335 $defaultOptions = array(
3337 'prefix_label' => '',
3340 $options = array_merge($defaultOptions,$options);
3343 $options['prefix'] . 'civicrm_phone' => array(
3344 'dao' => 'CRM_Core_DAO_Phone',
3346 $options['prefix'] . 'phone' => array(
3347 'title' => ts($options['prefix_label'] . 'Phone'),
3357 * Get address columns to add to array
3358 * @param array $options
3359 * - prefix Prefix to add to table (in case of more than one instance of the table)
3360 * - prefix_label Label to give columns from this address table instance
3361 * @return array address columns definition
3363 function getAddressColumns($options = array()){
3364 $defaultOptions = array(
3366 'prefix_label' => '',
3370 'defaults' => array(
3373 $options = array_merge($defaultOptions,$options);
3374 return $this->addAddressFields(
3375 $options['group_by'],
3376 $options['order_by'],
3377 $options['filters'],
3378 $options['defaults']
3383 function add2group($groupID) {
3384 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3385 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3386 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3388 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3389 $dao = CRM_Core_DAO
::executeQuery($sql);
3391 $contact_ids = array();
3392 // Add resulting contacts to group
3393 while ($dao->fetch()) {
3394 if ($dao->addtogroup_contact_id
) {
3395 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3399 if ( !empty($contact_ids) ) {
3400 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3401 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3404 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3409 /* function used for showing charts on print screen */
3410 static function uploadChartImage() {
3411 // upload strictly for '.png' images
3412 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3413 if (preg_match('/\.png$/', $name)) {
3415 // POST data is usually string data, but we are passing a RAW .png
3416 // so PHP is a bit confused and $_POST is empty. But it has saved
3417 // the raw bits into $HTTP_RAW_POST_DATA
3419 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3421 // prepare the directory
3422 $config = CRM_Core_Config
::singleton();
3423 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3424 if (!file_exists($defaultPath)) {
3425 mkdir($defaultPath, 0777, TRUE);
3428 // full path to the saved image including filename
3429 $destination = $defaultPath . $name;
3432 $jfh = fopen($destination, 'w') or die("can't open file");
3433 fwrite($jfh, $httpRawPostData);
3435 CRM_Utils_System
::civiExit();