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 $_customGroupFilters = TRUE;
139 protected $_customGroupGroupBy = FALSE;
140 protected $_customGroupJoin = 'LEFT JOIN';
146 protected $_tagFilter = FALSE;
149 * build groups filter
152 protected $_groupFilter = FALSE;
159 public $_navigation = array();
161 public $_drilldownReport = array();
164 * An attribute for checkbox/radio form field layout
168 protected $_fourColumnAttribute = array(
169 '</td><td width="25%">', '</td><td width="25%">',
170 '</td><td width="25%">', '</tr><tr><td>',
173 protected $_force = 1;
175 protected $_params = NULL;
176 protected $_formValues = NULL;
177 protected $_instanceValues = NULL;
179 protected $_instanceForm = FALSE;
180 protected $_criteriaForm = FALSE;
182 protected $_instanceButtonName = NULL;
183 protected $_createNewButtonName = NULL;
184 protected $_printButtonName = NULL;
185 protected $_pdfButtonName = NULL;
186 protected $_csvButtonName = NULL;
187 protected $_groupButtonName = NULL;
188 protected $_chartButtonName = NULL;
189 protected $_csvSupported = TRUE;
190 protected $_add2groupSupported = TRUE;
191 protected $_groups = NULL;
192 protected $_grandFlag = FALSE;
193 protected $_rowsFound = NULL;
194 protected $_selectAliases = array();
195 protected $_rollup = NULL;
196 protected $_limit = NULL;
197 protected $_sections = NULL;
198 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
199 protected $_absoluteUrl = FALSE;
202 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
206 protected $_storeResultSet = FALSE;
209 * When _storeResultSet Flag is set use this var to store result set in form of array
213 protected $_resultSet = array();
216 * To what frequency group-by a date column
220 protected $_groupByDateFreq = array(
222 'YEARWEEK' => 'Week',
223 'QUARTER' => 'Quarter',
228 * Variables to hold the acl inner join and where clause
230 protected $_aclFrom = NULL;
231 protected $_aclWhere = NULL;
234 * Array of DAO tables having columns included in SELECT or ORDER BY clause
238 protected $_selectedTables;
240 public $_having = NULL;
241 public $_select = NULL;
242 public $_columnHeaders = array();
243 public $_orderBy = NULL;
244 public $_groupBy = NULL;
245 public $_whereClauses = array();
246 public $_havingClauses = array();
249 * Variable to hold the currency alias
251 protected $_currencyColumn = NULL;
256 function __construct() {
257 parent
::__construct();
260 if ($this->_tagFilter
) {
261 $this->buildTagFilter();
263 if ($this->_exposeContactID
) {
264 if (array_key_exists('civicrm_contact', $this->_columns
)) {
265 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
267 'title' => 'Contact ID',
273 if ($this->_groupFilter
) {
274 $this->buildGroupFilter();
277 // Get all custom groups
278 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
280 // Get the custom groupIds for which the user have VIEW permission
281 require_once 'CRM/ACL/API.php';
282 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
284 // do not allow custom data for reports if user don't have
285 // permission to access custom data.
286 if (!empty($this->_customGroupExtends
) && !CRM_Core_Permission
::check('access all custom data') && empty($permCustomGroupIds)) {
287 $this->_customGroupExtends
= array();
290 // merge custom data columns to _columns list, if any
291 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
293 // add / modify display columns, filters ..etc
294 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
296 //assign currencyColumn variable to tpl
297 $this->assign('currencyColumn', $this->_currencyColumn
);
300 function preProcessCommon() {
302 CRM_Utils_Request
::retrieve(
305 CRM_Core_DAO
::$_nullObject
308 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
310 $this->assign('section', $this->_section
);
311 CRM_Core_Region
::instance('page-header')->add(array(
312 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
315 $this->_id
= $this->get('instanceId');
317 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
319 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
323 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
324 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
325 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
328 $this->assign('instanceId', $this->_id
);
329 $params = array('id' => $this->_id
);
330 $this->_instanceValues
= array();
331 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
333 $this->_instanceValues
335 if (empty($this->_instanceValues
)) {
336 CRM_Core_Error
::fatal("Report could not be loaded.");
339 if (!empty($this->_instanceValues
['permission']) &&
340 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
341 CRM_Core_Permission
::check('administer Reports')
344 CRM_Utils_System
::permissionDenied();
345 CRM_Utils_System
::civiExit();
348 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
350 $this->_formValues
= unserialize($formValues);
353 $this->_formValues
= NULL;
356 // lets always do a force if reset is found in the url.
357 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
362 $this->assign('mode', 'instance');
365 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
366 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
367 if (($instanceCount > 0) && $optionValueID) {
368 $this->assign('instanceUrl',
369 CRM_Utils_System
::url('civicrm/report/list',
370 "reset=1&ovid=$optionValueID"
374 if ($optionValueID) {
375 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
379 $this->assign('mode', 'template');
382 // lets display the Report Settings section
383 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
385 // Do not display Report Settings section if administer Reports permission is absent OR
386 // if report instance is reserved and administer reserved reports absent
387 if (!CRM_Core_Permission
::check('administer Reports') ||
388 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
389 $this->_instanceForm
= FALSE;
392 $this->assign('criteriaForm', FALSE);
393 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
394 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
395 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
396 $this->assign('criteriaForm', TRUE);
397 $this->_criteriaForm
= TRUE;
401 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
402 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
403 $this->_printButtonName
= $this->getButtonName('submit', 'print');
404 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
405 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
406 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
407 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
410 function addBreadCrumb() {
414 'title' => ts('Report Templates'),
415 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
419 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
422 function preProcess() {
423 $this->preProcessCommon();
426 $this->addBreadCrumb();
429 foreach ($this->_columns
as $tableName => $table) {
431 if (!isset($table['alias'])) {
432 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
435 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
438 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
440 $daoOrBaoName = NULL;
441 // higher preference to bao object
442 if (array_key_exists('bao', $table)) {
443 $daoOrBaoName = $table['bao'];
444 $expFields = $daoOrBaoName::exportableFields( );
446 elseif (array_key_exists('dao', $table)){
447 $daoOrBaoName = $table['dao'];
448 $expFields = $daoOrBaoName::export( );
451 $expFields = array();
454 $doNotCopy = array('required');
456 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
457 foreach ($fieldGroups as $fieldGrp) {
458 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
459 foreach ($table[$fieldGrp] as $fieldName => $field) {
460 // $name is the field name used to reference the BAO/DAO export fields array
461 $name = isset($field['name']) ?
$field['name'] : $fieldName;
463 // Sometimes the field name key in the BAO/DAO export fields array is
464 // different from the actual database field name.
465 // Unset $field['name'] so that actual database field name can be obtained
466 // from the BAO/DAO export fields array.
467 unset($field['name']);
469 if (array_key_exists($name, $expFields)) {
470 foreach ($doNotCopy as $dnc) {
471 // unset the values we don't want to be copied.
472 unset($expFields[$name][$dnc]);
475 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
478 foreach ($expFields[$name] as $property => $val) {
479 if (!array_key_exists($property, $field)) {
480 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
487 if (CRM_Utils_Array
::value('no_repeat', $field)) {
488 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
490 if (CRM_Utils_Array
::value('no_display', $field)) {
491 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
494 // set alias = table-name, unless already set
495 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
496 $this->_columns
[$tableName]['alias'] : $tableName
498 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
500 // set name = fieldName, unless already set
501 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
502 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
505 // set dbAlias = alias.name, unless already set
506 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
507 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
510 // a few auto fills for filters
511 if ($fieldGrp == 'filters') {
512 // fill operator types
513 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
514 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
515 case CRM_Utils_Type
::T_MONEY
:
516 case CRM_Utils_Type
::T_FLOAT
:
517 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
519 case CRM_Utils_Type
::T_INT
:
520 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
522 case CRM_Utils_Type
::T_DATE
:
523 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
525 case CRM_Utils_Type
::T_BOOLEAN
:
526 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
527 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
528 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
529 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
534 (array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
535 ||
array_key_exists('enumValues', $this->_columns
[$tableName][$fieldGrp][$fieldName]))
537 // with multiple options operator-type is generally multi-select
538 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
539 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
541 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
552 // copy filters to a separate handy variable
553 if (array_key_exists('filters', $table)) {
554 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
557 if (array_key_exists('group_bys', $table)) {
558 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
561 if (array_key_exists('fields', $table)) {
562 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
567 $this->setDefaultValues(FALSE);
570 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
571 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
572 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
573 CRM_Report_Utils_Get
::processChart($this->_defaults
);
576 $this->_formValues
= $this->_defaults
;
577 $this->postProcess();
581 function setDefaultValues($freeze = TRUE) {
582 $freezeGroup = array();
584 // FIXME: generalizing form field naming conventions would reduce
585 // lots of lines below.
586 foreach ($this->_columns
as $tableName => $table) {
587 if (array_key_exists('fields', $table)) {
588 foreach ($table['fields'] as $fieldName => $field) {
589 if (!array_key_exists('no_display', $field)) {
590 if (isset($field['required'])) {
592 $this->_defaults
['fields'][$fieldName] = 1;
595 // find element object, so that we could use quickform's freeze method
596 // for required elements
597 $obj = $this->getElementFromGroup("fields", $fieldName);
599 $freezeGroup[] = $obj;
603 elseif (isset($field['default'])) {
604 $this->_defaults
['fields'][$fieldName] = $field['default'];
610 if (array_key_exists('group_bys', $table)) {
611 foreach ($table['group_bys'] as $fieldName => $field) {
612 if (isset($field['default'])) {
613 if (CRM_Utils_Array
::value('frequency', $field)) {
614 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
616 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
620 if (array_key_exists('filters', $table)) {
621 foreach ($table['filters'] as $fieldName => $field) {
622 if (isset($field['default'])) {
623 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
624 if(is_array($field['default'])){
625 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
626 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
627 $this->_defaults
["{$fieldName}_relative"] = 0;
630 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
634 $this->_defaults
["{$fieldName}_value"] = $field['default'];
637 //assign default value as "in" for multiselect
638 //operator, To freeze the select element
639 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
640 $this->_defaults
["{$fieldName}_op"] = 'in';
642 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
643 $this->_defaults
["{$fieldName}_op"] = 'mhas';
645 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
646 $this->_defaults
["{$fieldName}_op"] = $op;
652 array_key_exists('order_bys', $table) &&
653 is_array($table['order_bys'])
655 if (!array_key_exists('order_bys', $this->_defaults
)) {
656 $this->_defaults
['order_bys'] = array();
658 foreach ($table['order_bys'] as $fieldName => $field) {
660 CRM_Utils_Array
::value('default', $field) ||
661 CRM_Utils_Array
::value('default_order', $field) ||
662 CRM_Utils_Array
::value('default_is_section', $field) ||
663 CRM_Utils_Array
::value('default_weight', $field)
666 'column' => $fieldName,
667 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
668 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
671 if (CRM_Utils_Array
::value('default_weight', $field)) {
672 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
675 array_unshift($this->_defaults
['order_bys'], $order_by);
681 foreach ($this->_options
as $fieldName => $field) {
682 if (isset($field['default'])) {
683 $this->_defaults
['options'][$fieldName] = $field['default'];
688 if (!empty($this->_submitValues
)) {
689 $this->preProcessOrderBy($this->_submitValues
);
692 $this->preProcessOrderBy($this->_defaults
);
695 // lets finish freezing task here itself
696 if (!empty($freezeGroup)) {
697 foreach ($freezeGroup as $elem) {
702 if ($this->_formValues
) {
703 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
706 if ($this->_instanceValues
) {
707 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
710 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
712 return $this->_defaults
;
715 function getElementFromGroup($group, $grpFieldName) {
716 $eleObj = $this->getElement($group);
717 foreach ($eleObj->_elements
as $index => $obj) {
718 if ($grpFieldName == $obj->_attributes
['name']) {
725 function addColumns() {
728 foreach ($this->_columns
as $tableName => $table) {
729 if (array_key_exists('fields', $table)) {
730 foreach ($table['fields'] as $fieldName => $field) {
732 if (!array_key_exists('no_display', $field)) {
733 foreach ( array('table', 'field') as $var) {
734 if (!empty($
{$var}['grouping'])) {
735 if (!is_array($
{$var}['grouping'])) {
736 $tableName = $
{$var}['grouping'];
738 $tableName = array_keys($
{$var}['grouping']);
739 $tableName = $tableName[0];
740 $groupTitle = array_values($
{$var}['grouping']);
741 $groupTitle = $groupTitle[0];
746 if (!$groupTitle && isset($table['group_title'])) {
747 $groupTitle = $table['group_title'];
750 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
751 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
752 $colGroups[$tableName]['group_title'] = $groupTitle;
755 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
761 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
762 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
764 $this->assign('colGroups', $colGroups);
767 function addFilters() {
768 $options = $filters = array();
770 foreach ($this->_filters
as $table => $attributes) {
771 foreach ($attributes as $fieldName => $field) {
772 // get ready with option value pair
773 // @ 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
775 $operations = $this->getOperationPair(
776 CRM_Utils_Array
::value('operatorType', $field),
779 $filters[$table][$fieldName] = $field;
781 switch (CRM_Utils_Array
::value('operatorType', $field)) {
782 case CRM_Report_Form
::OP_MONTH
:
783 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
784 // If there's no option list for this filter, define one.
785 $field['options'] = array(
794 9 => ts('September'),
796 11 => ts('November'),
797 12 => ts('December'),
799 // Add this option list to this column _columns. This is
800 // required so that filter statistics show properly.
801 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
803 case CRM_Report_FORM
::OP_MULTISELECT
:
804 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
805 // assume a multi-select field
806 if (!empty($field['options'])) {
807 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
808 if (count($operations) <= 1) {
811 $select = $this->addElement('select', "{$fieldName}_value", NULL,
812 $field['options'], array(
814 'style' => 'min-width:250px',
817 $select->setMultiple(TRUE);
821 case CRM_Report_FORM
::OP_SELECT
:
822 // assume a select field
823 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
824 if (!empty($field['options']))
825 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
828 case CRM_Report_FORM
::OP_DATE
:
829 // build datetime fields
830 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
834 case CRM_Report_FORM
::OP_DATETIME
:
835 // build datetime fields
836 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
840 case CRM_Report_FORM
::OP_INT
:
841 case CRM_Report_FORM
::OP_FLOAT
:
842 // and a min value input box
843 $this->add('text', "{$fieldName}_min", ts('Min'));
844 // and a max value input box
845 $this->add('text', "{$fieldName}_max", ts('Max'));
847 // default type is string
848 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
849 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
851 // we need text box for value input
852 $this->add('text', "{$fieldName}_value", NULL);
857 $this->assign('filters', $filters);
860 function addOptions() {
861 if (!empty($this->_options
)) {
862 // FIXME: For now lets build all elements as checkboxes.
863 // Once we clear with the format we can build elements based on type
866 foreach ($this->_options
as $fieldName => $field) {
867 if ($field['type'] == 'select') {
868 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
870 else if ($field['type'] == 'checkbox') {
871 $options[$field['title']] = $fieldName;
872 $this->addCheckBox($fieldName, NULL,
874 NULL, NULL, NULL, $this->_fourColumnAttribute
879 $this->assign('otherOptions', $this->_options
);
882 function addChartOptions() {
883 if (!empty($this->_charts
)) {
884 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
885 $this->assign('charts', $this->_charts
);
886 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
890 function addGroupBys() {
891 $options = $freqElements = array();
893 foreach ($this->_columns
as $tableName => $table) {
894 if (array_key_exists('group_bys', $table)) {
895 foreach ($table['group_bys'] as $fieldName => $field) {
896 if (!empty($field)) {
897 $options[$field['title']] = $fieldName;
898 if (CRM_Utils_Array
::value('frequency', $field)) {
899 $freqElements[$field['title']] = $fieldName;
905 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
906 NULL, NULL, NULL, $this->_fourColumnAttribute
908 $this->assign('groupByElements', $options);
910 foreach ($freqElements as $name) {
911 $this->addElement('select', "group_bys_freq[$name]",
912 ts('Frequency'), $this->_groupByDateFreq
917 function addOrderBys() {
919 foreach ($this->_columns
as $tableName => $table) {
921 // Report developer may define any column to order by; include these as order-by options
922 if (array_key_exists('order_bys', $table)) {
923 foreach ($table['order_bys'] as $fieldName => $field) {
924 if (!empty($field)) {
925 $options[$fieldName] = $field['title'];
930 /* Add searchable custom fields as order-by options, if so requested
931 * (These are already indexed, so allowing to order on them is cheap.)
935 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
936 foreach ($table['fields'] as $fieldName => $field) {
937 if (!array_key_exists('no_display', $field)) {
938 $options[$fieldName] = $field['title'];
946 $this->assign('orderByOptions', $options);
948 if (!empty($options)) {
950 '-' => ' - none - ') +
$options;
951 for ($i = 1; $i <= 5; $i++
) {
952 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
953 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
954 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
959 function buildInstanceAndButtons() {
960 CRM_Report_Form_Instance
::buildForm($this);
962 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
964 $this->addElement('submit', $this->_instanceButtonName
, $label);
965 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
966 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
969 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
971 if ($this->_instanceForm
) {
972 $this->assign('instanceForm', TRUE);
975 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
976 $this->addElement('submit', $this->_printButtonName
, $label);
978 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
979 $this->addElement('submit', $this->_pdfButtonName
, $label);
981 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
983 if ($this->_csvSupported
) {
984 $this->addElement('submit', $this->_csvButtonName
, $label);
987 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
988 $this->addElement('select', 'groups', ts('Group'),
989 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
991 $this->assign('group', TRUE);
994 $label = ts('Add these Contacts to Group');
995 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
997 $this->addChartOptions();
998 $this->addButtons(array(
1001 'name' => ts('Preview Report'),
1002 'isDefault' => TRUE,
1008 function buildQuickForm() {
1009 $this->addColumns();
1011 $this->addFilters();
1013 $this->addOptions();
1015 $this->addGroupBys();
1017 $this->addOrderBys();
1019 $this->buildInstanceAndButtons();
1021 //add form rule for report
1022 if (is_callable(array(
1023 $this, 'formRule'))) {
1024 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1028 // a formrule function to ensure that fields selected in group_by
1029 // (if any) should only be the ones present in display/select fields criteria;
1030 // note: works if and only if any custom field selected in group_by.
1031 function customDataFormRule($fields, $ignoreFields = array( )) {
1033 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1034 foreach ($this->_columns
as $tableName => $table) {
1035 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1036 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1037 if (array_key_exists($fieldName, $fields['group_bys']) &&
1038 !array_key_exists($fieldName, $fields['fields'])
1040 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1042 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1043 foreach ($fields['fields'] as $fld => $val) {
1044 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1045 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1056 // Note: $fieldName param allows inheriting class to build operationPairs
1057 // specific to a field.
1058 function getOperationPair($type = "string", $fieldName = NULL) {
1059 // FIXME: At some point we should move these key-val pairs
1060 // to option_group and option_value table.
1062 case CRM_Report_FORM
::OP_INT
:
1063 case CRM_Report_FORM
::OP_FLOAT
:
1065 'lte' => ts('Is less than or equal to'),
1066 'gte' => ts('Is greater than or equal to'),
1067 'bw' => ts('Is between'),
1068 'eq' => ts('Is equal to'),
1069 'lt' => ts('Is less than'),
1070 'gt' => ts('Is greater than'),
1071 'neq' => ts('Is not equal to'),
1072 'nbw' => ts('Is not between'),
1073 'nll' => ts('Is empty (Null)'),
1074 'nnll' => ts('Is not empty (Null)'),
1078 case CRM_Report_FORM
::OP_SELECT
:
1080 'eq' => ts('Is equal to'),
1083 case CRM_Report_FORM
::OP_MONTH
:
1084 case CRM_Report_FORM
::OP_MULTISELECT
:
1086 'in' => ts('Is one of'),
1087 'notin' => ts('Is not one of'),
1091 case CRM_Report_FORM
::OP_DATE
:
1093 'nll' => ts('Is empty (Null)'),
1094 'nnll' => ts('Is not empty (Null)'),
1098 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1099 // use this operator for the values, concatenated with separator. For e.g if
1100 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1102 'mhas' => ts('Is one of'),
1108 'has' => ts('Contains'),
1109 'sw' => ts('Starts with'),
1110 'ew' => ts('Ends with'),
1111 'nhas' => ts('Does not contain'),
1112 'eq' => ts('Is equal to'),
1113 'neq' => ts('Is not equal to'),
1114 'nll' => ts('Is empty (Null)'),
1115 'nnll' => ts('Is not empty (Null)'),
1120 function buildTagFilter() {
1121 $contactTags = CRM_Core_BAO_Tag
::getTags();
1122 if (!empty($contactTags)) {
1123 $this->_columns
['civicrm_tag'] = array(
1124 'dao' => 'CRM_Core_DAO_Tag',
1130 'title' => ts('Tag'),
1132 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1133 'options' => $contactTags,
1141 * Adds group filters to _columns (called from _Constuct
1143 function buildGroupFilter() {
1144 $this->_columns
['civicrm_group']['filters'] = array(
1147 'name' => 'group_id',
1148 'title' => ts('Group'),
1149 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1151 'options' => CRM_Core_PseudoConstant
::group(),
1154 if (empty($this->_columns
['civicrm_group']['dao'])) {
1155 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1157 if (empty($this->_columns
['civicrm_group']['alias'])) {
1158 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1162 function getSQLOperator($operator = "like") {
1163 switch ($operator) {
1196 return 'IS NOT NULL';
1204 function whereClause(&$field, $op,
1208 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1214 if (($min !== NULL && strlen($min) > 0) ||
1215 ($max !== NULL && strlen($max) > 0)
1217 $min = CRM_Utils_Type
::escape($min, $type);
1218 $max = CRM_Utils_Type
::escape($max, $type);
1222 $clauses[] = "( {$field['dbAlias']} >= $min )";
1225 $clauses[] = "( {$field['dbAlias']} < $min )";
1230 $clauses[] = "( {$field['dbAlias']} <= $max )";
1233 $clauses[] = "( {$field['dbAlias']} > $max )";
1237 if (!empty($clauses)) {
1239 $clause = implode(' AND ', $clauses);
1242 $clause = implode(' OR ', $clauses);
1250 if ($value !== NULL && strlen($value) > 0) {
1251 $value = CRM_Utils_Type
::escape($value, $type);
1252 if (strpos($value, '%') === FALSE) {
1253 $value = "'%{$value}%'";
1256 $value = "'{$value}'";
1258 $sqlOP = $this->getSQLOperator($op);
1259 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1265 if ($value !== NULL && is_array($value) && count($value) > 0) {
1266 $sqlOP = $this->getSQLOperator($op);
1267 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1268 //cycle through selections and esacape values
1269 foreach ($value as $key => $selection) {
1270 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1272 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1275 // for numerical values
1276 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1278 if ($op == 'notin') {
1279 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1282 $clause = "( " . $clause . " )";
1288 // mhas == multiple has
1289 if ($value !== NULL && count($value) > 0) {
1290 $sqlOP = $this->getSQLOperator($op);
1291 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1297 if ($value !== NULL && strlen($value) > 0) {
1298 $value = CRM_Utils_Type
::escape($value, $type);
1299 if (strpos($value, '%') === FALSE) {
1301 $value = "'{$value}%'";
1304 $value = "'%{$value}'";
1308 $value = "'{$value}'";
1310 $sqlOP = $this->getSQLOperator($op);
1311 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1317 $sqlOP = $this->getSQLOperator($op);
1318 $clause = "( {$field['dbAlias']} $sqlOP )";
1322 if ($value !== NULL && strlen($value) > 0) {
1323 if (isset($field['clause'])) {
1324 // FIXME: we not doing escape here. Better solution is to use two
1325 // different types - data-type and filter-type
1326 $clause = $field['clause'];
1329 $value = CRM_Utils_Type
::escape($value, $type);
1330 $sqlOP = $this->getSQLOperator($op);
1331 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1332 $value = "'{$value}'";
1334 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1340 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1341 $clause = $this->whereGroupClause($field, $value, $op);
1343 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1344 // not using left join in query because if any contact
1345 // belongs to more than one tag, results duplicate
1347 $clause = $this->whereTagClause($field, $value, $op);
1353 function dateClause($fieldName,
1354 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1357 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1358 $sqlOP = $this->getSQLOperator($relative);
1359 return "( {$fieldName} {$sqlOP} )";
1362 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1365 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1366 $clauses[] = "( {$fieldName} >= $from )";
1370 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1371 $clauses[] = "( {$fieldName} <= {$to} )";
1374 if (!empty($clauses)) {
1375 return implode(' AND ', $clauses);
1381 * @todo - could not find any instances where this is called
1382 * @param unknown_type $relative
1383 * @param String $from
1384 * @param String_type $to
1385 * @return string|NULL
1387 function dateDisplay($relative, $from, $to) {
1388 list($from, $to) = $this->getFromTo($relative, $from, $to);
1391 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1394 $clauses[] = 'Past';
1398 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1401 $clauses[] = 'Today';
1404 if (!empty($clauses)) {
1405 return implode(' - ', $clauses);
1411 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1412 if (empty($totime)) {
1415 //FIX ME not working for relative
1417 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1418 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1419 $from = substr($dateRange['from'], 0, 8);
1420 //Take only Date Part, Sometime Time part is also present in 'to'
1421 $to = substr($dateRange['to'], 0, 8);
1423 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1424 $to = CRM_Utils_Date
::processDate($to, $totime);
1425 return array($from, $to);
1428 function alterDisplay(&$rows) {
1429 // custom code to alter rows
1432 function alterCustomDataDisplay(&$rows) {
1433 // custom code to alter rows having custom values
1434 if (empty($this->_customGroupExtends
)) {
1438 $customFieldIds = array();
1439 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1440 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1441 $customFieldIds[$fieldAlias] = $fieldId;
1444 if (empty($customFieldIds)) {
1448 $customFields = $fieldValueMap = array();
1449 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1451 // skip for type date and ContactReference since date format is already handled
1453 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1454 FROM civicrm_custom_field cf
1455 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1456 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1457 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1458 cg.is_active = 1 AND
1459 cf.is_active = 1 AND
1460 cf.is_searchable = 1 AND
1461 cf.data_type NOT IN ('ContactReference', 'Date') AND
1462 cf.id IN (" . implode(",", $customFieldIds) . ")";
1464 $dao = CRM_Core_DAO
::executeQuery($query);
1465 while ($dao->fetch()) {
1466 foreach ($customFieldCols as $key) {
1467 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1469 if ($dao->option_group_id
) {
1470 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1475 $entryFound = FALSE;
1476 foreach ($rows as $rowNum => $row) {
1477 foreach ($row as $tableCol => $val) {
1478 if (array_key_exists($tableCol, $customFields)) {
1479 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1484 // skip looking further in rows, if first row itself doesn't
1485 // have the column we need
1492 function formatCustomValues($value, $customField, $fieldValueMap) {
1493 if (CRM_Utils_System
::isNull($value)) {
1497 $htmlType = $customField['html_type'];
1499 switch ($customField['data_type']) {
1501 if ($value == '1') {
1502 $retValue = ts('Yes');
1505 $retValue = ts('No');
1510 $retValue = CRM_Utils_System
::formatWikiURL($value);
1522 if ($htmlType == 'Text') {
1523 $retValue = (float)$value;
1527 if ($htmlType == 'Text') {
1537 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1542 if (in_array($htmlType, array(
1543 'Text', 'TextArea'))) {
1547 case 'StateProvince':
1550 switch ($htmlType) {
1551 case 'Multi-Select Country':
1552 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1553 $customData = array();
1554 foreach ($value as $val) {
1556 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1559 $retValue = implode(', ', $customData);
1562 case 'Select Country':
1563 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1566 case 'Select State/Province':
1567 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1570 case 'Multi-Select State/Province':
1571 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1572 $customData = array();
1573 foreach ($value as $val) {
1575 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1578 $retValue = implode(', ', $customData);
1583 case 'Autocomplete-Select':
1584 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1588 case 'AdvMulti-Select':
1589 case 'Multi-Select':
1590 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1591 $customData = array();
1592 foreach ($value as $val) {
1594 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1597 $retValue = implode(', ', $customData);
1612 function removeDuplicates(&$rows) {
1613 if (empty($this->_noRepeats
)) {
1616 $checkList = array();
1618 foreach ($rows as $key => $list) {
1619 foreach ($list as $colName => $colVal) {
1620 if (array_key_exists($colName, $checkList) &&
1621 $checkList[$colName] == $colVal) {
1622 $rows[$key][$colName] = "";
1624 if (in_array($colName, $this->_noRepeats
)) {
1625 $checkList[$colName] = $colVal;
1631 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1632 foreach ($row as $colName => $colVal) {
1633 if (in_array($colName, $fields)) {
1634 $row[$colName] = $row[$colName];
1636 elseif (isset($this->_columnHeaders
[$colName])) {
1638 $row[$colName] = "Subtotal";
1642 unset($row[$colName]);
1648 function grandTotal(&$rows) {
1649 if (!$this->_rollup ||
($this->_rollup
== '') ||
1650 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1654 $lastRow = array_pop($rows);
1656 foreach ($this->_columnHeaders
as $fld => $val) {
1657 if (!in_array($fld, $this->_statFields
)) {
1658 if (!$this->_grandFlag
) {
1659 $lastRow[$fld] = "Grand Total";
1660 $this->_grandFlag
= TRUE;
1663 $lastRow[$fld] = "";
1668 $this->assign('grandStat', $lastRow);
1672 function formatDisplay(&$rows, $pager = TRUE) {
1673 // set pager based on if any limit was applied in the query.
1678 // allow building charts if any
1679 if (!empty($this->_params
['charts']) && !empty($rows)) {
1680 $this->buildChart($rows);
1681 $this->assign('chartEnabled', TRUE);
1682 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1683 $this->assign('chartId', $this->_chartId
);
1686 // unset columns not to be displayed.
1687 foreach ($this->_columnHeaders
as $key => $value) {
1688 if (is_array($value) && isset($value['no_display'])) {
1689 unset($this->_columnHeaders
[$key]);
1693 // unset columns not to be displayed.
1694 if (!empty($rows)) {
1695 foreach ($this->_noDisplay
as $noDisplayField) {
1696 foreach ($rows as $rowNum => $row) {
1697 unset($this->_columnHeaders
[$noDisplayField]);
1702 // build array of section totals
1703 $this->sectionTotals();
1705 // process grand-total row
1706 $this->grandTotal($rows);
1708 // use this method for formatting rows for display purpose.
1709 $this->alterDisplay($rows);
1710 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1712 // use this method for formatting custom rows for display purpose.
1713 $this->alterCustomDataDisplay($rows);
1716 function buildChart(&$rows) {
1717 // override this method for building charts.
1720 // select() method below has been added recently (v3.3), and many of the report templates might
1721 // still be having their own select() method. We should fix them as and when encountered and move
1722 // towards generalizing the select() method below.
1726 foreach ($this->_columns
as $tableName => $table) {
1727 if (array_key_exists('fields', $table)) {
1728 foreach ($table['fields'] as $fieldName => $field) {
1729 if ($tableName == 'civicrm_address') {
1730 $this->_addressField
= TRUE;
1732 if ($tableName == 'civicrm_email') {
1733 $this->_emailField
= TRUE;
1735 if ($tableName == 'civicrm_phone') {
1736 $this->_phoneField
= TRUE;
1739 if (CRM_Utils_Array
::value('required', $field) ||
1740 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1743 // 1. In many cases we want select clause to be built in slightly different way
1744 // for a particular field of a particular type.
1745 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1747 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1748 if ($selectClause) {
1749 $select[] = $selectClause;
1753 // include statistics columns only if set
1754 if (CRM_Utils_Array
::value('statistics', $field)) {
1755 foreach ($field['statistics'] as $stat => $label) {
1756 $alias = "{$tableName}_{$fieldName}_{$stat}";
1757 switch (strtolower($stat)) {
1760 $select[] = "$stat({$field['dbAlias']}) as $alias";
1761 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1762 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1763 $this->_statFields
[$label] = $alias;
1764 $this->_selectAliases
[] = $alias;
1768 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1769 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1770 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1771 $this->_statFields
[$label] = $alias;
1772 $this->_selectAliases
[] = $alias;
1775 case 'count_distinct':
1776 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1777 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1778 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1779 $this->_statFields
[$label] = $alias;
1780 $this->_selectAliases
[] = $alias;
1784 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1785 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1786 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1787 $this->_statFields
[$label] = $alias;
1788 $this->_selectAliases
[] = $alias;
1794 $alias = "{$tableName}_{$fieldName}";
1795 $select[] = "{$field['dbAlias']} as $alias";
1796 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1797 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1798 $this->_selectAliases
[] = $alias;
1804 // select for group bys
1805 if (array_key_exists('group_bys', $table)) {
1806 foreach ($table['group_bys'] as $fieldName => $field) {
1808 if ($tableName == 'civicrm_address') {
1809 $this->_addressField
= TRUE;
1811 if ($tableName == 'civicrm_email') {
1812 $this->_emailField
= TRUE;
1814 if ($tableName == 'civicrm_phone') {
1815 $this->_phoneField
= TRUE;
1817 // 1. In many cases we want select clause to be built in slightly different way
1818 // for a particular field of a particular type.
1819 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1821 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1822 if ($selectClause) {
1823 $select[] = $selectClause;
1827 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1828 && !empty($this->_params
['group_bys_freq'])) {
1829 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1831 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1832 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1833 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1834 $field['title'] = 'Week';
1838 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1839 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1840 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1841 $field['title'] = 'Year';
1845 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1846 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1847 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1848 $field['title'] = 'Month';
1852 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1853 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1854 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1855 $field['title'] = 'Quarter';
1858 // for graphs and charts -
1859 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1860 $this->_interval
= $field['title'];
1861 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1862 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1863 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1865 // just to make sure these values are transfered to rows.
1866 // since we 'll need them for calculation purpose,
1867 // e.g making subtotals look nicer or graphs
1868 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1869 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1876 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1879 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1884 $this->storeWhereHavingClauseArray();
1886 if (empty($this->_whereClauses
)) {
1887 $this->_where
= "WHERE ( 1 ) ";
1888 $this->_having
= "";
1891 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1894 if ($this->_aclWhere
) {
1895 $this->_where
.= " AND {$this->_aclWhere} ";
1898 if (!empty($this->_havingClauses
)) {
1899 // use this clause to construct group by clause.
1900 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1905 * Store Where clauses into an array - breaking out this step makes
1906 * over-riding more flexible as the clauses can be used in constructing a
1907 * temp table that may not be part of the final where clause or added
1908 * in other functions
1910 function storeWhereHavingClauseArray(){
1911 foreach ($this->_columns
as $tableName => $table) {
1912 if (array_key_exists('filters', $table)) {
1913 foreach ($table['filters'] as $fieldName => $field) {
1914 // respect pseudofield to filter spec so fields can be marked as
1915 // not to be handled here
1916 if(!empty($field['pseudofield'])){
1920 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1921 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1922 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1923 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1924 if (is_array($value) && !empty($value)) {
1925 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1929 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1930 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1931 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1932 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1933 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1934 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1938 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1940 $clause = $this->whereClause($field,
1942 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1943 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1944 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1949 if (!empty($clause)) {
1950 if (CRM_Utils_Array
::value('having', $field)) {
1951 $this->_havingClauses
[] = $clause;
1954 $this->_whereClauses
[] = $clause;
1962 function processReportMode() {
1963 $buttonName = $this->controller
->getButtonName();
1965 $output = CRM_Utils_Request
::retrieve(
1968 CRM_Core_DAO
::$_nullObject
1972 CRM_Utils_Request
::retrieve(
1975 CRM_Core_DAO
::$_nullObject
1978 $this->_absoluteUrl
= FALSE;
1980 $this->assign('printOnly', FALSE);
1982 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1983 $this->assign('printOnly', TRUE);
1985 $this->assign('outputMode', 'print');
1986 $this->_outputMode
= 'print';
1987 if ($this->_sendmail
) {
1988 $this->_absoluteUrl
= TRUE;
1991 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1992 $this->assign('printOnly', TRUE);
1994 $this->assign('outputMode', 'pdf');
1995 $this->_outputMode
= 'pdf';
1996 $this->_absoluteUrl
= TRUE;
1998 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
1999 $this->assign('printOnly', TRUE);
2001 $this->assign('outputMode', 'csv');
2002 $this->_outputMode
= 'csv';
2003 $this->_absoluteUrl
= TRUE;
2005 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2006 $this->assign('outputMode', 'group');
2007 $this->_outputMode
= 'group';
2009 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2010 $this->assign('outputMode', 'create_report');
2011 $this->_outputMode
= 'create_report';
2014 $this->assign('outputMode', 'html');
2015 $this->_outputMode
= 'html';
2018 // Get today's date to include in printed reports
2020 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2021 $this->assign('reportDate', $reportDate);
2025 function beginPostProcess() {
2026 $this->_params
= $this->controller
->exportValues($this->_name
);
2028 if (empty($this->_params
) &&
2031 $this->_params
= $this->_formValues
;
2034 // hack to fix params when submitted from dashboard, CRM-8532
2035 // fields array is missing because form building etc is skipped
2036 // in dashboard mode for report
2037 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2038 $this->_params
= $this->_formValues
;
2041 $this->_formValues
= $this->_params
;
2042 if (CRM_Core_Permission
::check('administer Reports') &&
2043 isset($this->_id
) &&
2044 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2045 $this->_chartButtonName
== $this->controller
->getButtonName()
2048 $this->assign('updateReportButton', TRUE);
2050 $this->processReportMode();
2053 function buildQuery($applyLimit = TRUE) {
2056 $this->customDataFrom();
2061 // order_by columns not selected for display need to be included in SELECT
2062 $unselectedSectionColumns = $this->unselectedSectionColumns();
2063 foreach ($unselectedSectionColumns as $alias => $section) {
2064 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2067 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2070 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2072 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2076 function groupBy() {
2077 $groupBys = array();
2078 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2079 is_array($this->_params
['group_bys']) &&
2080 !empty($this->_params
['group_bys'])
2082 foreach ($this->_columns
as $tableName => $table) {
2083 if (array_key_exists('group_bys', $table)) {
2084 foreach ($table['group_bys'] as $fieldName => $field) {
2085 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2086 $groupBys[] = $field['dbAlias'];
2093 if (!empty($groupBys)) {
2094 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2098 function orderBy() {
2099 $this->_orderBy
= "";
2100 $this->_sections
= array();
2101 $this->storeOrderByArray();
2102 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2103 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2105 $this->assign('sections', $this->_sections
);
2108 * In some cases other functions want to know which fields are selected for ordering by
2109 * Separating this into a separate function allows it to be called separately from constructing
2110 * the order by clause
2112 function storeOrderByArray() {
2113 $orderBys = array();
2115 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2116 is_array($this->_params
['order_bys']) &&
2117 !empty($this->_params
['order_bys'])
2120 // Proces order_bys in user-specified order
2121 foreach ($this->_params
['order_bys'] as $orderBy) {
2122 $orderByField = array();
2123 foreach ($this->_columns
as $tableName => $table) {
2124 if (array_key_exists('order_bys', $table)) {
2125 // For DAO columns defined in $this->_columns
2126 $fields = $table['order_bys'];
2128 elseif (array_key_exists('extends', $table)) {
2129 // For custom fields referenced in $this->_customGroupExtends
2130 $fields = $table['fields'];
2132 if (!empty($fields) && is_array($fields)) {
2133 foreach ($fields as $fieldName => $field) {
2134 if ($fieldName == $orderBy['column']) {
2135 $orderByField = $field;
2136 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2143 if (!empty($orderByField)) {
2144 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2146 // Record any section headers for assignment to the template
2147 if (CRM_Utils_Array
::value('section', $orderBy)) {
2148 $this->_sections
[$orderByField['tplField']] = $orderByField;
2154 $this->_orderByArray
= $orderBys;
2156 $this->assign('sections', $this->_sections
);
2159 function unselectedSectionColumns() {
2160 $selectColumns = array();
2161 foreach ($this->_columns
as $tableName => $table) {
2162 if (array_key_exists('fields', $table)) {
2163 foreach ($table['fields'] as $fieldName => $field) {
2164 if (CRM_Utils_Array
::value('required', $field) ||
2165 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2168 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2173 if (is_array($this->_sections
)) {
2174 return array_diff_key($this->_sections
, $selectColumns);
2181 function buildRows($sql, &$rows) {
2182 $dao = CRM_Core_DAO
::executeQuery($sql);
2183 if (!is_array($rows)) {
2187 // use this method to modify $this->_columnHeaders
2188 $this->modifyColumnHeaders();
2190 $unselectedSectionColumns = $this->unselectedSectionColumns();
2192 while ($dao->fetch()) {
2194 foreach ($this->_columnHeaders
as $key => $value) {
2195 if (property_exists($dao, $key)) {
2196 $row[$key] = $dao->$key;
2200 // section headers not selected for display need to be added to row
2201 foreach ($unselectedSectionColumns as $key => $values) {
2202 if (property_exists($dao, $key)) {
2203 $row[$key] = $dao->$key;
2212 * When "order by" fields are marked as sections, this assigns to the template
2213 * an array of total counts for each section. This data is used by the Smarty
2214 * plugin {sectionTotal}
2216 function sectionTotals() {
2218 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2219 if (empty($this->_selectAliases
)) {
2223 if (!empty($this->_sections
)) {
2224 // build the query with no LIMIT clause
2225 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2226 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2228 // pull section aliases out of $this->_sections
2229 $sectionAliases = array_keys($this->_sections
);
2232 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2233 $ifnulls[] = "ifnull($alias, '') as $alias";
2236 /* Group (un-limited) report by all aliases and get counts. This might
2237 * be done more efficiently when the contents of $sql are known, ie. by
2238 * overriding this method in the report class.
2242 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2244 // initialize array of total counts
2246 $dao = CRM_Core_DAO
::executeQuery($query);
2247 while ($dao->fetch()) {
2249 // let $this->_alterDisplay translate any integer ids to human-readable values.
2250 $rows[0] = $dao->toArray();
2251 $this->alterDisplay($rows);
2254 // add totals for all permutations of section values
2257 $aliasCount = count($sectionAliases);
2258 foreach ($sectionAliases as $alias) {
2259 $values[] = $row[$alias];
2260 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2261 if ($i == $aliasCount) {
2262 // the last alias is the lowest-level section header; use count as-is
2263 $totals[$key] = $dao->ct
;
2266 // other aliases are higher level; roll count into their total
2267 $totals[$key] +
= $dao->ct
;
2271 $this->assign('sectionTotals', $totals);
2275 function modifyColumnHeaders() {
2276 // use this method to modify $this->_columnHeaders
2279 function doTemplateAssignment(&$rows) {
2280 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2281 $this->assign_by_ref('rows', $rows);
2282 $this->assign('statistics', $this->statistics($rows));
2285 // override this method to build your own statistics
2286 function statistics(&$rows) {
2287 $statistics = array();
2289 $count = count($rows);
2291 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2295 $this->countStat($statistics, $count);
2297 $this->groupByStat($statistics);
2299 $this->filterStat($statistics);
2304 function countStat(&$statistics, $count) {
2305 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2309 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2310 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2311 'value' => $this->_rowsFound
,
2316 function groupByStat(&$statistics) {
2317 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2318 is_array($this->_params
['group_bys']) &&
2319 !empty($this->_params
['group_bys'])
2321 foreach ($this->_columns
as $tableName => $table) {
2322 if (array_key_exists('group_bys', $table)) {
2323 foreach ($table['group_bys'] as $fieldName => $field) {
2324 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2325 $combinations[] = $field['title'];
2330 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2331 'value' => implode(' & ', $combinations),
2336 function filterStat(&$statistics) {
2337 foreach ($this->_columns
as $tableName => $table) {
2338 if (array_key_exists('filters', $table)) {
2339 foreach ($table['filters'] as $fieldName => $field) {
2340 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2343 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2344 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2345 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2346 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2347 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2349 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2350 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2352 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2353 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2356 $statistics['filters'][] = array(
2357 'title' => $field['title'],
2358 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2361 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2362 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2364 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2365 $statistics['filters'][] = array(
2366 'title' => $field['title'],
2367 'value' => $pair[$rel],
2372 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2375 $pair = $this->getOperationPair(
2376 CRM_Utils_Array
::value('operatorType', $field),
2379 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2380 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2381 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2382 if (in_array($op, array(
2383 'bw', 'nbw')) && ($min ||
$max)) {
2384 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2386 elseif ($op == 'nll' ||
$op == 'nnll') {
2387 $value = $pair[$op];
2389 elseif (is_array($val) && (!empty($val))) {
2390 $options = CRM_Utils_Array
::value('options', $field, array());
2391 foreach ($val as $key => $valIds) {
2392 if (isset($options[$valIds])) {
2393 $val[$key] = $options[$valIds];
2396 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2397 $val = implode(', ', $val);
2398 $value = "{$pair[$op]} " . $val;
2400 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2401 is_array($field['options']) && !empty($field['options'])
2403 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2406 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2410 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2420 function endPostProcess(&$rows = NULL) {
2421 if ( $this->_storeResultSet
) {
2422 $this->_resultSet
= $rows;
2425 if ($this->_outputMode
== 'print' ||
2426 $this->_outputMode
== 'pdf' ||
2430 $content = $this->compileContent();
2431 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2435 if ($this->_sendmail
) {
2436 $config = CRM_Core_Config
::singleton();
2437 $attachments = array();
2439 if ($this->_outputMode
== 'csv') {
2440 $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'];
2442 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2443 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2444 file_put_contents($csvFullFilename, $csvContent);
2445 $attachments[] = array(
2446 'fullPath' => $csvFullFilename,
2447 'mime_type' => 'text/csv',
2448 'cleanName' => 'CiviReport.csv',
2451 if ($this->_outputMode
== 'pdf') {
2452 // generate PDF content
2453 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2454 file_put_contents($pdfFullFilename,
2455 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2456 TRUE, array('orientation' => 'landscape')
2459 // generate Email Content
2460 $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'];
2462 $attachments[] = array(
2463 'fullPath' => $pdfFullFilename,
2464 'mime_type' => 'application/pdf',
2465 'cleanName' => 'CiviReport.pdf',
2469 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2470 $this->_outputMode
, $attachments
2472 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2475 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2478 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2480 elseif ($this->_outputMode
== 'print') {
2484 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2485 $config = CRM_Core_Config
::singleton();
2486 //get chart image name
2487 $chartImg = $this->_chartId
. '.png';
2488 //get image url path
2489 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2490 $uploadUrl .= $chartImg;
2491 //get image doc path to overwrite
2492 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2494 $chart = imagecreatefrompng($uploadUrl);
2495 //convert it into formattd png
2496 header('Content-type: image/png');
2497 //overwrite with same image
2498 imagepng($chart, $uploadImg);
2500 imagedestroy($chart);
2502 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2504 CRM_Utils_System
::civiExit();
2506 elseif ($this->_outputMode
== 'csv') {
2507 CRM_Report_Utils_Report
::export2csv($this, $rows);
2509 elseif ($this->_outputMode
== 'group') {
2510 $group = $this->_params
['groups'];
2511 $this->add2group($group);
2513 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2514 CRM_Report_Form_Instance
::postProcess($this);
2516 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2517 $this->_outputMode
== 'create_report' ) {
2518 $this->_createNew
= TRUE;
2519 CRM_Report_Form_Instance
::postProcess($this);
2523 function storeResultSet() {
2524 $this->_storeResultSet
= TRUE;
2527 function getResultSet() {
2528 return $this->_resultSet
;
2532 * Get Template file name - use default form template if a specific one has not been set up for this report
2535 function getTemplateFileName(){
2536 $defaultTpl = parent
::getTemplateFileName();
2537 $template = CRM_Core_Smarty
::singleton();
2538 if (!$template->template_exists($defaultTpl)) {
2539 $defaultTpl = 'CRM/Report/Form.tpl';
2545 * Compile the report content
2547 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2549 function compileContent(){
2550 $templateFile = $this->getHookedTemplateFileName();
2551 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2555 function postProcess() {
2556 // get ready with post process params
2557 $this->beginPostProcess();
2560 $sql = $this->buildQuery();
2562 // build array of result based on column headers. This method also allows
2563 // modifying column headers before using it to build result set i.e $rows.
2565 $this->buildRows($sql, $rows);
2567 // format result set.
2568 $this->formatDisplay($rows);
2570 // assign variables to templates
2571 $this->doTemplateAssignment($rows);
2573 // do print / pdf / instance stuff if needed
2574 $this->endPostProcess($rows);
2577 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2578 // lets do the pager if in html mode
2579 $this->_limit
= NULL;
2580 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2581 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2583 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2585 if (!$pageId && !empty($_POST)) {
2586 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2587 $pageId = max((int)@$_POST['crmPID_B'], 1);
2589 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2590 $pageId = max((int)@$_POST['crmPID'], 1);
2592 unset($_POST['crmPID_B'], $_POST['crmPID']);
2595 $pageId = $pageId ?
$pageId : 1;
2596 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2597 $offset = ($pageId - 1) * $rowCount;
2599 $this->_limit
= " LIMIT $offset, " . $rowCount;
2600 return array($offset, $rowCount);
2604 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2605 if ($this->_limit
&& ($this->_limit
!= '')) {
2606 $sql = "SELECT FOUND_ROWS();";
2607 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2609 'total' => $this->_rowsFound
,
2610 'rowCount' => $rowCount,
2611 'status' => ts('Records') . ' %%StatusMessage%%',
2612 'buttonBottom' => 'PagerBottomButton',
2613 'buttonTop' => 'PagerTopButton',
2614 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2617 $pager = new CRM_Utils_Pager($params);
2618 $this->assign_by_ref('pager', $pager);
2622 function whereGroupClause($field, $value, $op) {
2624 $smartGroupQuery = "";
2626 $group = new CRM_Contact_DAO_Group();
2627 $group->is_active
= 1;
2629 $smartGroups = array();
2630 while ($group->fetch()) {
2631 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2632 $smartGroups[] = $group->id
;
2636 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2638 $smartGroupQuery = '';
2639 if (!empty($smartGroups)) {
2640 $smartGroups = implode(',', $smartGroups);
2641 $smartGroupQuery = " UNION DISTINCT
2642 SELECT DISTINCT smartgroup_contact.contact_id
2643 FROM civicrm_group_contact_cache smartgroup_contact
2644 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2647 $sqlOp = $this->getSQLOperator($op);
2648 if (!is_array($value)) {
2649 $value = array($value);
2651 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2653 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2654 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2655 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2656 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2657 {$smartGroupQuery} ) ";
2660 function whereTagClause($field, $value, $op) {
2661 // not using left join in query because if any contact
2662 // belongs to more than one tag, results duplicate
2664 $sqlOp = $this->getSQLOperator($op);
2665 if (!is_array($value)) {
2666 $value = array($value);
2668 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2670 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2671 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2672 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2673 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2676 function buildACLClause($tableAlias = 'contact_a') {
2677 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2680 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2681 if (empty($this->_customGroupExtends
)) {
2684 if (!is_array($this->_customGroupExtends
)) {
2685 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2687 $customGroupWhere = '';
2688 if (!empty($permCustomGroupIds)) {
2689 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2692 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2693 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2694 FROM civicrm_custom_group cg
2695 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2696 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2698 cg.is_active = 1 AND
2699 cf.is_active = 1 AND
2700 cf.is_searchable = 1
2701 ORDER BY cg.weight, cf.weight";
2702 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2705 while ($customDAO->fetch()) {
2706 if ($customDAO->table_name
!= $curTable) {
2707 $curTable = $customDAO->table_name
;
2708 $curFields = $curFilters = array();
2711 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2712 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2713 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2714 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2717 'fields', 'filters', 'group_bys') as $colKey) {
2718 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2719 $this->_columns
[$curTable][$colKey] = array();
2723 $fieldName = 'custom_' . $customDAO->cf_id
;
2726 // this makes aliasing work in favor
2727 $curFields[$fieldName] = array(
2728 'name' => $customDAO->column_name
,
2729 'title' => $customDAO->label
,
2730 'dataType' => $customDAO->data_type
,
2731 'htmlType' => $customDAO->html_type
,
2734 if ($this->_customGroupFilters
) {
2735 // this makes aliasing work in favor
2736 $curFilters[$fieldName] = array(
2737 'name' => $customDAO->column_name
,
2738 'title' => $customDAO->label
,
2739 'dataType' => $customDAO->data_type
,
2740 'htmlType' => $customDAO->html_type
,
2744 switch ($customDAO->data_type
) {
2747 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2748 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2749 // CRM-6946, show time part for datetime date fields
2750 if ($customDAO->time_format
) {
2751 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2756 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2757 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2761 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2765 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2766 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2770 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2771 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2775 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2776 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2780 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2782 if (!empty($customDAO->option_group_id
)) {
2783 if (in_array($customDAO->html_type
, array(
2784 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2785 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2788 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2790 if ($this->_customGroupFilters
) {
2791 $curFilters[$fieldName]['options'] = array();
2792 $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')));
2793 while ($ogDAO->fetch()) {
2794 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2800 case 'StateProvince':
2801 if (in_array($customDAO->html_type
, array(
2802 'Multi-Select State/Province'))) {
2803 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2806 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2808 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2812 if (in_array($customDAO->html_type
, array(
2813 'Multi-Select Country'))) {
2814 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2817 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2819 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2822 case 'ContactReference':
2823 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2824 $curFilters[$fieldName]['name'] = 'display_name';
2825 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2827 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2828 $curFields[$fieldName]['name'] = 'display_name';
2829 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2833 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2834 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2837 if (!array_key_exists('type', $curFields[$fieldName])) {
2838 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2842 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2844 if ($this->_customGroupFilters
) {
2845 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2847 if ($this->_customGroupGroupBy
) {
2848 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2853 function customDataFrom() {
2854 if (empty($this->_customGroupExtends
)) {
2857 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2859 foreach ($this->_columns
as $table => $prop) {
2860 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2861 $extendsTable = $mapper[$prop['extends']];
2863 // check field is in params
2864 if (!$this->isFieldSelected($prop)) {
2868 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2870 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2871 // handle for ContactReference
2872 if (array_key_exists('fields', $prop)) {
2873 foreach ($prop['fields'] as $fieldName => $field) {
2874 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2875 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2877 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2885 function isFieldSelected($prop) {
2890 if (!empty($this->_params
['fields'])) {
2891 foreach (array_keys($prop['fields']) as $fieldAlias) {
2892 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2893 if ($customFieldId) {
2894 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2898 //might be survey response field.
2899 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2900 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2908 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2909 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2910 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2916 if (!empty($this->_params
['order_bys'])) {
2917 foreach (array_keys($prop['fields']) as $fieldAlias) {
2918 foreach ($this->_params
['order_bys'] as $orderBy) {
2919 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2926 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2927 foreach ($prop['filters'] as $fieldAlias => $val) {
2929 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2930 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2931 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2932 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2938 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2939 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2950 * Check for empty order_by configurations and remove them; also set
2951 * template to hide them.
2953 function preProcessOrderBy(&$formValues) {
2954 // Object to show/hide form elements
2955 $_showHide = new CRM_Core_ShowHideBlocks('', '');
2957 $_showHide->addShow('optionField_1');
2959 // Cycle through order_by options; skip any empty ones, and hide them as well
2962 if (!empty($formValues['order_bys'])) {
2963 foreach ($formValues['order_bys'] as $order_by) {
2964 if ($order_by['column'] && $order_by['column'] != '-') {
2965 $_showHide->addShow('optionField_' . $n);
2966 $orderBys[$n] = $order_by;
2971 for ($i = $n; $i <= 5; $i++
) {
2973 $_showHide->addHide('optionField_' . $i);
2977 // overwrite order_by options with modified values
2978 if (!empty($orderBys)) {
2979 $formValues['order_bys'] = $orderBys;
2982 $formValues['order_bys'] = array(1 => array('column' => '-'));
2985 // assign show/hide data to template
2986 $_showHide->addToTemplate();
2990 * Does table name have columns in SELECT clause?
2992 * @param string $tableName Name of table (index of $this->_columns array)
2996 function isTableSelected($tableName) {
2997 return in_array($tableName, $this->selectedTables());
3001 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3002 * (building the array if it's unset)
3004 * @return Array $this->_selectedTables
3006 function selectedTables() {
3007 if (!$this->_selectedTables
) {
3008 $orderByColumns = array();
3009 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3010 foreach ($this->_params
['order_bys'] as $orderBy) {
3011 $orderByColumns[] = $orderBy['column'];
3015 foreach ($this->_columns
as $tableName => $table) {
3016 if (array_key_exists('fields', $table)) {
3017 foreach ($table['fields'] as $fieldName => $field) {
3018 if (CRM_Utils_Array
::value('required', $field) ||
3019 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3021 $this->_selectedTables
[] = $tableName;
3026 if (array_key_exists('order_bys', $table)) {
3027 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3028 if (in_array($orderByName, $orderByColumns)) {
3029 $this->_selectedTables
[] = $tableName;
3034 if (array_key_exists('filters', $table)) {
3035 foreach ($table['filters'] as $filterName => $filter) {
3036 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3037 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3038 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3040 $this->_selectedTables
[] = $tableName;
3047 return $this->_selectedTables
;
3051 * @deprecated - use getAddressColumns which is a more accurate description
3052 * and also accepts an array of options rather than a long list
3054 * function for adding address fields to construct function in reports
3055 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3056 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3057 * @return array address fields for construct clause
3059 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3060 'country_id' => TRUE)) {
3061 $addressFields = array(
3062 'civicrm_address' =>
3064 'dao' => 'CRM_Core_DAO_Address',
3068 array('title' => ts('Address Name'),
3069 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3072 array('title' => ts('Street Address'),
3073 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3075 'supplemental_address_1' =>
3076 array('title' => ts('Supplementary Address Field 1'),
3077 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3079 'supplemental_address_2' =>
3080 array('title' => ts('Supplementary Address Field 2'),
3081 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3085 'name' => 'street_number',
3086 'title' => ts('Street Number'),
3088 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3092 'name' => 'street_name',
3093 'title' => ts('Street Name'),
3095 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3099 'name' => 'street_unit',
3100 'title' => ts('Street Unit'),
3102 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3105 array('title' => ts('City'),
3106 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3109 array('title' => ts('Postal Code'),
3110 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3113 array('title' => ts('County'),
3114 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3116 'state_province_id' =>
3117 array('title' => ts('State/Province'),
3118 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3121 array('title' => ts('Country'),
3122 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3125 'grouping' => 'location-fields',
3130 $addressFields['civicrm_address']['filters'] = array(
3131 'street_number' => array('title' => ts('Street Number'),
3133 'name' => 'street_number',
3135 'street_name' => array('title' => ts('Street Name'),
3136 'name' => 'street_name',
3137 'operator' => 'like',
3139 'postal_code' => array('title' => ts('Postal Code'),
3141 'name' => 'postal_code',
3143 'city' => array('title' => ts('City'),
3144 'operator' => 'like',
3147 'county_id' => array(
3148 'name' => 'county_id',
3149 'title' => ts('County'),
3150 'type' => CRM_Utils_Type
::T_INT
,
3152 CRM_Report_Form
::OP_MULTISELECT
,
3154 CRM_Core_PseudoConstant
::county(),
3156 'state_province_id' => array(
3157 'name' => 'state_province_id',
3158 'title' => ts('State/Province'),
3159 'type' => CRM_Utils_Type
::T_INT
,
3161 CRM_Report_Form
::OP_MULTISELECT
,
3163 CRM_Core_PseudoConstant
::stateProvince(),
3165 'country_id' => array(
3166 'name' => 'country_id',
3167 'title' => ts('Country'),
3168 'type' => CRM_Utils_Type
::T_INT
,
3170 CRM_Report_Form
::OP_MULTISELECT
,
3172 CRM_Core_PseudoConstant
::country(),
3178 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3179 'street_number' => array('title' => 'Odd / Even Street Number'),
3180 'street_address' => NULL,
3182 'postal_code' => NULL,
3187 $addressFields['civicrm_address']['group_bys'] = array(
3188 'street_address' => NULL,
3190 'postal_code' => NULL,
3191 'state_province_id' =>
3192 array('title' => ts('State/Province'),
3195 array('title' => ts('Country'),
3198 array('title' => ts('County'),
3202 return $addressFields;
3206 * Do AlterDisplay processing on Address Fields
3208 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3209 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3210 $entryFound = FALSE;
3212 if (array_key_exists('civicrm_address_country_id', $row)) {
3213 if ($value = $row['civicrm_address_country_id']) {
3214 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3215 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3216 "reset=1&force=1&{$criteriaQueryParams}&" .
3217 "country_id_op=in&country_id_value={$value}",
3218 $this->_absoluteUrl
, $this->_id
3220 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3221 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3228 if (array_key_exists('civicrm_address_county_id', $row)) {
3229 if ($value = $row['civicrm_address_county_id']) {
3230 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3231 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3232 "reset=1&force=1&{$criteriaQueryParams}&" .
3233 "county_id_op=in&county_id_value={$value}",
3234 $this->_absoluteUrl
, $this->_id
3236 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3237 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3243 // handle state province
3244 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3245 if ($value = $row['civicrm_address_state_province_id']) {
3246 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3248 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3249 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3250 $this->_absoluteUrl
, $this->_id
3252 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3253 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3264 * Adjusts dates passed in to YEAR() for fiscal year.
3266 function fiscalYearOffset($fieldName) {
3267 $config = CRM_Core_Config
::singleton();
3268 $fy = $config->fiscalYearStart
;
3269 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3270 return "YEAR( $fieldName )";
3272 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3276 * Add Address into From Table if required
3278 function addAddressFromClause() {
3279 // include address field if address column is to be included
3280 if ((isset($this->_addressField
) &&
3281 $this->_addressField
3283 $this->isTableSelected('civicrm_address')
3286 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3287 ON ({$this->_aliases['civicrm_contact']}.id =
3288 {$this->_aliases['civicrm_address']}.contact_id) AND
3289 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3294 * Add Phone into From Table if required
3296 function addPhoneFromClause() {
3297 // include address field if address column is to be included
3298 if ($this->isTableSelected('civicrm_phone')
3301 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3302 ON ({$this->_aliases['civicrm_contact']}.id =
3303 {$this->_aliases['civicrm_phone']}.contact_id) AND
3304 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3309 * Get phone columns to add to array
3310 * @param array $options
3311 * - prefix Prefix to add to table (in case of more than one instance of the table)
3312 * - prefix_label Label to give columns from this phone table instance
3313 * @return array phone columns definition
3315 function getPhoneColumns($options = array()){
3316 $defaultOptions = array(
3318 'prefix_label' => '',
3321 $options = array_merge($defaultOptions,$options);
3324 $options['prefix'] . 'civicrm_phone' => array(
3325 'dao' => 'CRM_Core_DAO_Phone',
3327 $options['prefix'] . 'phone' => array(
3328 'title' => ts($options['prefix_label'] . 'Phone'),
3338 * Get address columns to add to array
3339 * @param array $options
3340 * - prefix Prefix to add to table (in case of more than one instance of the table)
3341 * - prefix_label Label to give columns from this address table instance
3342 * @return array address columns definition
3344 function getAddressColumns($options = array()){
3345 $defaultOptions = array(
3347 'prefix_label' => '',
3351 'defaults' => array(
3354 $options = array_merge($defaultOptions,$options);
3355 return $this->addAddressFields(
3356 $options['group_by'],
3357 $options['order_by'],
3358 $options['filters'],
3359 $options['defaults']
3364 function add2group($groupID) {
3365 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3366 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3367 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3369 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3370 $dao = CRM_Core_DAO
::executeQuery($sql);
3372 $contact_ids = array();
3373 // Add resulting contacts to group
3374 while ($dao->fetch()) {
3375 if ($dao->addtogroup_contact_id
) {
3376 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3380 if ( !empty($contact_ids) ) {
3381 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3382 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3385 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3390 /* function used for showing charts on print screen */
3391 static function uploadChartImage() {
3392 // upload strictly for '.png' images
3393 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3394 if (preg_match('/\.png$/', $name)) {
3396 // POST data is usually string data, but we are passing a RAW .png
3397 // so PHP is a bit confused and $_POST is empty. But it has saved
3398 // the raw bits into $HTTP_RAW_POST_DATA
3400 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3402 // prepare the directory
3403 $config = CRM_Core_Config
::singleton();
3404 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3405 if (!file_exists($defaultPath)) {
3406 mkdir($defaultPath, 0777, TRUE);
3409 // full path to the saved image including filename
3410 $destination = $defaultPath . $name;
3413 $jfh = fopen($destination, 'w') or die("can't open file");
3414 fwrite($jfh, $httpRawPostData);
3416 CRM_Utils_System
::civiExit();