3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 CONST ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
53 * The id of the report instance
60 * The id of the report template
64 protected $_templateID;
72 protected $_noFields = FALSE;
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attribues as the value
80 protected $_columns = array();
83 * The set of filters in the report
87 protected $_filters = array();
90 * The set of optional columns in the report
94 protected $_options = array();
96 protected $_defaults = array();
99 * By default most reports hide contact id.
100 * Setting this to true makes it available
102 protected $_exposeContactID = TRUE;
105 * Set of statistic fields
109 protected $_statFields = array();
112 * Set of statistics data
116 protected $_statistics = array();
119 * List of fields not to be repeated during display
123 protected $_noRepeats = array();
126 * List of fields not to be displayed
130 protected $_noDisplay = array();
133 * Object type that a custom group extends
137 protected $_customGroupExtends = NULL;
138 protected $_customGroupExtendsJoin = array();
139 protected $_customGroupFilters = TRUE;
140 protected $_customGroupGroupBy = FALSE;
141 protected $_customGroupJoin = 'LEFT JOIN';
147 protected $_tagFilter = FALSE;
150 * build groups filter
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * An attribute for checkbox/radio form field layout
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
174 protected $_force = 1;
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_grandFlag = FALSE;
194 protected $_rowsFound = NULL;
195 protected $_selectAliases = array();
196 protected $_rollup = NULL;
197 protected $_limit = NULL;
198 protected $_sections = NULL;
199 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
200 protected $_absoluteUrl = FALSE;
203 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
207 protected $_storeResultSet = FALSE;
210 * When _storeResultSet Flag is set use this var to store result set in form of array
214 protected $_resultSet = array();
217 * To what frequency group-by a date column
221 protected $_groupByDateFreq = array(
223 'YEARWEEK' => 'Week',
224 'QUARTER' => 'Quarter',
229 * Variables to hold the acl inner join and where clause
231 protected $_aclFrom = NULL;
232 protected $_aclWhere = NULL;
235 * Array of DAO tables having columns included in SELECT or ORDER BY clause
239 protected $_selectedTables;
241 public $_having = NULL;
242 public $_select = NULL;
243 public $_selectClauses = array();
244 public $_columnHeaders = array();
245 public $_orderBy = NULL;
246 public $_orderByFields = array();
247 public $_orderByArray = array();
248 public $_groupBy = NULL;
249 public $_whereClauses = array();
250 public $_havingClauses = array();
253 * Variable to hold the currency alias
255 protected $_currencyColumn = NULL;
260 function __construct() {
261 parent
::__construct();
264 if ($this->_tagFilter
) {
265 $this->buildTagFilter();
267 if ($this->_exposeContactID
) {
268 if (array_key_exists('civicrm_contact', $this->_columns
)) {
269 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
271 'title' => 'Contact ID',
277 if ($this->_groupFilter
) {
278 $this->buildGroupFilter();
281 // Get all custom groups
282 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
284 // Get the custom groupIds for which the user has VIEW permission
285 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
286 // and addCustomDataToColumns() will allow access to all custom groups.
287 $permCustomGroupIds = array();
288 if (!CRM_Core_Permission
::check('access all custom data')) {
289 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
290 // do not allow custom data for reports if user doesn't have
291 // permission to access custom data.
292 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
293 $this->_customGroupExtends
= array();
297 // merge custom data columns to _columns list, if any
298 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
300 // add / modify display columns, filters ..etc
301 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
303 //assign currencyColumn variable to tpl
304 $this->assign('currencyColumn', $this->_currencyColumn
);
307 function preProcessCommon() {
309 CRM_Utils_Request
::retrieve(
312 CRM_Core_DAO
::$_nullObject
315 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
317 $this->assign('section', $this->_section
);
318 CRM_Core_Region
::instance('page-header')->add(array(
319 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
322 $this->_id
= $this->get('instanceId');
324 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
326 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
330 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
331 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
332 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
335 $this->assign('instanceId', $this->_id
);
336 $params = array('id' => $this->_id
);
337 $this->_instanceValues
= array();
338 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
340 $this->_instanceValues
342 if (empty($this->_instanceValues
)) {
343 CRM_Core_Error
::fatal("Report could not be loaded.");
346 if (!empty($this->_instanceValues
['permission']) &&
347 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
348 CRM_Core_Permission
::check('administer Reports')
351 CRM_Utils_System
::permissionDenied();
352 CRM_Utils_System
::civiExit();
355 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
357 $this->_formValues
= unserialize($formValues);
360 $this->_formValues
= NULL;
363 // lets always do a force if reset is found in the url.
364 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
369 $this->assign('mode', 'instance');
372 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
373 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
374 if (($instanceCount > 0) && $optionValueID) {
375 $this->assign('instanceUrl',
376 CRM_Utils_System
::url('civicrm/report/list',
377 "reset=1&ovid=$optionValueID"
381 if ($optionValueID) {
382 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
386 $this->assign('mode', 'template');
389 // lets display the Report Settings section
390 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
392 // Do not display Report Settings section if administer Reports permission is absent OR
393 // if report instance is reserved and administer reserved reports absent
394 if (!CRM_Core_Permission
::check('administer Reports') ||
395 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
396 $this->_instanceForm
= FALSE;
399 $this->assign('criteriaForm', FALSE);
400 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
401 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
402 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
403 $this->assign('criteriaForm', TRUE);
404 $this->_criteriaForm
= TRUE;
408 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
409 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
410 $this->_printButtonName
= $this->getButtonName('submit', 'print');
411 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
412 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
413 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
414 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
417 function addBreadCrumb() {
421 'title' => ts('Report Templates'),
422 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
426 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
429 function preProcess() {
430 $this->preProcessCommon();
433 $this->addBreadCrumb();
436 foreach ($this->_columns
as $tableName => $table) {
438 if (!isset($table['alias'])) {
439 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
442 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
445 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
447 $daoOrBaoName = NULL;
448 // higher preference to bao object
449 if (array_key_exists('bao', $table)) {
450 $daoOrBaoName = $table['bao'];
451 $expFields = $daoOrBaoName::exportableFields( );
453 elseif (array_key_exists('dao', $table)){
454 $daoOrBaoName = $table['dao'];
455 $expFields = $daoOrBaoName::export( );
458 $expFields = array();
461 $doNotCopy = array('required');
463 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
464 foreach ($fieldGroups as $fieldGrp) {
465 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
466 foreach ($table[$fieldGrp] as $fieldName => $field) {
467 // $name is the field name used to reference the BAO/DAO export fields array
468 $name = isset($field['name']) ?
$field['name'] : $fieldName;
470 // Sometimes the field name key in the BAO/DAO export fields array is
471 // different from the actual database field name.
472 // Unset $field['name'] so that actual database field name can be obtained
473 // from the BAO/DAO export fields array.
474 unset($field['name']);
476 if (array_key_exists($name, $expFields)) {
477 foreach ($doNotCopy as $dnc) {
478 // unset the values we don't want to be copied.
479 unset($expFields[$name][$dnc]);
482 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
485 foreach ($expFields[$name] as $property => $val) {
486 if (!array_key_exists($property, $field)) {
487 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
494 if (CRM_Utils_Array
::value('no_repeat', $field)) {
495 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
497 if (CRM_Utils_Array
::value('no_display', $field)) {
498 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
501 // set alias = table-name, unless already set
502 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
503 $this->_columns
[$tableName]['alias'] : $tableName
505 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
507 // set name = fieldName, unless already set
508 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
509 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
512 // set dbAlias = alias.name, unless already set
513 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
514 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
517 // a few auto fills for filters
518 if ($fieldGrp == 'filters') {
519 // fill operator types
520 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
521 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
522 case CRM_Utils_Type
::T_MONEY
:
523 case CRM_Utils_Type
::T_FLOAT
:
524 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
526 case CRM_Utils_Type
::T_INT
:
527 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
529 case CRM_Utils_Type
::T_DATE
:
530 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
532 case CRM_Utils_Type
::T_BOOLEAN
:
533 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
534 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
535 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
536 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
541 (array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
542 ||
array_key_exists('enumValues', $this->_columns
[$tableName][$fieldGrp][$fieldName]))
544 // with multiple options operator-type is generally multi-select
545 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
546 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
548 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
559 // copy filters to a separate handy variable
560 if (array_key_exists('filters', $table)) {
561 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
564 if (array_key_exists('group_bys', $table)) {
565 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
568 if (array_key_exists('fields', $table)) {
569 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
574 $this->setDefaultValues(FALSE);
577 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
578 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
579 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
580 CRM_Report_Utils_Get
::processChart($this->_defaults
);
583 $this->_formValues
= $this->_defaults
;
584 $this->postProcess();
588 function setDefaultValues($freeze = TRUE) {
589 $freezeGroup = array();
591 // FIXME: generalizing form field naming conventions would reduce
592 // lots of lines below.
593 foreach ($this->_columns
as $tableName => $table) {
594 if (array_key_exists('fields', $table)) {
595 foreach ($table['fields'] as $fieldName => $field) {
596 if (!CRM_Utils_Array
::value('no_display', $field)) {
597 if (isset($field['required'])) {
599 $this->_defaults
['fields'][$fieldName] = 1;
602 // find element object, so that we could use quickform's freeze method
603 // for required elements
604 $obj = $this->getElementFromGroup("fields", $fieldName);
606 $freezeGroup[] = $obj;
610 elseif (isset($field['default'])) {
611 $this->_defaults
['fields'][$fieldName] = $field['default'];
617 if (array_key_exists('group_bys', $table)) {
618 foreach ($table['group_bys'] as $fieldName => $field) {
619 if (isset($field['default'])) {
620 if (CRM_Utils_Array
::value('frequency', $field)) {
621 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
623 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
627 if (array_key_exists('filters', $table)) {
628 foreach ($table['filters'] as $fieldName => $field) {
629 if (isset($field['default'])) {
630 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
631 if(is_array($field['default'])){
632 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
633 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
634 $this->_defaults
["{$fieldName}_relative"] = 0;
637 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
641 $this->_defaults
["{$fieldName}_value"] = $field['default'];
644 //assign default value as "in" for multiselect
645 //operator, To freeze the select element
646 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
647 $this->_defaults
["{$fieldName}_op"] = 'in';
649 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
650 $this->_defaults
["{$fieldName}_op"] = 'mhas';
652 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
653 $this->_defaults
["{$fieldName}_op"] = $op;
659 array_key_exists('order_bys', $table) &&
660 is_array($table['order_bys'])
662 if (!array_key_exists('order_bys', $this->_defaults
)) {
663 $this->_defaults
['order_bys'] = array();
665 foreach ($table['order_bys'] as $fieldName => $field) {
667 CRM_Utils_Array
::value('default', $field) ||
668 CRM_Utils_Array
::value('default_order', $field) ||
669 CRM_Utils_Array
::value('default_is_section', $field) ||
670 CRM_Utils_Array
::value('default_weight', $field)
673 'column' => $fieldName,
674 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
675 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
678 if (CRM_Utils_Array
::value('default_weight', $field)) {
679 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
682 array_unshift($this->_defaults
['order_bys'], $order_by);
688 foreach ($this->_options
as $fieldName => $field) {
689 if (isset($field['default'])) {
690 $this->_defaults
['options'][$fieldName] = $field['default'];
695 if (!empty($this->_submitValues
)) {
696 $this->preProcessOrderBy($this->_submitValues
);
699 $this->preProcessOrderBy($this->_defaults
);
702 // lets finish freezing task here itself
703 if (!empty($freezeGroup)) {
704 foreach ($freezeGroup as $elem) {
709 if ($this->_formValues
) {
710 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
713 if ($this->_instanceValues
) {
714 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
717 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
719 return $this->_defaults
;
722 function getElementFromGroup($group, $grpFieldName) {
723 $eleObj = $this->getElement($group);
724 foreach ($eleObj->_elements
as $index => $obj) {
725 if ($grpFieldName == $obj->_attributes
['name']) {
732 function addColumns() {
735 foreach ($this->_columns
as $tableName => $table) {
736 if (array_key_exists('fields', $table)) {
737 foreach ($table['fields'] as $fieldName => $field) {
739 if (!CRM_Utils_Array
::value('no_display', $field)) {
740 foreach ( array('table', 'field') as $var) {
741 if (!empty($
{$var}['grouping'])) {
742 if (!is_array($
{$var}['grouping'])) {
743 $tableName = $
{$var}['grouping'];
745 $tableName = array_keys($
{$var}['grouping']);
746 $tableName = $tableName[0];
747 $groupTitle = array_values($
{$var}['grouping']);
748 $groupTitle = $groupTitle[0];
753 if (!$groupTitle && isset($table['group_title'])) {
754 $groupTitle = $table['group_title'];
757 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
758 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
759 $colGroups[$tableName]['group_title'] = $groupTitle;
762 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
768 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
769 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
771 $this->assign('colGroups', $colGroups);
774 function addFilters() {
775 $options = $filters = array();
777 foreach ($this->_filters
as $table => $attributes) {
778 foreach ($attributes as $fieldName => $field) {
779 // get ready with option value pair
780 // @ todo being able to specific options for a field (e.g a date field) in the field spec as an array rather than an override
782 $operations = $this->getOperationPair(
783 CRM_Utils_Array
::value('operatorType', $field),
786 $filters[$table][$fieldName] = $field;
788 switch (CRM_Utils_Array
::value('operatorType', $field)) {
789 case CRM_Report_Form
::OP_MONTH
:
790 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
791 // If there's no option list for this filter, define one.
792 $field['options'] = array(
801 9 => ts('September'),
803 11 => ts('November'),
804 12 => ts('December'),
806 // Add this option list to this column _columns. This is
807 // required so that filter statistics show properly.
808 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
810 case CRM_Report_FORM
::OP_MULTISELECT
:
811 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
812 // assume a multi-select field
813 if (!empty($field['options'])) {
814 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
815 if (count($operations) <= 1) {
818 $select = $this->addElement('select', "{$fieldName}_value", NULL,
819 $field['options'], array(
821 'style' => 'min-width:250px',
824 $select->setMultiple(TRUE);
828 case CRM_Report_FORM
::OP_SELECT
:
829 // assume a select field
830 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
831 if (!empty($field['options']))
832 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
835 case CRM_Report_FORM
::OP_DATE
:
836 // build datetime fields
837 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
841 case CRM_Report_FORM
::OP_DATETIME
:
842 // build datetime fields
843 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
847 case CRM_Report_FORM
::OP_INT
:
848 case CRM_Report_FORM
::OP_FLOAT
:
849 // and a min value input box
850 $this->add('text', "{$fieldName}_min", ts('Min'));
851 // and a max value input box
852 $this->add('text', "{$fieldName}_max", ts('Max'));
854 // default type is string
855 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
856 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
858 // we need text box for value input
859 $this->add('text', "{$fieldName}_value", NULL);
864 $this->assign('filters', $filters);
867 function addOptions() {
868 if (!empty($this->_options
)) {
869 // FIXME: For now lets build all elements as checkboxes.
870 // Once we clear with the format we can build elements based on type
873 foreach ($this->_options
as $fieldName => $field) {
874 if ($field['type'] == 'select') {
875 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
877 else if ($field['type'] == 'checkbox') {
878 $options[$field['title']] = $fieldName;
879 $this->addCheckBox($fieldName, NULL,
881 NULL, NULL, NULL, $this->_fourColumnAttribute
886 $this->assign('otherOptions', $this->_options
);
889 function addChartOptions() {
890 if (!empty($this->_charts
)) {
891 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
892 $this->assign('charts', $this->_charts
);
893 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
897 function addGroupBys() {
898 $options = $freqElements = array();
900 foreach ($this->_columns
as $tableName => $table) {
901 if (array_key_exists('group_bys', $table)) {
902 foreach ($table['group_bys'] as $fieldName => $field) {
903 if (!empty($field)) {
904 $options[$field['title']] = $fieldName;
905 if (CRM_Utils_Array
::value('frequency', $field)) {
906 $freqElements[$field['title']] = $fieldName;
912 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
913 NULL, NULL, NULL, $this->_fourColumnAttribute
915 $this->assign('groupByElements', $options);
917 foreach ($freqElements as $name) {
918 $this->addElement('select', "group_bys_freq[$name]",
919 ts('Frequency'), $this->_groupByDateFreq
924 function addOrderBys() {
926 foreach ($this->_columns
as $tableName => $table) {
928 // Report developer may define any column to order by; include these as order-by options
929 if (array_key_exists('order_bys', $table)) {
930 foreach ($table['order_bys'] as $fieldName => $field) {
931 if (!empty($field)) {
932 $options[$fieldName] = $field['title'];
937 /* Add searchable custom fields as order-by options, if so requested
938 * (These are already indexed, so allowing to order on them is cheap.)
942 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
943 foreach ($table['fields'] as $fieldName => $field) {
944 if (!CRM_Utils_Array
::value('no_display', $field)) {
945 $options[$fieldName] = $field['title'];
953 $this->assign('orderByOptions', $options);
955 if (!empty($options)) {
957 '-' => ' - none - ') +
$options;
958 for ($i = 1; $i <= 5; $i++
) {
959 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
960 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
961 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
962 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
967 function buildInstanceAndButtons() {
968 CRM_Report_Form_Instance
::buildForm($this);
970 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
972 $this->addElement('submit', $this->_instanceButtonName
, $label);
973 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
974 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
977 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
979 if ($this->_instanceForm
) {
980 $this->assign('instanceForm', TRUE);
983 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
984 $this->addElement('submit', $this->_printButtonName
, $label);
986 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
987 $this->addElement('submit', $this->_pdfButtonName
, $label);
989 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
991 if ($this->_csvSupported
) {
992 $this->addElement('submit', $this->_csvButtonName
, $label);
995 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
996 $this->addElement('select', 'groups', ts('Group'),
997 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
999 $this->assign('group', TRUE);
1002 $label = ts('Add these Contacts to Group');
1003 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1005 $this->addChartOptions();
1006 $this->addButtons(array(
1009 'name' => ts('Preview Report'),
1010 'isDefault' => TRUE,
1016 function buildQuickForm() {
1017 $this->addColumns();
1019 $this->addFilters();
1021 $this->addOptions();
1023 $this->addGroupBys();
1025 $this->addOrderBys();
1027 $this->buildInstanceAndButtons();
1029 //add form rule for report
1030 if (is_callable(array(
1031 $this, 'formRule'))) {
1032 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1036 // a formrule function to ensure that fields selected in group_by
1037 // (if any) should only be the ones present in display/select fields criteria;
1038 // note: works if and only if any custom field selected in group_by.
1039 function customDataFormRule($fields, $ignoreFields = array( )) {
1041 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1042 foreach ($this->_columns
as $tableName => $table) {
1043 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1044 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1045 if (array_key_exists($fieldName, $fields['group_bys']) &&
1046 !array_key_exists($fieldName, $fields['fields'])
1048 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1050 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1051 foreach ($fields['fields'] as $fld => $val) {
1052 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1053 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1064 // Note: $fieldName param allows inheriting class to build operationPairs
1065 // specific to a field.
1066 function getOperationPair($type = "string", $fieldName = NULL) {
1067 // FIXME: At some point we should move these key-val pairs
1068 // to option_group and option_value table.
1070 case CRM_Report_FORM
::OP_INT
:
1071 case CRM_Report_FORM
::OP_FLOAT
:
1073 'lte' => ts('Is less than or equal to'),
1074 'gte' => ts('Is greater than or equal to'),
1075 'bw' => ts('Is between'),
1076 'eq' => ts('Is equal to'),
1077 'lt' => ts('Is less than'),
1078 'gt' => ts('Is greater than'),
1079 'neq' => ts('Is not equal to'),
1080 'nbw' => ts('Is not between'),
1081 'nll' => ts('Is empty (Null)'),
1082 'nnll' => ts('Is not empty (Null)'),
1086 case CRM_Report_FORM
::OP_SELECT
:
1088 'eq' => ts('Is equal to'),
1091 case CRM_Report_FORM
::OP_MONTH
:
1092 case CRM_Report_FORM
::OP_MULTISELECT
:
1094 'in' => ts('Is one of'),
1095 'notin' => ts('Is not one of'),
1099 case CRM_Report_FORM
::OP_DATE
:
1101 'nll' => ts('Is empty (Null)'),
1102 'nnll' => ts('Is not empty (Null)'),
1106 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1107 // use this operator for the values, concatenated with separator. For e.g if
1108 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1110 'mhas' => ts('Is one of'),
1116 'has' => ts('Contains'),
1117 'sw' => ts('Starts with'),
1118 'ew' => ts('Ends with'),
1119 'nhas' => ts('Does not contain'),
1120 'eq' => ts('Is equal to'),
1121 'neq' => ts('Is not equal to'),
1122 'nll' => ts('Is empty (Null)'),
1123 'nnll' => ts('Is not empty (Null)'),
1128 function buildTagFilter() {
1129 $contactTags = CRM_Core_BAO_Tag
::getTags();
1130 if (!empty($contactTags)) {
1131 $this->_columns
['civicrm_tag'] = array(
1132 'dao' => 'CRM_Core_DAO_Tag',
1138 'title' => ts('Tag'),
1140 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1141 'options' => $contactTags,
1149 * Adds group filters to _columns (called from _Constuct
1151 function buildGroupFilter() {
1152 $this->_columns
['civicrm_group']['filters'] = array(
1155 'name' => 'group_id',
1156 'title' => ts('Group'),
1157 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1159 'options' => CRM_Core_PseudoConstant
::group(),
1162 if (empty($this->_columns
['civicrm_group']['dao'])) {
1163 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1165 if (empty($this->_columns
['civicrm_group']['alias'])) {
1166 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1170 function getSQLOperator($operator = "like") {
1171 switch ($operator) {
1204 return 'IS NOT NULL';
1212 function whereClause(&$field, $op,
1216 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1222 if (($min !== NULL && strlen($min) > 0) ||
1223 ($max !== NULL && strlen($max) > 0)
1225 $min = CRM_Utils_Type
::escape($min, $type);
1226 $max = CRM_Utils_Type
::escape($max, $type);
1230 $clauses[] = "( {$field['dbAlias']} >= $min )";
1233 $clauses[] = "( {$field['dbAlias']} < $min )";
1238 $clauses[] = "( {$field['dbAlias']} <= $max )";
1241 $clauses[] = "( {$field['dbAlias']} > $max )";
1245 if (!empty($clauses)) {
1247 $clause = implode(' AND ', $clauses);
1250 $clause = implode(' OR ', $clauses);
1258 if ($value !== NULL && strlen($value) > 0) {
1259 $value = CRM_Utils_Type
::escape($value, $type);
1260 if (strpos($value, '%') === FALSE) {
1261 $value = "'%{$value}%'";
1264 $value = "'{$value}'";
1266 $sqlOP = $this->getSQLOperator($op);
1267 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1273 if ($value !== NULL && is_array($value) && count($value) > 0) {
1274 $sqlOP = $this->getSQLOperator($op);
1275 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1276 //cycle through selections and esacape values
1277 foreach ($value as $key => $selection) {
1278 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1280 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1283 // for numerical values
1284 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1286 if ($op == 'notin') {
1287 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1290 $clause = "( " . $clause . " )";
1296 // mhas == multiple has
1297 if ($value !== NULL && count($value) > 0) {
1298 $sqlOP = $this->getSQLOperator($op);
1299 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1305 if ($value !== NULL && strlen($value) > 0) {
1306 $value = CRM_Utils_Type
::escape($value, $type);
1307 if (strpos($value, '%') === FALSE) {
1309 $value = "'{$value}%'";
1312 $value = "'%{$value}'";
1316 $value = "'{$value}'";
1318 $sqlOP = $this->getSQLOperator($op);
1319 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1325 $sqlOP = $this->getSQLOperator($op);
1326 $clause = "( {$field['dbAlias']} $sqlOP )";
1330 if ($value !== NULL && strlen($value) > 0) {
1331 if (isset($field['clause'])) {
1332 // FIXME: we not doing escape here. Better solution is to use two
1333 // different types - data-type and filter-type
1334 $clause = $field['clause'];
1337 $value = CRM_Utils_Type
::escape($value, $type);
1338 $sqlOP = $this->getSQLOperator($op);
1339 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1340 $value = "'{$value}'";
1342 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1348 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1349 $clause = $this->whereGroupClause($field, $value, $op);
1351 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1352 // not using left join in query because if any contact
1353 // belongs to more than one tag, results duplicate
1355 $clause = $this->whereTagClause($field, $value, $op);
1361 function dateClause($fieldName,
1362 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1365 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1366 $sqlOP = $this->getSQLOperator($relative);
1367 return "( {$fieldName} {$sqlOP} )";
1370 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1373 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1374 $clauses[] = "( {$fieldName} >= $from )";
1378 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1379 $clauses[] = "( {$fieldName} <= {$to} )";
1382 if (!empty($clauses)) {
1383 return implode(' AND ', $clauses);
1389 * @todo - could not find any instances where this is called
1390 * @param unknown_type $relative
1391 * @param String $from
1392 * @param String_type $to
1393 * @return string|NULL
1395 function dateDisplay($relative, $from, $to) {
1396 list($from, $to) = $this->getFromTo($relative, $from, $to);
1399 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1402 $clauses[] = 'Past';
1406 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1409 $clauses[] = 'Today';
1412 if (!empty($clauses)) {
1413 return implode(' - ', $clauses);
1419 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1420 if (empty($totime)) {
1423 //FIX ME not working for relative
1425 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1426 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1427 $from = substr($dateRange['from'], 0, 8);
1428 //Take only Date Part, Sometime Time part is also present in 'to'
1429 $to = substr($dateRange['to'], 0, 8);
1431 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1432 $to = CRM_Utils_Date
::processDate($to, $totime);
1433 return array($from, $to);
1436 function alterDisplay(&$rows) {
1437 // custom code to alter rows
1440 function alterCustomDataDisplay(&$rows) {
1441 // custom code to alter rows having custom values
1442 if (empty($this->_customGroupExtends
)) {
1446 $customFieldIds = array();
1447 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1448 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1449 $customFieldIds[$fieldAlias] = $fieldId;
1452 if (empty($customFieldIds)) {
1456 $customFields = $fieldValueMap = array();
1457 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1459 // skip for type date and ContactReference since date format is already handled
1461 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1462 FROM civicrm_custom_field cf
1463 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1464 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1465 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1466 cg.is_active = 1 AND
1467 cf.is_active = 1 AND
1468 cf.is_searchable = 1 AND
1469 cf.data_type NOT IN ('ContactReference', 'Date') AND
1470 cf.id IN (" . implode(",", $customFieldIds) . ")";
1472 $dao = CRM_Core_DAO
::executeQuery($query);
1473 while ($dao->fetch()) {
1474 foreach ($customFieldCols as $key) {
1475 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1477 if ($dao->option_group_id
) {
1478 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1483 $entryFound = FALSE;
1484 foreach ($rows as $rowNum => $row) {
1485 foreach ($row as $tableCol => $val) {
1486 if (array_key_exists($tableCol, $customFields)) {
1487 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1492 // skip looking further in rows, if first row itself doesn't
1493 // have the column we need
1500 function formatCustomValues($value, $customField, $fieldValueMap) {
1501 if (CRM_Utils_System
::isNull($value)) {
1505 $htmlType = $customField['html_type'];
1507 switch ($customField['data_type']) {
1509 if ($value == '1') {
1510 $retValue = ts('Yes');
1513 $retValue = ts('No');
1518 $retValue = CRM_Utils_System
::formatWikiURL($value);
1530 if ($htmlType == 'Text') {
1531 $retValue = (float)$value;
1535 if ($htmlType == 'Text') {
1545 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1550 if (in_array($htmlType, array(
1551 'Text', 'TextArea'))) {
1555 case 'StateProvince':
1558 switch ($htmlType) {
1559 case 'Multi-Select Country':
1560 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1561 $customData = array();
1562 foreach ($value as $val) {
1564 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1567 $retValue = implode(', ', $customData);
1570 case 'Select Country':
1571 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1574 case 'Select State/Province':
1575 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1578 case 'Multi-Select State/Province':
1579 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1580 $customData = array();
1581 foreach ($value as $val) {
1583 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1586 $retValue = implode(', ', $customData);
1591 case 'Autocomplete-Select':
1592 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1596 case 'AdvMulti-Select':
1597 case 'Multi-Select':
1598 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1599 $customData = array();
1600 foreach ($value as $val) {
1602 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1605 $retValue = implode(', ', $customData);
1620 function removeDuplicates(&$rows) {
1621 if (empty($this->_noRepeats
)) {
1624 $checkList = array();
1626 foreach ($rows as $key => $list) {
1627 foreach ($list as $colName => $colVal) {
1628 if (array_key_exists($colName, $checkList) &&
1629 $checkList[$colName] == $colVal) {
1630 $rows[$key][$colName] = "";
1632 if (in_array($colName, $this->_noRepeats
)) {
1633 $checkList[$colName] = $colVal;
1639 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1640 foreach ($row as $colName => $colVal) {
1641 if (in_array($colName, $fields)) {
1642 $row[$colName] = $row[$colName];
1644 elseif (isset($this->_columnHeaders
[$colName])) {
1646 $row[$colName] = "Subtotal";
1650 unset($row[$colName]);
1656 function grandTotal(&$rows) {
1657 if (!$this->_rollup ||
($this->_rollup
== '') ||
1658 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1662 $lastRow = array_pop($rows);
1664 foreach ($this->_columnHeaders
as $fld => $val) {
1665 if (!in_array($fld, $this->_statFields
)) {
1666 if (!$this->_grandFlag
) {
1667 $lastRow[$fld] = "Grand Total";
1668 $this->_grandFlag
= TRUE;
1671 $lastRow[$fld] = "";
1676 $this->assign('grandStat', $lastRow);
1680 function formatDisplay(&$rows, $pager = TRUE) {
1681 // set pager based on if any limit was applied in the query.
1686 // allow building charts if any
1687 if (!empty($this->_params
['charts']) && !empty($rows)) {
1688 $this->buildChart($rows);
1689 $this->assign('chartEnabled', TRUE);
1690 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1691 $this->assign('chartId', $this->_chartId
);
1694 // unset columns not to be displayed.
1695 foreach ($this->_columnHeaders
as $key => $value) {
1696 if (CRM_Utils_Array
::value('no_display', $value)) {
1697 unset($this->_columnHeaders
[$key]);
1701 // unset columns not to be displayed.
1702 if (!empty($rows)) {
1703 foreach ($this->_noDisplay
as $noDisplayField) {
1704 foreach ($rows as $rowNum => $row) {
1705 unset($this->_columnHeaders
[$noDisplayField]);
1710 // build array of section totals
1711 $this->sectionTotals();
1713 // process grand-total row
1714 $this->grandTotal($rows);
1716 // use this method for formatting rows for display purpose.
1717 $this->alterDisplay($rows);
1718 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1720 // use this method for formatting custom rows for display purpose.
1721 $this->alterCustomDataDisplay($rows);
1724 function buildChart(&$rows) {
1725 // override this method for building charts.
1728 // select() method below has been added recently (v3.3), and many of the report templates might
1729 // still be having their own select() method. We should fix them as and when encountered and move
1730 // towards generalizing the select() method below.
1732 $select = $this->_selectAliases
= array();
1734 foreach ($this->_columns
as $tableName => $table) {
1735 if (array_key_exists('fields', $table)) {
1736 foreach ($table['fields'] as $fieldName => $field) {
1737 if ($tableName == 'civicrm_address') {
1738 $this->_addressField
= TRUE;
1740 if ($tableName == 'civicrm_email') {
1741 $this->_emailField
= TRUE;
1743 if ($tableName == 'civicrm_phone') {
1744 $this->_phoneField
= TRUE;
1747 if (CRM_Utils_Array
::value('required', $field) ||
1748 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1751 // 1. In many cases we want select clause to be built in slightly different way
1752 // for a particular field of a particular type.
1753 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1755 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1756 if ($selectClause) {
1757 $select[] = $selectClause;
1761 // include statistics columns only if set
1762 if (CRM_Utils_Array
::value('statistics', $field)) {
1763 foreach ($field['statistics'] as $stat => $label) {
1764 $alias = "{$tableName}_{$fieldName}_{$stat}";
1765 switch (strtolower($stat)) {
1768 $select[] = "$stat({$field['dbAlias']}) as $alias";
1769 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1770 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1771 $this->_statFields
[$label] = $alias;
1772 $this->_selectAliases
[] = $alias;
1776 $select[] = "COUNT({$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;
1783 case 'count_distinct':
1784 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1785 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1786 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1787 $this->_statFields
[$label] = $alias;
1788 $this->_selectAliases
[] = $alias;
1792 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1793 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1794 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1795 $this->_statFields
[$label] = $alias;
1796 $this->_selectAliases
[] = $alias;
1802 $alias = "{$tableName}_{$fieldName}";
1803 $select[] = "{$field['dbAlias']} as $alias";
1804 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1805 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1806 $this->_selectAliases
[] = $alias;
1812 // select for group bys
1813 if (array_key_exists('group_bys', $table)) {
1814 foreach ($table['group_bys'] as $fieldName => $field) {
1816 if ($tableName == 'civicrm_address') {
1817 $this->_addressField
= TRUE;
1819 if ($tableName == 'civicrm_email') {
1820 $this->_emailField
= TRUE;
1822 if ($tableName == 'civicrm_phone') {
1823 $this->_phoneField
= TRUE;
1825 // 1. In many cases we want select clause to be built in slightly different way
1826 // for a particular field of a particular type.
1827 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1829 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1830 if ($selectClause) {
1831 $select[] = $selectClause;
1835 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1836 && !empty($this->_params
['group_bys_freq'])) {
1837 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1839 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1840 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1841 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1842 $field['title'] = 'Week';
1846 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1847 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1848 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1849 $field['title'] = 'Year';
1853 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1854 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1855 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1856 $field['title'] = 'Month';
1860 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1861 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1862 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1863 $field['title'] = 'Quarter';
1866 // for graphs and charts -
1867 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1868 $this->_interval
= $field['title'];
1869 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1870 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1871 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1873 // just to make sure these values are transfered to rows.
1874 // since we 'll need them for calculation purpose,
1875 // e.g making subtotals look nicer or graphs
1876 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1877 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1884 $this->_selectClauses
= $select;
1885 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1888 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1893 $this->storeWhereHavingClauseArray();
1895 if (empty($this->_whereClauses
)) {
1896 $this->_where
= "WHERE ( 1 ) ";
1897 $this->_having
= "";
1900 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1903 if ($this->_aclWhere
) {
1904 $this->_where
.= " AND {$this->_aclWhere} ";
1907 if (!empty($this->_havingClauses
)) {
1908 // use this clause to construct group by clause.
1909 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1914 * Store Where clauses into an array - breaking out this step makes
1915 * over-riding more flexible as the clauses can be used in constructing a
1916 * temp table that may not be part of the final where clause or added
1917 * in other functions
1919 function storeWhereHavingClauseArray(){
1920 foreach ($this->_columns
as $tableName => $table) {
1921 if (array_key_exists('filters', $table)) {
1922 foreach ($table['filters'] as $fieldName => $field) {
1923 // respect pseudofield to filter spec so fields can be marked as
1924 // not to be handled here
1925 if(!empty($field['pseudofield'])){
1929 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1930 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1931 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1932 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1933 if (is_array($value) && !empty($value)) {
1934 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1938 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1939 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1940 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1941 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1942 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1943 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1947 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1949 $clause = $this->whereClause($field,
1951 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1952 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1953 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1958 if (!empty($clause)) {
1959 if (CRM_Utils_Array
::value('having', $field)) {
1960 $this->_havingClauses
[] = $clause;
1963 $this->_whereClauses
[] = $clause;
1971 function processReportMode() {
1972 $buttonName = $this->controller
->getButtonName();
1974 $output = CRM_Utils_Request
::retrieve(
1977 CRM_Core_DAO
::$_nullObject
1981 CRM_Utils_Request
::retrieve(
1984 CRM_Core_DAO
::$_nullObject
1987 $this->_absoluteUrl
= FALSE;
1989 $this->assign('printOnly', FALSE);
1991 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1992 $this->assign('printOnly', TRUE);
1994 $this->assign('outputMode', 'print');
1995 $this->_outputMode
= 'print';
1996 if ($this->_sendmail
) {
1997 $this->_absoluteUrl
= TRUE;
2000 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2001 $this->assign('printOnly', TRUE);
2003 $this->assign('outputMode', 'pdf');
2004 $this->_outputMode
= 'pdf';
2005 $this->_absoluteUrl
= TRUE;
2007 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2008 $this->assign('printOnly', TRUE);
2010 $this->assign('outputMode', 'csv');
2011 $this->_outputMode
= 'csv';
2012 $this->_absoluteUrl
= TRUE;
2014 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2015 $this->assign('outputMode', 'group');
2016 $this->_outputMode
= 'group';
2018 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2019 $this->assign('outputMode', 'create_report');
2020 $this->_outputMode
= 'create_report';
2023 $this->assign('outputMode', 'html');
2024 $this->_outputMode
= 'html';
2027 // Get today's date to include in printed reports
2029 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2030 $this->assign('reportDate', $reportDate);
2034 function beginPostProcess() {
2035 $this->_params
= $this->controller
->exportValues($this->_name
);
2037 if (empty($this->_params
) &&
2040 $this->_params
= $this->_formValues
;
2043 // hack to fix params when submitted from dashboard, CRM-8532
2044 // fields array is missing because form building etc is skipped
2045 // in dashboard mode for report
2046 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2047 $this->_params
= $this->_formValues
;
2050 $this->_formValues
= $this->_params
;
2051 if (CRM_Core_Permission
::check('administer Reports') &&
2052 isset($this->_id
) &&
2053 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2054 $this->_chartButtonName
== $this->controller
->getButtonName()
2057 $this->assign('updateReportButton', TRUE);
2059 $this->processReportMode();
2062 function buildQuery($applyLimit = TRUE) {
2065 $this->customDataFrom();
2070 // order_by columns not selected for display need to be included in SELECT
2071 $unselectedSectionColumns = $this->unselectedSectionColumns();
2072 foreach ($unselectedSectionColumns as $alias => $section) {
2073 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2076 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2079 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2081 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2085 function groupBy() {
2086 $groupBys = array();
2087 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2088 is_array($this->_params
['group_bys']) &&
2089 !empty($this->_params
['group_bys'])
2091 foreach ($this->_columns
as $tableName => $table) {
2092 if (array_key_exists('group_bys', $table)) {
2093 foreach ($table['group_bys'] as $fieldName => $field) {
2094 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2095 $groupBys[] = $field['dbAlias'];
2102 if (!empty($groupBys)) {
2103 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2107 function orderBy() {
2108 $this->_orderBy
= "";
2109 $this->_sections
= array();
2110 $this->storeOrderByArray();
2111 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2112 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2114 $this->assign('sections', $this->_sections
);
2118 * In some cases other functions want to know which fields are selected for ordering by
2119 * Separating this into a separate function allows it to be called separately from constructing
2120 * the order by clause
2122 function storeOrderByArray() {
2123 $orderBys = array();
2125 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2126 is_array($this->_params
['order_bys']) &&
2127 !empty($this->_params
['order_bys'])
2130 // Proces order_bys in user-specified order
2131 foreach ($this->_params
['order_bys'] as $orderBy) {
2132 $orderByField = array();
2133 foreach ($this->_columns
as $tableName => $table) {
2134 if (array_key_exists('order_bys', $table)) {
2135 // For DAO columns defined in $this->_columns
2136 $fields = $table['order_bys'];
2138 elseif (array_key_exists('extends', $table)) {
2139 // For custom fields referenced in $this->_customGroupExtends
2140 $fields = $table['fields'];
2142 if (!empty($fields) && is_array($fields)) {
2143 foreach ($fields as $fieldName => $field) {
2144 if ($fieldName == $orderBy['column']) {
2145 $orderByField = array_merge($field, $orderBy);
2146 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2153 if (!empty($orderByField)) {
2154 $this->_orderByFields
[] = $orderByField;
2155 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2157 // Record any section headers for assignment to the template
2158 if (CRM_Utils_Array
::value('section', $orderBy)) {
2159 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2160 $this->_sections
[$orderByField['tplField']] = $orderByField;
2166 $this->_orderByArray
= $orderBys;
2168 $this->assign('sections', $this->_sections
);
2171 function unselectedSectionColumns() {
2172 $selectColumns = array();
2173 foreach ($this->_columns
as $tableName => $table) {
2174 if (array_key_exists('fields', $table)) {
2175 foreach ($table['fields'] as $fieldName => $field) {
2176 if (CRM_Utils_Array
::value('required', $field) ||
2177 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2180 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2186 if (is_array($this->_sections
)) {
2187 return array_diff_key($this->_sections
, $selectColumns);
2194 function buildRows($sql, &$rows) {
2195 $dao = CRM_Core_DAO
::executeQuery($sql);
2196 if (!is_array($rows)) {
2200 // use this method to modify $this->_columnHeaders
2201 $this->modifyColumnHeaders();
2203 $unselectedSectionColumns = $this->unselectedSectionColumns();
2205 while ($dao->fetch()) {
2207 foreach ($this->_columnHeaders
as $key => $value) {
2208 if (property_exists($dao, $key)) {
2209 $row[$key] = $dao->$key;
2213 // section headers not selected for display need to be added to row
2214 foreach ($unselectedSectionColumns as $key => $values) {
2215 if (property_exists($dao, $key)) {
2216 $row[$key] = $dao->$key;
2225 * When "order by" fields are marked as sections, this assigns to the template
2226 * an array of total counts for each section. This data is used by the Smarty
2227 * plugin {sectionTotal}
2229 function sectionTotals() {
2231 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2232 if (empty($this->_selectAliases
)) {
2236 if (!empty($this->_sections
)) {
2237 // build the query with no LIMIT clause
2238 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2239 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2241 // pull section aliases out of $this->_sections
2242 $sectionAliases = array_keys($this->_sections
);
2245 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2246 $ifnulls[] = "ifnull($alias, '') as $alias";
2249 /* Group (un-limited) report by all aliases and get counts. This might
2250 * be done more efficiently when the contents of $sql are known, ie. by
2251 * overriding this method in the report class.
2255 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2257 // initialize array of total counts
2259 $dao = CRM_Core_DAO
::executeQuery($query);
2260 while ($dao->fetch()) {
2262 // let $this->_alterDisplay translate any integer ids to human-readable values.
2263 $rows[0] = $dao->toArray();
2264 $this->alterDisplay($rows);
2267 // add totals for all permutations of section values
2270 $aliasCount = count($sectionAliases);
2271 foreach ($sectionAliases as $alias) {
2272 $values[] = $row[$alias];
2273 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2274 if ($i == $aliasCount) {
2275 // the last alias is the lowest-level section header; use count as-is
2276 $totals[$key] = $dao->ct
;
2279 // other aliases are higher level; roll count into their total
2280 $totals[$key] +
= $dao->ct
;
2284 $this->assign('sectionTotals', $totals);
2288 function modifyColumnHeaders() {
2289 // use this method to modify $this->_columnHeaders
2292 function doTemplateAssignment(&$rows) {
2293 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2294 $this->assign_by_ref('rows', $rows);
2295 $this->assign('statistics', $this->statistics($rows));
2298 // override this method to build your own statistics
2299 function statistics(&$rows) {
2300 $statistics = array();
2302 $count = count($rows);
2304 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2308 $this->countStat($statistics, $count);
2310 $this->groupByStat($statistics);
2312 $this->filterStat($statistics);
2317 function countStat(&$statistics, $count) {
2318 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2322 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2323 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2324 'value' => $this->_rowsFound
,
2329 function groupByStat(&$statistics) {
2330 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2331 is_array($this->_params
['group_bys']) &&
2332 !empty($this->_params
['group_bys'])
2334 foreach ($this->_columns
as $tableName => $table) {
2335 if (array_key_exists('group_bys', $table)) {
2336 foreach ($table['group_bys'] as $fieldName => $field) {
2337 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2338 $combinations[] = $field['title'];
2343 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2344 'value' => implode(' & ', $combinations),
2349 function filterStat(&$statistics) {
2350 foreach ($this->_columns
as $tableName => $table) {
2351 if (array_key_exists('filters', $table)) {
2352 foreach ($table['filters'] as $fieldName => $field) {
2353 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2356 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2357 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2358 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2359 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2360 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2362 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2363 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2365 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2366 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2369 $statistics['filters'][] = array(
2370 'title' => $field['title'],
2371 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2374 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2375 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2377 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2378 $statistics['filters'][] = array(
2379 'title' => $field['title'],
2380 'value' => $pair[$rel],
2385 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2388 $pair = $this->getOperationPair(
2389 CRM_Utils_Array
::value('operatorType', $field),
2392 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2393 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2394 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2395 if (in_array($op, array(
2396 'bw', 'nbw')) && ($min ||
$max)) {
2397 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2399 elseif ($op == 'nll' ||
$op == 'nnll') {
2400 $value = $pair[$op];
2402 elseif (is_array($val) && (!empty($val))) {
2403 $options = CRM_Utils_Array
::value('options', $field, array());
2404 foreach ($val as $key => $valIds) {
2405 if (isset($options[$valIds])) {
2406 $val[$key] = $options[$valIds];
2409 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2410 $val = implode(', ', $val);
2411 $value = "{$pair[$op]} " . $val;
2413 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2414 is_array($field['options']) && !empty($field['options'])
2416 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2419 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2423 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2433 function endPostProcess(&$rows = NULL) {
2434 if ( $this->_storeResultSet
) {
2435 $this->_resultSet
= $rows;
2438 if ($this->_outputMode
== 'print' ||
2439 $this->_outputMode
== 'pdf' ||
2443 $content = $this->compileContent();
2444 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2448 if ($this->_sendmail
) {
2449 $config = CRM_Core_Config
::singleton();
2450 $attachments = array();
2452 if ($this->_outputMode
== 'csv') {
2453 $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'];
2455 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2456 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2457 file_put_contents($csvFullFilename, $csvContent);
2458 $attachments[] = array(
2459 'fullPath' => $csvFullFilename,
2460 'mime_type' => 'text/csv',
2461 'cleanName' => 'CiviReport.csv',
2464 if ($this->_outputMode
== 'pdf') {
2465 // generate PDF content
2466 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2467 file_put_contents($pdfFullFilename,
2468 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2469 TRUE, array('orientation' => 'landscape')
2472 // generate Email Content
2473 $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'];
2475 $attachments[] = array(
2476 'fullPath' => $pdfFullFilename,
2477 'mime_type' => 'application/pdf',
2478 'cleanName' => 'CiviReport.pdf',
2482 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2483 $this->_outputMode
, $attachments
2485 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2488 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2491 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2493 elseif ($this->_outputMode
== 'print') {
2497 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2498 $config = CRM_Core_Config
::singleton();
2499 //get chart image name
2500 $chartImg = $this->_chartId
. '.png';
2501 //get image url path
2502 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2503 $uploadUrl .= $chartImg;
2504 //get image doc path to overwrite
2505 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2507 $chart = imagecreatefrompng($uploadUrl);
2508 //convert it into formattd png
2509 header('Content-type: image/png');
2510 //overwrite with same image
2511 imagepng($chart, $uploadImg);
2513 imagedestroy($chart);
2515 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2517 CRM_Utils_System
::civiExit();
2519 elseif ($this->_outputMode
== 'csv') {
2520 CRM_Report_Utils_Report
::export2csv($this, $rows);
2522 elseif ($this->_outputMode
== 'group') {
2523 $group = $this->_params
['groups'];
2524 $this->add2group($group);
2526 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2527 CRM_Report_Form_Instance
::postProcess($this);
2529 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2530 $this->_outputMode
== 'create_report' ) {
2531 $this->_createNew
= TRUE;
2532 CRM_Report_Form_Instance
::postProcess($this);
2536 function storeResultSet() {
2537 $this->_storeResultSet
= TRUE;
2540 function getResultSet() {
2541 return $this->_resultSet
;
2545 * Get Template file name - use default form template if a specific one has not been set up for this report
2548 function getTemplateFileName(){
2549 $defaultTpl = parent
::getTemplateFileName();
2550 $template = CRM_Core_Smarty
::singleton();
2551 if (!$template->template_exists($defaultTpl)) {
2552 $defaultTpl = 'CRM/Report/Form.tpl';
2558 * Compile the report content
2560 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2562 function compileContent(){
2563 $templateFile = $this->getHookedTemplateFileName();
2564 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2568 function postProcess() {
2569 // get ready with post process params
2570 $this->beginPostProcess();
2573 $sql = $this->buildQuery();
2575 // build array of result based on column headers. This method also allows
2576 // modifying column headers before using it to build result set i.e $rows.
2578 $this->buildRows($sql, $rows);
2580 // format result set.
2581 $this->formatDisplay($rows);
2583 // assign variables to templates
2584 $this->doTemplateAssignment($rows);
2586 // do print / pdf / instance stuff if needed
2587 $this->endPostProcess($rows);
2590 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2591 // lets do the pager if in html mode
2592 $this->_limit
= NULL;
2593 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2594 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2596 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2598 if (!$pageId && !empty($_POST)) {
2599 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2600 $pageId = max((int)@$_POST['crmPID_B'], 1);
2602 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2603 $pageId = max((int)@$_POST['crmPID'], 1);
2605 unset($_POST['crmPID_B'], $_POST['crmPID']);
2608 $pageId = $pageId ?
$pageId : 1;
2609 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2610 $offset = ($pageId - 1) * $rowCount;
2612 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2613 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2615 $this->_limit
= " LIMIT $offset, $rowCount";
2616 return array($offset, $rowCount);
2620 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2621 if ($this->_limit
&& ($this->_limit
!= '')) {
2622 $sql = "SELECT FOUND_ROWS();";
2623 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2625 'total' => $this->_rowsFound
,
2626 'rowCount' => $rowCount,
2627 'status' => ts('Records') . ' %%StatusMessage%%',
2628 'buttonBottom' => 'PagerBottomButton',
2629 'buttonTop' => 'PagerTopButton',
2630 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2633 $pager = new CRM_Utils_Pager($params);
2634 $this->assign_by_ref('pager', $pager);
2638 function whereGroupClause($field, $value, $op) {
2640 $smartGroupQuery = "";
2642 $group = new CRM_Contact_DAO_Group();
2643 $group->is_active
= 1;
2645 $smartGroups = array();
2646 while ($group->fetch()) {
2647 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2648 $smartGroups[] = $group->id
;
2652 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2654 $smartGroupQuery = '';
2655 if (!empty($smartGroups)) {
2656 $smartGroups = implode(',', $smartGroups);
2657 $smartGroupQuery = " UNION DISTINCT
2658 SELECT DISTINCT smartgroup_contact.contact_id
2659 FROM civicrm_group_contact_cache smartgroup_contact
2660 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2663 $sqlOp = $this->getSQLOperator($op);
2664 if (!is_array($value)) {
2665 $value = array($value);
2667 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2669 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2670 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2671 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2672 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2673 {$smartGroupQuery} ) ";
2676 function whereTagClause($field, $value, $op) {
2677 // not using left join in query because if any contact
2678 // belongs to more than one tag, results duplicate
2680 $sqlOp = $this->getSQLOperator($op);
2681 if (!is_array($value)) {
2682 $value = array($value);
2684 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2686 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2687 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2688 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2689 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2692 function buildACLClause($tableAlias = 'contact_a') {
2693 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2696 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2697 if (empty($this->_customGroupExtends
)) {
2700 if (!is_array($this->_customGroupExtends
)) {
2701 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2703 $customGroupWhere = '';
2704 if (!empty($permCustomGroupIds)) {
2705 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2708 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2709 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2710 FROM civicrm_custom_group cg
2711 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2712 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2714 cg.is_active = 1 AND
2715 cf.is_active = 1 AND
2716 cf.is_searchable = 1
2717 ORDER BY cg.weight, cf.weight";
2718 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2721 while ($customDAO->fetch()) {
2722 if ($customDAO->table_name
!= $curTable) {
2723 $curTable = $customDAO->table_name
;
2724 $curFields = $curFilters = array();
2727 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2728 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2729 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2730 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2733 'fields', 'filters', 'group_bys') as $colKey) {
2734 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2735 $this->_columns
[$curTable][$colKey] = array();
2739 $fieldName = 'custom_' . $customDAO->cf_id
;
2742 // this makes aliasing work in favor
2743 $curFields[$fieldName] = array(
2744 'name' => $customDAO->column_name
,
2745 'title' => $customDAO->label
,
2746 'dataType' => $customDAO->data_type
,
2747 'htmlType' => $customDAO->html_type
,
2750 if ($this->_customGroupFilters
) {
2751 // this makes aliasing work in favor
2752 $curFilters[$fieldName] = array(
2753 'name' => $customDAO->column_name
,
2754 'title' => $customDAO->label
,
2755 'dataType' => $customDAO->data_type
,
2756 'htmlType' => $customDAO->html_type
,
2760 switch ($customDAO->data_type
) {
2763 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2764 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2765 // CRM-6946, show time part for datetime date fields
2766 if ($customDAO->time_format
) {
2767 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2772 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2773 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2777 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2781 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2782 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2786 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2787 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2791 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2792 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2796 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2798 if (!empty($customDAO->option_group_id
)) {
2799 if (in_array($customDAO->html_type
, array(
2800 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2801 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2804 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2806 if ($this->_customGroupFilters
) {
2807 $curFilters[$fieldName]['options'] = array();
2808 $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')));
2809 while ($ogDAO->fetch()) {
2810 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2816 case 'StateProvince':
2817 if (in_array($customDAO->html_type
, array(
2818 'Multi-Select State/Province'))) {
2819 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2822 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2824 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2828 if (in_array($customDAO->html_type
, array(
2829 'Multi-Select Country'))) {
2830 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2833 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2835 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2838 case 'ContactReference':
2839 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2840 $curFilters[$fieldName]['name'] = 'display_name';
2841 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2843 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2844 $curFields[$fieldName]['name'] = 'display_name';
2845 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2849 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2850 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2853 if (!array_key_exists('type', $curFields[$fieldName])) {
2854 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2858 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2860 if ($this->_customGroupFilters
) {
2861 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2863 if ($this->_customGroupGroupBy
) {
2864 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2869 function customDataFrom() {
2870 if (empty($this->_customGroupExtends
)) {
2873 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2875 foreach ($this->_columns
as $table => $prop) {
2876 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2877 $extendsTable = $mapper[$prop['extends']];
2879 // check field is in params
2880 if (!$this->isFieldSelected($prop)) {
2883 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
2885 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2887 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
2888 // handle for ContactReference
2889 if (array_key_exists('fields', $prop)) {
2890 foreach ($prop['fields'] as $fieldName => $field) {
2891 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2892 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2894 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2902 function isFieldSelected($prop) {
2907 if (!empty($this->_params
['fields'])) {
2908 foreach (array_keys($prop['fields']) as $fieldAlias) {
2909 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2910 if ($customFieldId) {
2911 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2915 //might be survey response field.
2916 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2917 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2925 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2926 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2927 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2933 if (!empty($this->_params
['order_bys'])) {
2934 foreach (array_keys($prop['fields']) as $fieldAlias) {
2935 foreach ($this->_params
['order_bys'] as $orderBy) {
2936 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2943 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2944 foreach ($prop['filters'] as $fieldAlias => $val) {
2946 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2947 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2948 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2949 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2955 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2956 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2967 * Check for empty order_by configurations and remove them; also set
2968 * template to hide them.
2970 function preProcessOrderBy(&$formValues) {
2971 // Object to show/hide form elements
2972 $_showHide = new CRM_Core_ShowHideBlocks('', '');
2974 $_showHide->addShow('optionField_1');
2976 // Cycle through order_by options; skip any empty ones, and hide them as well
2979 if (!empty($formValues['order_bys'])) {
2980 foreach ($formValues['order_bys'] as $order_by) {
2981 if ($order_by['column'] && $order_by['column'] != '-') {
2982 $_showHide->addShow('optionField_' . $n);
2983 $orderBys[$n] = $order_by;
2988 for ($i = $n; $i <= 5; $i++
) {
2990 $_showHide->addHide('optionField_' . $i);
2994 // overwrite order_by options with modified values
2995 if (!empty($orderBys)) {
2996 $formValues['order_bys'] = $orderBys;
2999 $formValues['order_bys'] = array(1 => array('column' => '-'));
3002 // assign show/hide data to template
3003 $_showHide->addToTemplate();
3007 * Does table name have columns in SELECT clause?
3009 * @param string $tableName Name of table (index of $this->_columns array)
3013 function isTableSelected($tableName) {
3014 return in_array($tableName, $this->selectedTables());
3018 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3019 * (building the array if it's unset)
3021 * @return Array $this->_selectedTables
3023 function selectedTables() {
3024 if (!$this->_selectedTables
) {
3025 $orderByColumns = array();
3026 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3027 foreach ($this->_params
['order_bys'] as $orderBy) {
3028 $orderByColumns[] = $orderBy['column'];
3032 foreach ($this->_columns
as $tableName => $table) {
3033 if (array_key_exists('fields', $table)) {
3034 foreach ($table['fields'] as $fieldName => $field) {
3035 if (CRM_Utils_Array
::value('required', $field) ||
3036 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3038 $this->_selectedTables
[] = $tableName;
3043 if (array_key_exists('order_bys', $table)) {
3044 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3045 if (in_array($orderByName, $orderByColumns)) {
3046 $this->_selectedTables
[] = $tableName;
3051 if (array_key_exists('filters', $table)) {
3052 foreach ($table['filters'] as $filterName => $filter) {
3053 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3054 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3055 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3057 $this->_selectedTables
[] = $tableName;
3064 return $this->_selectedTables
;
3068 * @deprecated - use getAddressColumns which is a more accurate description
3069 * and also accepts an array of options rather than a long list
3071 * function for adding address fields to construct function in reports
3072 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3073 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3074 * @return array address fields for construct clause
3076 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3077 'country_id' => TRUE)) {
3078 $addressFields = array(
3079 'civicrm_address' =>
3081 'dao' => 'CRM_Core_DAO_Address',
3085 array('title' => ts('Address Name'),
3086 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3089 array('title' => ts('Street Address'),
3090 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3092 'supplemental_address_1' =>
3093 array('title' => ts('Supplementary Address Field 1'),
3094 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3096 'supplemental_address_2' =>
3097 array('title' => ts('Supplementary Address Field 2'),
3098 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3102 'name' => 'street_number',
3103 'title' => ts('Street Number'),
3105 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3109 'name' => 'street_name',
3110 'title' => ts('Street Name'),
3112 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3116 'name' => 'street_unit',
3117 'title' => ts('Street Unit'),
3119 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3122 array('title' => ts('City'),
3123 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3126 array('title' => ts('Postal Code'),
3127 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3129 'postal_code_suffix' =>
3130 array('title' => ts('Postal Code Suffix'),
3131 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3134 array('title' => ts('County'),
3135 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3137 'state_province_id' =>
3138 array('title' => ts('State/Province'),
3139 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3142 array('title' => ts('Country'),
3143 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3146 'grouping' => 'location-fields',
3151 $addressFields['civicrm_address']['filters'] = array(
3152 'street_number' => array('title' => ts('Street Number'),
3154 'name' => 'street_number',
3156 'street_name' => array('title' => ts('Street Name'),
3157 'name' => 'street_name',
3158 'operator' => 'like',
3160 'postal_code' => array('title' => ts('Postal Code'),
3162 'name' => 'postal_code',
3164 'city' => array('title' => ts('City'),
3165 'operator' => 'like',
3168 'county_id' => array(
3169 'name' => 'county_id',
3170 'title' => ts('County'),
3171 'type' => CRM_Utils_Type
::T_INT
,
3173 CRM_Report_Form
::OP_MULTISELECT
,
3175 CRM_Core_PseudoConstant
::county(),
3177 'state_province_id' => array(
3178 'name' => 'state_province_id',
3179 'title' => ts('State/Province'),
3180 'type' => CRM_Utils_Type
::T_INT
,
3182 CRM_Report_Form
::OP_MULTISELECT
,
3184 CRM_Core_PseudoConstant
::stateProvince(),
3186 'country_id' => array(
3187 'name' => 'country_id',
3188 'title' => ts('Country'),
3189 'type' => CRM_Utils_Type
::T_INT
,
3191 CRM_Report_Form
::OP_MULTISELECT
,
3193 CRM_Core_PseudoConstant
::country(),
3199 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3200 'street_number' => array('title' => 'Odd / Even Street Number'),
3201 'street_address' => NULL,
3203 'postal_code' => NULL,
3208 $addressFields['civicrm_address']['group_bys'] = array(
3209 'street_address' => NULL,
3211 'postal_code' => NULL,
3212 'state_province_id' =>
3213 array('title' => ts('State/Province'),
3216 array('title' => ts('Country'),
3219 array('title' => ts('County'),
3223 return $addressFields;
3227 * Do AlterDisplay processing on Address Fields
3229 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3230 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3231 $entryFound = FALSE;
3233 if (array_key_exists('civicrm_address_country_id', $row)) {
3234 if ($value = $row['civicrm_address_country_id']) {
3235 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3236 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3237 "reset=1&force=1&{$criteriaQueryParams}&" .
3238 "country_id_op=in&country_id_value={$value}",
3239 $this->_absoluteUrl
, $this->_id
3241 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3242 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3249 if (array_key_exists('civicrm_address_county_id', $row)) {
3250 if ($value = $row['civicrm_address_county_id']) {
3251 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3252 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3253 "reset=1&force=1&{$criteriaQueryParams}&" .
3254 "county_id_op=in&county_id_value={$value}",
3255 $this->_absoluteUrl
, $this->_id
3257 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3258 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3264 // handle state province
3265 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3266 if ($value = $row['civicrm_address_state_province_id']) {
3267 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3269 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3270 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3271 $this->_absoluteUrl
, $this->_id
3273 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3274 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3285 * Adjusts dates passed in to YEAR() for fiscal year.
3287 function fiscalYearOffset($fieldName) {
3288 $config = CRM_Core_Config
::singleton();
3289 $fy = $config->fiscalYearStart
;
3290 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3291 return "YEAR( $fieldName )";
3293 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3297 * Add Address into From Table if required
3299 function addAddressFromClause() {
3300 // include address field if address column is to be included
3301 if ((isset($this->_addressField
) &&
3302 $this->_addressField
3304 $this->isTableSelected('civicrm_address')
3307 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3308 ON ({$this->_aliases['civicrm_contact']}.id =
3309 {$this->_aliases['civicrm_address']}.contact_id) AND
3310 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3315 * Add Phone into From Table if required
3317 function addPhoneFromClause() {
3318 // include address field if address column is to be included
3319 if ($this->isTableSelected('civicrm_phone')
3322 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3323 ON ({$this->_aliases['civicrm_contact']}.id =
3324 {$this->_aliases['civicrm_phone']}.contact_id) AND
3325 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3330 * Get phone columns to add to array
3331 * @param array $options
3332 * - prefix Prefix to add to table (in case of more than one instance of the table)
3333 * - prefix_label Label to give columns from this phone table instance
3334 * @return array phone columns definition
3336 function getPhoneColumns($options = array()){
3337 $defaultOptions = array(
3339 'prefix_label' => '',
3342 $options = array_merge($defaultOptions,$options);
3345 $options['prefix'] . 'civicrm_phone' => array(
3346 'dao' => 'CRM_Core_DAO_Phone',
3348 $options['prefix'] . 'phone' => array(
3349 'title' => ts($options['prefix_label'] . 'Phone'),
3359 * Get address columns to add to array
3360 * @param array $options
3361 * - prefix Prefix to add to table (in case of more than one instance of the table)
3362 * - prefix_label Label to give columns from this address table instance
3363 * @return array address columns definition
3365 function getAddressColumns($options = array()){
3366 $defaultOptions = array(
3368 'prefix_label' => '',
3372 'defaults' => array(
3375 $options = array_merge($defaultOptions,$options);
3376 return $this->addAddressFields(
3377 $options['group_by'],
3378 $options['order_by'],
3379 $options['filters'],
3380 $options['defaults']
3385 function add2group($groupID) {
3386 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3387 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3388 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3390 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3391 $dao = CRM_Core_DAO
::executeQuery($sql);
3393 $contact_ids = array();
3394 // Add resulting contacts to group
3395 while ($dao->fetch()) {
3396 if ($dao->addtogroup_contact_id
) {
3397 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3401 if ( !empty($contact_ids) ) {
3402 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3403 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3406 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3411 /* function used for showing charts on print screen */
3412 static function uploadChartImage() {
3413 // upload strictly for '.png' images
3414 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3415 if (preg_match('/\.png$/', $name)) {
3417 // POST data is usually string data, but we are passing a RAW .png
3418 // so PHP is a bit confused and $_POST is empty. But it has saved
3419 // the raw bits into $HTTP_RAW_POST_DATA
3421 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3423 // prepare the directory
3424 $config = CRM_Core_Config
::singleton();
3425 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3426 if (!file_exists($defaultPath)) {
3427 mkdir($defaultPath, 0777, TRUE);
3430 // full path to the saved image including filename
3431 $destination = $defaultPath . $name;
3434 $jfh = fopen($destination, 'w') or die("can't open file");
3435 fwrite($jfh, $httpRawPostData);
3437 CRM_Utils_System
::civiExit();