3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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,
54 * The id of the report instance
61 * The id of the report template
65 protected $_templateID;
73 protected $_noFields = FALSE;
76 * The set of all columns in the report. An associative array
77 * with column name as the key and attribues as the value
81 protected $_columns = array();
84 * The set of filters in the report
88 protected $_filters = array();
91 * The set of optional columns in the report
95 protected $_options = array();
97 protected $_defaults = array();
100 * By default most reports hide contact id.
101 * Setting this to true makes it available
103 protected $_exposeContactID = TRUE;
106 * Set of statistic fields
110 protected $_statFields = array();
113 * Set of statistics data
117 protected $_statistics = array();
120 * List of fields not to be repeated during display
124 protected $_noRepeats = array();
127 * List of fields not to be displayed
131 protected $_noDisplay = array();
134 * Object type that a custom group extends
138 protected $_customGroupExtends = NULL;
139 protected $_customGroupExtendsJoin = array();
140 protected $_customGroupFilters = TRUE;
141 protected $_customGroupGroupBy = FALSE;
142 protected $_customGroupJoin = 'LEFT JOIN';
148 protected $_tagFilter = FALSE;
151 * specify entity table for tags filter
154 protected $_tagFilterTable = 'civicrm_contact';
157 * build groups filter
160 protected $_groupFilter = FALSE;
167 public $_navigation = array();
169 public $_drilldownReport = array();
172 * An attribute for checkbox/radio form field layout
176 protected $_fourColumnAttribute = array(
177 '</td><td width="25%">', '</td><td width="25%">',
178 '</td><td width="25%">', '</tr><tr><td>',
181 protected $_force = 1;
183 protected $_params = NULL;
184 protected $_formValues = NULL;
185 protected $_instanceValues = NULL;
187 protected $_instanceForm = FALSE;
188 protected $_criteriaForm = FALSE;
190 protected $_instanceButtonName = NULL;
191 protected $_createNewButtonName = NULL;
192 protected $_printButtonName = NULL;
193 protected $_pdfButtonName = NULL;
194 protected $_csvButtonName = NULL;
195 protected $_groupButtonName = NULL;
196 protected $_chartButtonName = NULL;
197 protected $_csvSupported = TRUE;
198 protected $_add2groupSupported = TRUE;
199 protected $_groups = NULL;
200 protected $_grandFlag = FALSE;
201 protected $_rowsFound = NULL;
202 protected $_selectAliases = array();
203 protected $_rollup = NULL;
209 protected $_limit = NULL;
212 * This can be set to specify a limit to the number of rows
213 * Since it is currently envisaged as part of the api usage it is only being applied
214 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
215 * of the code (see limit() fn
218 protected $_limitValue = NULL;
221 * This can be set to specify row offset
222 * See notes on _limitValue
225 protected $_offsetValue = NULL;
226 protected $_sections = NULL;
227 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
228 protected $_absoluteUrl = FALSE;
231 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
235 protected $_storeResultSet = FALSE;
238 * When _storeResultSet Flag is set use this var to store result set in form of array
242 protected $_resultSet = array();
245 * To what frequency group-by a date column
249 protected $_groupByDateFreq = array(
251 'YEARWEEK' => 'Week',
252 'QUARTER' => 'Quarter',
257 * Variables to hold the acl inner join and where clause
259 protected $_aclFrom = NULL;
260 protected $_aclWhere = NULL;
263 * Array of DAO tables having columns included in SELECT or ORDER BY clause
267 protected $_selectedTables;
270 * outputmode e.g 'print', 'csv', 'pdf'
273 protected $_outputMode;
275 public $_having = NULL;
276 public $_select = NULL;
277 public $_selectClauses = array();
278 public $_columnHeaders = array();
279 public $_orderBy = NULL;
280 public $_orderByFields = array();
281 public $_orderByArray = array();
282 public $_groupBy = NULL;
283 public $_whereClauses = array();
284 public $_havingClauses = array();
287 * dashBoardRowCount Dashboard row count
290 public $_dashBoardRowCount;
293 * Is this being called without a form controller (ie. the report is being render outside the normal form
294 * - e.g the api is retrieving the rows
297 public $noController = FALSE;
300 * Variable to hold the currency alias
302 protected $_currencyColumn = NULL;
307 function __construct() {
308 parent
::__construct();
311 if ($this->_tagFilter
) {
312 $this->buildTagFilter();
314 if ($this->_exposeContactID
) {
315 if (array_key_exists('civicrm_contact', $this->_columns
)) {
316 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
318 'title' => 'Contact ID',
324 if ($this->_groupFilter
) {
325 $this->buildGroupFilter();
328 // Get all custom groups
329 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
331 // Get the custom groupIds for which the user has VIEW permission
332 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
333 // and addCustomDataToColumns() will allow access to all custom groups.
334 $permCustomGroupIds = array();
335 if (!CRM_Core_Permission
::check('access all custom data')) {
336 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
337 // do not allow custom data for reports if user doesn't have
338 // permission to access custom data.
339 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
340 $this->_customGroupExtends
= array();
344 // merge custom data columns to _columns list, if any
345 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
347 // add / modify display columns, filters ..etc
348 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
350 //assign currencyColumn variable to tpl
351 $this->assign('currencyColumn', $this->_currencyColumn
);
354 function preProcessCommon() {
356 CRM_Utils_Request
::retrieve(
359 CRM_Core_DAO
::$_nullObject
362 $this->_dashBoardRowCount
=
363 CRM_Utils_Request
::retrieve(
366 CRM_Core_DAO
::$_nullObject
369 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
371 $this->assign('section', $this->_section
);
372 CRM_Core_Region
::instance('page-header')->add(array(
373 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
375 if(!$this->noController
) {
376 $this->setID($this->get('instanceId'));
379 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
381 $this->setID( CRM_Report_Utils_Report
::getInstanceIDForPath());
385 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
386 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
387 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
391 $this->assign('instanceId', $this->_id
);
392 $params = array('id' => $this->_id
);
393 $this->_instanceValues
= array();
394 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
396 $this->_instanceValues
398 if (empty($this->_instanceValues
)) {
399 CRM_Core_Error
::fatal("Report could not be loaded.");
401 $this->_title
= $this->_instanceValues
['title'];
402 if (!empty($this->_instanceValues
['permission']) &&
403 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
404 CRM_Core_Permission
::check('administer Reports')
407 CRM_Utils_System
::permissionDenied();
408 CRM_Utils_System
::civiExit();
411 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
413 $this->_formValues
= unserialize($formValues);
416 $this->_formValues
= NULL;
419 // lets always do a force if reset is found in the url.
420 if (!empty($_REQUEST['reset'])) {
425 $this->assign('mode', 'instance');
427 elseif (!$this->noController
) {
428 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
429 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
430 if (($instanceCount > 0) && $optionValueID) {
431 $this->assign('instanceUrl',
432 CRM_Utils_System
::url('civicrm/report/list',
433 "reset=1&ovid=$optionValueID"
437 if ($optionValueID) {
438 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
442 $this->assign('mode', 'template');
445 // lets display the Report Settings section
446 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
448 // Do not display Report Settings section if administer Reports permission is absent OR
449 // if report instance is reserved and administer reserved reports absent
450 if (!CRM_Core_Permission
::check('administer Reports') ||
451 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
452 $this->_instanceForm
= FALSE;
455 $this->assign('criteriaForm', FALSE);
456 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
457 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
458 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
459 $this->assign('criteriaForm', TRUE);
460 $this->_criteriaForm
= TRUE;
464 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
465 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
466 $this->_printButtonName
= $this->getButtonName('submit', 'print');
467 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
468 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
469 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
470 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
473 function addBreadCrumb() {
477 'title' => ts('Report Templates'),
478 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
482 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
485 function preProcess() {
486 $this->preProcessCommon();
489 $this->addBreadCrumb();
492 foreach ($this->_columns
as $tableName => $table) {
494 if (!isset($table['alias'])) {
495 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
498 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
501 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
503 $daoOrBaoName = NULL;
504 // higher preference to bao object
505 if (array_key_exists('bao', $table)) {
506 $daoOrBaoName = $table['bao'];
507 $expFields = $daoOrBaoName::exportableFields( );
509 elseif (array_key_exists('dao', $table)){
510 $daoOrBaoName = $table['dao'];
511 $expFields = $daoOrBaoName::export( );
514 $expFields = array();
517 $doNotCopy = array('required');
519 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
520 foreach ($fieldGroups as $fieldGrp) {
521 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
522 foreach ($table[$fieldGrp] as $fieldName => $field) {
523 // $name is the field name used to reference the BAO/DAO export fields array
524 $name = isset($field['name']) ?
$field['name'] : $fieldName;
526 // Sometimes the field name key in the BAO/DAO export fields array is
527 // different from the actual database field name.
528 // Unset $field['name'] so that actual database field name can be obtained
529 // from the BAO/DAO export fields array.
530 unset($field['name']);
532 if (array_key_exists($name, $expFields)) {
533 foreach ($doNotCopy as $dnc) {
534 // unset the values we don't want to be copied.
535 unset($expFields[$name][$dnc]);
538 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
541 foreach ($expFields[$name] as $property => $val) {
542 if (!array_key_exists($property, $field)) {
543 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
550 if (!empty($field['no_repeat'])) {
551 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
553 if (!empty($field['no_display'])) {
554 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
557 // set alias = table-name, unless already set
558 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
559 $this->_columns
[$tableName]['alias'] : $tableName
561 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
563 // set name = fieldName, unless already set
564 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
565 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
568 // set dbAlias = alias.name, unless already set
569 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
570 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
573 // a few auto fills for filters
574 if ($fieldGrp == 'filters') {
575 // fill operator types
576 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
577 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
578 case CRM_Utils_Type
::T_MONEY
:
579 case CRM_Utils_Type
::T_FLOAT
:
580 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
582 case CRM_Utils_Type
::T_INT
:
583 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
585 case CRM_Utils_Type
::T_DATE
:
586 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
588 case CRM_Utils_Type
::T_BOOLEAN
:
589 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
590 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
591 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
592 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
597 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
598 // with multiple options operator-type is generally multi-select
599 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
600 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
602 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
613 // copy filters to a separate handy variable
614 if (array_key_exists('filters', $table)) {
615 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
618 if (array_key_exists('group_bys', $table)) {
619 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
622 if (array_key_exists('fields', $table)) {
623 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
628 $this->setDefaultValues(FALSE);
631 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
632 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
633 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
634 CRM_Report_Utils_Get
::processChart($this->_defaults
);
637 $this->_formValues
= $this->_defaults
;
638 $this->postProcess();
643 * @param bool $freeze
647 function setDefaultValues($freeze = TRUE) {
648 $freezeGroup = array();
650 // FIXME: generalizing form field naming conventions would reduce
651 // lots of lines below.
652 foreach ($this->_columns
as $tableName => $table) {
653 if (array_key_exists('fields', $table)) {
654 foreach ($table['fields'] as $fieldName => $field) {
655 if (empty($field['no_display'])) {
656 if (isset($field['required'])) {
658 $this->_defaults
['fields'][$fieldName] = 1;
661 // find element object, so that we could use quickform's freeze method
662 // for required elements
663 $obj = $this->getElementFromGroup("fields", $fieldName);
665 $freezeGroup[] = $obj;
669 elseif (isset($field['default'])) {
670 $this->_defaults
['fields'][$fieldName] = $field['default'];
676 if (array_key_exists('group_bys', $table)) {
677 foreach ($table['group_bys'] as $fieldName => $field) {
678 if (isset($field['default'])) {
679 if (!empty($field['frequency'])) {
680 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
682 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
686 if (array_key_exists('filters', $table)) {
687 foreach ($table['filters'] as $fieldName => $field) {
688 if (isset($field['default'])) {
689 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
690 if(is_array($field['default'])){
691 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
692 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
693 $this->_defaults
["{$fieldName}_relative"] = 0;
696 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
700 $this->_defaults
["{$fieldName}_value"] = $field['default'];
703 //assign default value as "in" for multiselect
704 //operator, To freeze the select element
705 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT
) {
706 $this->_defaults
["{$fieldName}_op"] = 'in';
708 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_ENTITYREF
) {
709 $this->_defaults
["{$fieldName}_op"] = 'in';
711 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
) {
712 $this->_defaults
["{$fieldName}_op"] = 'mhas';
714 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
715 $this->_defaults
["{$fieldName}_op"] = $op;
721 array_key_exists('order_bys', $table) &&
722 is_array($table['order_bys'])
724 if (!array_key_exists('order_bys', $this->_defaults
)) {
725 $this->_defaults
['order_bys'] = array();
727 foreach ($table['order_bys'] as $fieldName => $field) {
728 if (!empty($field['default']) ||
!empty($field['default_order']) ||
729 CRM_Utils_Array
::value('default_is_section', $field) ||
!empty($field['default_weight'])) {
731 'column' => $fieldName,
732 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
733 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
736 if (!empty($field['default_weight'])) {
737 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
740 array_unshift($this->_defaults
['order_bys'], $order_by);
746 foreach ($this->_options
as $fieldName => $field) {
747 if (isset($field['default'])) {
748 $this->_defaults
['options'][$fieldName] = $field['default'];
753 if (!empty($this->_submitValues
)) {
754 $this->preProcessOrderBy($this->_submitValues
);
757 $this->preProcessOrderBy($this->_defaults
);
760 // lets finish freezing task here itself
761 if (!empty($freezeGroup)) {
762 foreach ($freezeGroup as $elem) {
767 if ($this->_formValues
) {
768 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
771 if ($this->_instanceValues
) {
772 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
775 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
777 return $this->_defaults
;
782 * @param $grpFieldName
786 function getElementFromGroup($group, $grpFieldName) {
787 $eleObj = $this->getElement($group);
788 foreach ($eleObj->_elements
as $index => $obj) {
789 if ($grpFieldName == $obj->_attributes
['name']) {
797 * Setter for $_params
798 * @param array $params
800 function setParams($params) {
801 $this->_params
= $params;
809 * @internal param int $id
811 function setID($instanceid) {
812 $this->_id
= $instanceid;
818 * @internal param bool $force
820 function setForce($isForce) {
821 $this->_force
= $isForce;
825 * Setter for $_limitValue
826 * @param number $_limitValue
828 function setLimitValue($_limitValue) {
829 $this->_limitValue
= $_limitValue;
833 * Setter for $_offsetValue
834 * @param number $_offsetValue
836 function setOffsetValue($_offsetValue) {
837 $this->_offsetValue
= $_offsetValue;
841 * Getter for $_defaultValues
842 * @return array $_defaultValues
844 function getDefaultValues() {
845 return $this->_defaults
;
848 function addColumns() {
851 foreach ($this->_columns
as $tableName => $table) {
852 if (array_key_exists('fields', $table)) {
853 foreach ($table['fields'] as $fieldName => $field) {
855 if (empty($field['no_display'])) {
856 foreach ( array('table', 'field') as $var) {
857 if (!empty($
{$var}['grouping'])) {
858 if (!is_array($
{$var}['grouping'])) {
859 $tableName = $
{$var}['grouping'];
861 $tableName = array_keys($
{$var}['grouping']);
862 $tableName = $tableName[0];
863 $groupTitle = array_values($
{$var}['grouping']);
864 $groupTitle = $groupTitle[0];
869 if (!$groupTitle && isset($table['group_title'])) {
870 $groupTitle = $table['group_title'];
873 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
874 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
875 $colGroups[$tableName]['group_title'] = $groupTitle;
878 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
884 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
885 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
887 $this->assign('colGroups', $colGroups);
890 function addFilters() {
893 foreach ($this->_filters
as $table => $attributes) {
894 foreach ($attributes as $fieldName => $field) {
895 // get ready with option value pair
896 // @ 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
898 $operations = $this->getOperationPair(
899 CRM_Utils_Array
::value('operatorType', $field),
902 $filters[$table][$fieldName] = $field;
904 switch (CRM_Utils_Array
::value('operatorType', $field)) {
905 case CRM_Report_Form
::OP_MONTH
:
906 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
907 // If there's no option list for this filter, define one.
908 $field['options'] = array(
917 9 => ts('September'),
919 11 => ts('November'),
920 12 => ts('December'),
922 // Add this option list to this column _columns. This is
923 // required so that filter statistics show properly.
924 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
926 case CRM_Report_Form
::OP_MULTISELECT
:
927 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
928 // assume a multi-select field
929 if (!empty($field['options']) ||
$fieldName == 'state_province_id' ||
$fieldName == 'county_id') {
930 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
931 if (count($operations) <= 1) {
934 if ($fieldName == 'state_province_id' ||
$fieldName == 'county_id') {
935 $this->addChainSelect($fieldName . '_value', array('multiple' => TRUE, 'label' => NULL, 'class' => 'huge'));
938 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
939 'style' => 'min-width:250px',
940 'class' => 'crm-select2 huge',
942 'placeholder' => ts('- select -'),
948 case CRM_Report_Form
::OP_SELECT
:
949 // assume a select field
950 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
951 if (!empty($field['options']))
952 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
955 case CRM_Report_Form
::OP_ENTITYREF
:
956 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
957 $this->setEntityRefDefaults($field, $table);
958 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
961 case CRM_Report_Form
::OP_DATE
:
962 // build datetime fields
963 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
967 case CRM_Report_Form
::OP_DATETIME
:
968 // build datetime fields
969 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
973 case CRM_Report_Form
::OP_INT
:
974 case CRM_Report_Form
::OP_FLOAT
:
975 // and a min value input box
976 $this->add('text', "{$fieldName}_min", ts('Min'));
977 // and a max value input box
978 $this->add('text', "{$fieldName}_max", ts('Max'));
980 // default type is string
981 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
982 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
984 // we need text box for value input
985 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
990 $this->assign('filters', $filters);
993 function addOptions() {
994 if (!empty($this->_options
)) {
995 // FIXME: For now lets build all elements as checkboxes.
996 // Once we clear with the format we can build elements based on type
999 foreach ($this->_options
as $fieldName => $field) {
1000 if ($field['type'] == 'select') {
1001 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1003 else if ($field['type'] == 'checkbox') {
1004 $options[$field['title']] = $fieldName;
1005 $this->addCheckBox($fieldName, NULL,
1007 NULL, NULL, NULL, $this->_fourColumnAttribute
1012 $this->assign('otherOptions', $this->_options
);
1015 function addChartOptions() {
1016 if (!empty($this->_charts
)) {
1017 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
1018 $this->assign('charts', $this->_charts
);
1019 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1023 function addGroupBys() {
1024 $options = $freqElements = array();
1026 foreach ($this->_columns
as $tableName => $table) {
1027 if (array_key_exists('group_bys', $table)) {
1028 foreach ($table['group_bys'] as $fieldName => $field) {
1029 if (!empty($field)) {
1030 $options[$field['title']] = $fieldName;
1031 if (!empty($field['frequency'])) {
1032 $freqElements[$field['title']] = $fieldName;
1038 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1039 NULL, NULL, NULL, $this->_fourColumnAttribute
1041 $this->assign('groupByElements', $options);
1043 foreach ($freqElements as $name) {
1044 $this->addElement('select', "group_bys_freq[$name]",
1045 ts('Frequency'), $this->_groupByDateFreq
1050 function addOrderBys() {
1052 foreach ($this->_columns
as $tableName => $table) {
1054 // Report developer may define any column to order by; include these as order-by options
1055 if (array_key_exists('order_bys', $table)) {
1056 foreach ($table['order_bys'] as $fieldName => $field) {
1057 if (!empty($field)) {
1058 $options[$fieldName] = $field['title'];
1063 /* Add searchable custom fields as order-by options, if so requested
1064 * (These are already indexed, so allowing to order on them is cheap.)
1068 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1069 foreach ($table['fields'] as $fieldName => $field) {
1070 if (empty($field['no_display'])) {
1071 $options[$fieldName] = $field['title'];
1079 $this->assign('orderByOptions', $options);
1081 if (!empty($options)) {
1083 '-' => ' - none - ') +
$options;
1084 for ($i = 1; $i <= 5; $i++
) {
1085 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1086 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1087 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1088 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1093 function buildInstanceAndButtons() {
1094 CRM_Report_Form_Instance
::buildForm($this);
1096 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1098 $this->addElement('submit', $this->_instanceButtonName
, $label);
1099 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1100 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1103 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1105 if ($this->_instanceForm
) {
1106 $this->assign('instanceForm', TRUE);
1109 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1110 $this->addElement('submit', $this->_printButtonName
, $label);
1112 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1113 $this->addElement('submit', $this->_pdfButtonName
, $label);
1115 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1117 if ($this->_csvSupported
) {
1118 $this->addElement('submit', $this->_csvButtonName
, $label);
1121 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1122 $this->addElement('select', 'groups', ts('Group'),
1123 array('' => ts('Add Contacts to Group')) + CRM_Core_PseudoConstant
::nestedGroup(),
1124 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1126 $this->assign('group', TRUE);
1129 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1131 $this->addChartOptions();
1132 $this->addButtons(array(
1135 'name' => ts('Preview Report'),
1136 'isDefault' => TRUE,
1142 function buildQuickForm() {
1143 $this->addColumns();
1145 $this->addFilters();
1147 $this->addOptions();
1149 $this->addGroupBys();
1151 $this->addOrderBys();
1153 $this->buildInstanceAndButtons();
1155 //add form rule for report
1156 if (is_callable(array(
1157 $this, 'formRule'))) {
1158 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1162 // a formrule function to ensure that fields selected in group_by
1163 // (if any) should only be the ones present in display/select fields criteria;
1164 // note: works if and only if any custom field selected in group_by.
1167 * @param array $ignoreFields
1171 function customDataFormRule($fields, $ignoreFields = array( )) {
1173 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1174 foreach ($this->_columns
as $tableName => $table) {
1175 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1176 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1177 if (array_key_exists($fieldName, $fields['group_bys']) &&
1178 !array_key_exists($fieldName, $fields['fields'])
1180 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1182 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1183 foreach ($fields['fields'] as $fld => $val) {
1184 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1185 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1196 // Note: $fieldName param allows inheriting class to build operationPairs
1197 // specific to a field.
1199 * @param string $type
1200 * @param null $fieldName
1204 function getOperationPair($type = "string", $fieldName = NULL) {
1205 // FIXME: At some point we should move these key-val pairs
1206 // to option_group and option_value table.
1208 case CRM_Report_Form
::OP_INT
:
1209 case CRM_Report_Form
::OP_FLOAT
:
1211 'lte' => ts('Is less than or equal to'),
1212 'gte' => ts('Is greater than or equal to'),
1213 'bw' => ts('Is between'),
1214 'eq' => ts('Is equal to'),
1215 'lt' => ts('Is less than'),
1216 'gt' => ts('Is greater than'),
1217 'neq' => ts('Is not equal to'),
1218 'nbw' => ts('Is not between'),
1219 'nll' => ts('Is empty (Null)'),
1220 'nnll' => ts('Is not empty (Null)'),
1224 case CRM_Report_Form
::OP_SELECT
:
1226 'eq' => ts('Is equal to'),
1229 case CRM_Report_Form
::OP_MONTH
:
1230 case CRM_Report_Form
::OP_MULTISELECT
:
1231 case CRM_Report_Form
::OP_ENTITYREF
:
1233 'in' => ts('Is one of'),
1234 'notin' => ts('Is not one of'),
1238 case CRM_Report_Form
::OP_DATE
:
1240 'nll' => ts('Is empty (Null)'),
1241 'nnll' => ts('Is not empty (Null)'),
1245 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1246 // use this operator for the values, concatenated with separator. For e.g if
1247 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1249 'mhas' => ts('Is one of'),
1250 'mnot' => ts('Is not one of'),
1256 'has' => ts('Contains'),
1257 'sw' => ts('Starts with'),
1258 'ew' => ts('Ends with'),
1259 'nhas' => ts('Does not contain'),
1260 'eq' => ts('Is equal to'),
1261 'neq' => ts('Is not equal to'),
1262 'nll' => ts('Is empty (Null)'),
1263 'nnll' => ts('Is not empty (Null)'),
1268 function buildTagFilter() {
1269 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1270 if (!empty($contactTags)) {
1271 $this->_columns
['civicrm_tag'] = array(
1272 'dao' => 'CRM_Core_DAO_Tag',
1278 'title' => ts('Tag'),
1280 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1281 'options' => $contactTags,
1289 * Adds group filters to _columns (called from _Constuct
1291 function buildGroupFilter() {
1292 $this->_columns
['civicrm_group']['filters'] = array(
1295 'name' => 'group_id',
1296 'title' => ts('Group'),
1297 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1299 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1302 if (empty($this->_columns
['civicrm_group']['dao'])) {
1303 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1305 if (empty($this->_columns
['civicrm_group']['alias'])) {
1306 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1311 * @param string $operator
1315 function getSQLOperator($operator = "like") {
1316 switch ($operator) {
1349 return 'IS NOT NULL';
1364 * @return null|string
1366 function whereClause(&$field, $op,
1370 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1376 if (($min !== NULL && strlen($min) > 0) ||
1377 ($max !== NULL && strlen($max) > 0)
1379 $min = CRM_Utils_Type
::escape($min, $type);
1380 $max = CRM_Utils_Type
::escape($max, $type);
1384 $clauses[] = "( {$field['dbAlias']} >= $min )";
1387 $clauses[] = "( {$field['dbAlias']} < $min )";
1392 $clauses[] = "( {$field['dbAlias']} <= $max )";
1395 $clauses[] = "( {$field['dbAlias']} > $max )";
1399 if (!empty($clauses)) {
1401 $clause = implode(' AND ', $clauses);
1404 $clause = implode(' OR ', $clauses);
1412 if ($value !== NULL && strlen($value) > 0) {
1413 $value = CRM_Utils_Type
::escape($value, $type);
1414 if (strpos($value, '%') === FALSE) {
1415 $value = "'%{$value}%'";
1418 $value = "'{$value}'";
1420 $sqlOP = $this->getSQLOperator($op);
1421 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1427 if (is_string($value) && strlen($value)) {
1428 $value = explode(',', $value);
1430 if ($value !== NULL && is_array($value) && count($value) > 0) {
1431 $sqlOP = $this->getSQLOperator($op);
1432 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1433 //cycle through selections and esacape values
1434 foreach ($value as $key => $selection) {
1435 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1437 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1440 // for numerical values
1441 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1443 if ($op == 'notin') {
1444 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1447 $clause = "( " . $clause . " )";
1453 // mhas == multiple has
1454 if ($value !== NULL && count($value) > 0) {
1455 $sqlOP = $this->getSQLOperator($op);
1456 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1461 // mnot == multiple is not one of
1462 if ($value !== NULL && count($value) > 0) {
1463 $sqlOP = $this->getSQLOperator($op);
1464 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1470 if ($value !== NULL && strlen($value) > 0) {
1471 $value = CRM_Utils_Type
::escape($value, $type);
1472 if (strpos($value, '%') === FALSE) {
1474 $value = "'{$value}%'";
1477 $value = "'%{$value}'";
1481 $value = "'{$value}'";
1483 $sqlOP = $this->getSQLOperator($op);
1484 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1490 $sqlOP = $this->getSQLOperator($op);
1491 $clause = "( {$field['dbAlias']} $sqlOP )";
1495 if ($value !== NULL && strlen($value) > 0) {
1496 if (isset($field['clause'])) {
1497 // FIXME: we not doing escape here. Better solution is to use two
1498 // different types - data-type and filter-type
1499 $clause = $field['clause'];
1502 $value = CRM_Utils_Type
::escape($value, $type);
1503 $sqlOP = $this->getSQLOperator($op);
1504 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1505 $value = "'{$value}'";
1507 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1513 if (!empty($field['group']) && $clause) {
1514 $clause = $this->whereGroupClause($field, $value, $op);
1516 elseif (!empty($field['tag']) && $clause) {
1517 // not using left join in query because if any contact
1518 // belongs to more than one tag, results duplicate
1520 $clause = $this->whereTagClause($field, $value, $op);
1522 elseif (!empty($field['membership_org']) && $clause) {
1523 $clause = $this->whereMembershipOrgClause($field, $value, $op);
1525 elseif (!empty($field['membership_type']) && $clause) {
1526 $clause = $this->whereMembershipTypeClause($field, $value, $op);
1537 * @param null $fromTime
1538 * @param null $toTime
1540 * @return null|string
1542 function dateClause($fieldName,
1543 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1546 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1547 $sqlOP = $this->getSQLOperator($relative);
1548 return "( {$fieldName} {$sqlOP} )";
1551 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1554 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1555 $clauses[] = "( {$fieldName} >= $from )";
1559 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1560 $clauses[] = "( {$fieldName} <= {$to} )";
1563 if (!empty($clauses)) {
1564 return implode(' AND ', $clauses);
1570 * @todo - could not find any instances where this is called
1571 * @param unknown_type $relative
1572 * @param String $from
1573 * @param String_type $to
1574 * @return string|NULL
1576 function dateDisplay($relative, $from, $to) {
1577 list($from, $to) = $this->getFromTo($relative, $from, $to);
1580 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1583 $clauses[] = 'Past';
1587 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1590 $clauses[] = 'Today';
1593 if (!empty($clauses)) {
1594 return implode(' - ', $clauses);
1604 * @param null $fromtime
1605 * @param null $totime
1609 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1610 if (empty($totime)) {
1613 //FIX ME not working for relative
1615 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1616 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1617 $from = substr($dateRange['from'], 0, 8);
1618 //Take only Date Part, Sometime Time part is also present in 'to'
1619 $to = substr($dateRange['to'], 0, 8);
1621 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1622 $to = CRM_Utils_Date
::processDate($to, $totime);
1623 return array($from, $to);
1629 function alterDisplay(&$rows) {
1630 // custom code to alter rows
1636 function alterCustomDataDisplay(&$rows) {
1637 // custom code to alter rows having custom values
1638 if (empty($this->_customGroupExtends
)) {
1642 $customFieldIds = array();
1643 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1644 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1645 $customFieldIds[$fieldAlias] = $fieldId;
1648 if (empty($customFieldIds)) {
1652 $customFields = $fieldValueMap = array();
1653 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1655 // skip for type date and ContactReference since date format is already handled
1657 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1658 FROM civicrm_custom_field cf
1659 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1660 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1661 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1662 cg.is_active = 1 AND
1663 cf.is_active = 1 AND
1664 cf.is_searchable = 1 AND
1665 cf.data_type NOT IN ('ContactReference', 'Date') AND
1666 cf.id IN (" . implode(",", $customFieldIds) . ")";
1668 $dao = CRM_Core_DAO
::executeQuery($query);
1669 while ($dao->fetch()) {
1670 foreach ($customFieldCols as $key) {
1671 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1673 if ($dao->option_group_id
) {
1674 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1679 $entryFound = FALSE;
1680 foreach ($rows as $rowNum => $row) {
1681 foreach ($row as $tableCol => $val) {
1682 if (array_key_exists($tableCol, $customFields)) {
1683 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1688 // skip looking further in rows, if first row itself doesn't
1689 // have the column we need
1698 * @param $customField
1699 * @param $fieldValueMap
1701 * @return float|string
1703 function formatCustomValues($value, $customField, $fieldValueMap) {
1704 if (CRM_Utils_System
::isNull($value)) {
1708 $htmlType = $customField['html_type'];
1710 switch ($customField['data_type']) {
1712 if ($value == '1') {
1713 $retValue = ts('Yes');
1716 $retValue = ts('No');
1721 $retValue = CRM_Utils_System
::formatWikiURL($value);
1733 if ($htmlType == 'Text') {
1734 $retValue = (float)$value;
1738 if ($htmlType == 'Text') {
1748 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1753 if (in_array($htmlType, array(
1754 'Text', 'TextArea'))) {
1758 case 'StateProvince':
1761 switch ($htmlType) {
1762 case 'Multi-Select Country':
1763 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1764 $customData = array();
1765 foreach ($value as $val) {
1767 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1770 $retValue = implode(', ', $customData);
1773 case 'Select Country':
1774 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1777 case 'Select State/Province':
1778 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1781 case 'Multi-Select State/Province':
1782 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1783 $customData = array();
1784 foreach ($value as $val) {
1786 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1789 $retValue = implode(', ', $customData);
1794 case 'Autocomplete-Select':
1795 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1799 case 'AdvMulti-Select':
1800 case 'Multi-Select':
1801 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1802 $customData = array();
1803 foreach ($value as $val) {
1805 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1808 $retValue = implode(', ', $customData);
1826 function removeDuplicates(&$rows) {
1827 if (empty($this->_noRepeats
)) {
1830 $checkList = array();
1832 foreach ($rows as $key => $list) {
1833 foreach ($list as $colName => $colVal) {
1834 if (array_key_exists($colName, $checkList) &&
1835 $checkList[$colName] == $colVal) {
1836 $rows[$key][$colName] = "";
1838 if (in_array($colName, $this->_noRepeats
)) {
1839 $checkList[$colName] = $colVal;
1848 * @param bool $subtotal
1850 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1851 foreach ($row as $colName => $colVal) {
1852 if (in_array($colName, $fields)) {
1853 $row[$colName] = $row[$colName];
1855 elseif (isset($this->_columnHeaders
[$colName])) {
1857 $row[$colName] = "Subtotal";
1861 unset($row[$colName]);
1872 function grandTotal(&$rows) {
1873 if (!$this->_rollup ||
($this->_rollup
== '') ||
1874 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1878 $lastRow = array_pop($rows);
1880 foreach ($this->_columnHeaders
as $fld => $val) {
1881 if (!in_array($fld, $this->_statFields
)) {
1882 if (!$this->_grandFlag
) {
1883 $lastRow[$fld] = "Grand Total";
1884 $this->_grandFlag
= TRUE;
1887 $lastRow[$fld] = "";
1892 $this->assign('grandStat', $lastRow);
1898 * @param bool $pager
1900 function formatDisplay(&$rows, $pager = TRUE) {
1901 // set pager based on if any limit was applied in the query.
1906 // allow building charts if any
1907 if (!empty($this->_params
['charts']) && !empty($rows)) {
1908 $this->buildChart($rows);
1909 $this->assign('chartEnabled', TRUE);
1910 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1911 $this->assign('chartId', $this->_chartId
);
1914 // unset columns not to be displayed.
1915 foreach ($this->_columnHeaders
as $key => $value) {
1916 if (!empty($value['no_display'])) {
1917 unset($this->_columnHeaders
[$key]);
1921 // unset columns not to be displayed.
1922 if (!empty($rows)) {
1923 foreach ($this->_noDisplay
as $noDisplayField) {
1924 foreach ($rows as $rowNum => $row) {
1925 unset($this->_columnHeaders
[$noDisplayField]);
1930 // build array of section totals
1931 $this->sectionTotals();
1933 // process grand-total row
1934 $this->grandTotal($rows);
1936 // use this method for formatting rows for display purpose.
1937 $this->alterDisplay($rows);
1938 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1940 // use this method for formatting custom rows for display purpose.
1941 $this->alterCustomDataDisplay($rows);
1947 function buildChart(&$rows) {
1948 // override this method for building charts.
1951 // select() method below has been added recently (v3.3), and many of the report templates might
1952 // still be having their own select() method. We should fix them as and when encountered and move
1953 // towards generalizing the select() method below.
1955 $select = $this->_selectAliases
= array();
1957 foreach ($this->_columns
as $tableName => $table) {
1958 if (array_key_exists('fields', $table)) {
1959 foreach ($table['fields'] as $fieldName => $field) {
1960 if ($tableName == 'civicrm_address') {
1961 $this->_addressField
= TRUE;
1963 if ($tableName == 'civicrm_email') {
1964 $this->_emailField
= TRUE;
1966 if ($tableName == 'civicrm_phone') {
1967 $this->_phoneField
= TRUE;
1970 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1972 // 1. In many cases we want select clause to be built in slightly different way
1973 // for a particular field of a particular type.
1974 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1976 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1977 if ($selectClause) {
1978 $select[] = $selectClause;
1982 // include statistics columns only if set
1983 if (!empty($field['statistics'])) {
1984 foreach ($field['statistics'] as $stat => $label) {
1985 $alias = "{$tableName}_{$fieldName}_{$stat}";
1986 switch (strtolower($stat)) {
1989 $select[] = "$stat({$field['dbAlias']}) as $alias";
1990 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1991 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1992 $this->_statFields
[$label] = $alias;
1993 $this->_selectAliases
[] = $alias;
1997 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1998 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1999 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2000 $this->_statFields
[$label] = $alias;
2001 $this->_selectAliases
[] = $alias;
2004 case 'count_distinct':
2005 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2006 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2007 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2008 $this->_statFields
[$label] = $alias;
2009 $this->_selectAliases
[] = $alias;
2013 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2014 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2015 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2016 $this->_statFields
[$label] = $alias;
2017 $this->_selectAliases
[] = $alias;
2023 $alias = "{$tableName}_{$fieldName}";
2024 $select[] = "{$field['dbAlias']} as $alias";
2025 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2026 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2027 $this->_selectAliases
[] = $alias;
2033 // select for group bys
2034 if (array_key_exists('group_bys', $table)) {
2035 foreach ($table['group_bys'] as $fieldName => $field) {
2037 if ($tableName == 'civicrm_address') {
2038 $this->_addressField
= TRUE;
2040 if ($tableName == 'civicrm_email') {
2041 $this->_emailField
= TRUE;
2043 if ($tableName == 'civicrm_phone') {
2044 $this->_phoneField
= TRUE;
2046 // 1. In many cases we want select clause to be built in slightly different way
2047 // for a particular field of a particular type.
2048 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2050 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2051 if ($selectClause) {
2052 $select[] = $selectClause;
2056 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
2057 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2059 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2060 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2061 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2062 $field['title'] = 'Week';
2066 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2067 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2068 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2069 $field['title'] = 'Year';
2073 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2074 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2075 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2076 $field['title'] = 'Month';
2080 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2081 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2082 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2083 $field['title'] = 'Quarter';
2086 // for graphs and charts -
2087 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2088 $this->_interval
= $field['title'];
2089 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
2090 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2091 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2093 // just to make sure these values are transfered to rows.
2094 // since we 'll need them for calculation purpose,
2095 // e.g making subtotals look nicer or graphs
2096 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2097 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2104 $this->_selectClauses
= $select;
2105 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2116 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2121 $this->storeWhereHavingClauseArray();
2123 if (empty($this->_whereClauses
)) {
2124 $this->_where
= "WHERE ( 1 ) ";
2125 $this->_having
= "";
2128 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2131 if ($this->_aclWhere
) {
2132 $this->_where
.= " AND {$this->_aclWhere} ";
2135 if (!empty($this->_havingClauses
)) {
2136 // use this clause to construct group by clause.
2137 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2142 * Store Where clauses into an array - breaking out this step makes
2143 * over-riding more flexible as the clauses can be used in constructing a
2144 * temp table that may not be part of the final where clause or added
2145 * in other functions
2147 function storeWhereHavingClauseArray(){
2148 foreach ($this->_columns
as $tableName => $table) {
2149 if (array_key_exists('filters', $table)) {
2150 foreach ($table['filters'] as $fieldName => $field) {
2151 // respect pseudofield to filter spec so fields can be marked as
2152 // not to be handled here
2153 if(!empty($field['pseudofield'])){
2157 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2158 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2159 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2160 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2161 if (is_array($value) && !empty($value)) {
2162 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2166 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2167 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2168 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2169 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2170 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2171 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2175 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2177 $clause = $this->whereClause($field,
2179 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2180 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2181 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2186 if (!empty($clause)) {
2187 if (!empty($field['having'])) {
2188 $this->_havingClauses
[] = $clause;
2191 $this->_whereClauses
[] = $clause;
2199 function processReportMode() {
2200 $buttonName = $this->controller
->getButtonName();
2202 $output = CRM_Utils_Request
::retrieve(
2205 CRM_Core_DAO
::$_nullObject
2209 CRM_Utils_Request
::retrieve(
2212 CRM_Core_DAO
::$_nullObject
2215 $this->_absoluteUrl
= FALSE;
2217 $this->assign('printOnly', FALSE);
2219 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2220 $this->assign('printOnly', TRUE);
2222 $this->assign('outputMode', 'print');
2223 $this->_outputMode
= 'print';
2224 if ($this->_sendmail
) {
2225 $this->_absoluteUrl
= TRUE;
2228 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2229 $this->assign('printOnly', TRUE);
2231 $this->assign('outputMode', 'pdf');
2232 $this->_outputMode
= 'pdf';
2233 $this->_absoluteUrl
= TRUE;
2235 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2236 $this->assign('printOnly', TRUE);
2238 $this->assign('outputMode', 'csv');
2239 $this->_outputMode
= 'csv';
2240 $this->_absoluteUrl
= TRUE;
2242 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2243 $this->assign('outputMode', 'group');
2244 $this->_outputMode
= 'group';
2246 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2247 $this->assign('outputMode', 'create_report');
2248 $this->_outputMode
= 'create_report';
2251 $this->assign('outputMode', 'html');
2252 $this->_outputMode
= 'html';
2255 // Get today's date to include in printed reports
2257 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2258 $this->assign('reportDate', $reportDate);
2263 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2265 function beginPostProcess() {
2266 $this->setParams($this->controller
->exportValues($this->_name
));
2268 if (empty($this->_params
) &&
2271 $this->setParams($this->_formValues
);
2274 // hack to fix params when submitted from dashboard, CRM-8532
2275 // fields array is missing because form building etc is skipped
2276 // in dashboard mode for report
2277 //@todo - this could be done in the dashboard no we have a setter
2278 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2279 $this->setParams($this->_formValues
);
2282 $this->_formValues
= $this->_params
;
2283 if (CRM_Core_Permission
::check('administer Reports') &&
2284 isset($this->_id
) &&
2285 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2286 $this->_chartButtonName
== $this->controller
->getButtonName()
2289 $this->assign('updateReportButton', TRUE);
2291 $this->processReportMode();
2292 $this->beginPostProcessCommon();
2296 * beginPostProcess function run in both report mode and non-report mode (api)
2298 function beginPostProcessCommon() {
2303 * @param bool $applyLimit
2307 function buildQuery($applyLimit = TRUE) {
2310 $this->customDataFrom();
2315 // order_by columns not selected for display need to be included in SELECT
2316 $unselectedSectionColumns = $this->unselectedSectionColumns();
2317 foreach ($unselectedSectionColumns as $alias => $section) {
2318 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2321 if ($applyLimit && empty($this->_params
['charts'])) {
2324 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2326 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2330 function groupBy() {
2331 $groupBys = array();
2332 if (!empty($this->_params
['group_bys']) &&
2333 is_array($this->_params
['group_bys']) &&
2334 !empty($this->_params
['group_bys'])
2336 foreach ($this->_columns
as $tableName => $table) {
2337 if (array_key_exists('group_bys', $table)) {
2338 foreach ($table['group_bys'] as $fieldName => $field) {
2339 if (!empty($this->_params
['group_bys'][$fieldName])) {
2340 $groupBys[] = $field['dbAlias'];
2347 if (!empty($groupBys)) {
2348 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2352 function orderBy() {
2353 $this->_orderBy
= "";
2354 $this->_sections
= array();
2355 $this->storeOrderByArray();
2356 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2357 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2359 $this->assign('sections', $this->_sections
);
2363 * In some cases other functions want to know which fields are selected for ordering by
2364 * Separating this into a separate function allows it to be called separately from constructing
2365 * the order by clause
2367 function storeOrderByArray() {
2368 $orderBys = array();
2370 if (!empty($this->_params
['order_bys']) &&
2371 is_array($this->_params
['order_bys']) &&
2372 !empty($this->_params
['order_bys'])
2375 // Proces order_bys in user-specified order
2376 foreach ($this->_params
['order_bys'] as $orderBy) {
2377 $orderByField = array();
2378 foreach ($this->_columns
as $tableName => $table) {
2379 if (array_key_exists('order_bys', $table)) {
2380 // For DAO columns defined in $this->_columns
2381 $fields = $table['order_bys'];
2383 elseif (array_key_exists('extends', $table)) {
2384 // For custom fields referenced in $this->_customGroupExtends
2385 $fields = CRM_Utils_Array
::value('fields', $table, array());
2387 if (!empty($fields) && is_array($fields)) {
2388 foreach ($fields as $fieldName => $field) {
2389 if ($fieldName == $orderBy['column']) {
2390 $orderByField = array_merge($field, $orderBy);
2391 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2398 if (!empty($orderByField)) {
2399 $this->_orderByFields
[] = $orderByField;
2400 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2402 // Record any section headers for assignment to the template
2403 if (!empty($orderBy['section'])) {
2404 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2405 $this->_sections
[$orderByField['tplField']] = $orderByField;
2411 $this->_orderByArray
= $orderBys;
2413 $this->assign('sections', $this->_sections
);
2419 function unselectedSectionColumns() {
2420 $selectColumns = array();
2421 foreach ($this->_columns
as $tableName => $table) {
2422 if (array_key_exists('fields', $table)) {
2423 foreach ($table['fields'] as $fieldName => $field) {
2424 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2426 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2432 if (is_array($this->_sections
)) {
2433 return array_diff_key($this->_sections
, $selectColumns);
2444 function buildRows($sql, &$rows) {
2445 $dao = CRM_Core_DAO
::executeQuery($sql);
2446 if (!is_array($rows)) {
2450 // use this method to modify $this->_columnHeaders
2451 $this->modifyColumnHeaders();
2453 $unselectedSectionColumns = $this->unselectedSectionColumns();
2455 while ($dao->fetch()) {
2457 foreach ($this->_columnHeaders
as $key => $value) {
2458 if (property_exists($dao, $key)) {
2459 $row[$key] = $dao->$key;
2463 // section headers not selected for display need to be added to row
2464 foreach ($unselectedSectionColumns as $key => $values) {
2465 if (property_exists($dao, $key)) {
2466 $row[$key] = $dao->$key;
2475 * When "order by" fields are marked as sections, this assigns to the template
2476 * an array of total counts for each section. This data is used by the Smarty
2477 * plugin {sectionTotal}
2479 function sectionTotals() {
2481 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2482 if (empty($this->_selectAliases
)) {
2486 if (!empty($this->_sections
)) {
2487 // build the query with no LIMIT clause
2488 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2489 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2491 // pull section aliases out of $this->_sections
2492 $sectionAliases = array_keys($this->_sections
);
2495 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2496 $ifnulls[] = "ifnull($alias, '') as $alias";
2499 /* Group (un-limited) report by all aliases and get counts. This might
2500 * be done more efficiently when the contents of $sql are known, ie. by
2501 * overriding this method in the report class.
2505 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2507 // initialize array of total counts
2509 $dao = CRM_Core_DAO
::executeQuery($query);
2510 while ($dao->fetch()) {
2512 // let $this->_alterDisplay translate any integer ids to human-readable values.
2513 $rows[0] = $dao->toArray();
2514 $this->alterDisplay($rows);
2517 // add totals for all permutations of section values
2520 $aliasCount = count($sectionAliases);
2521 foreach ($sectionAliases as $alias) {
2522 $values[] = $row[$alias];
2523 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2524 if ($i == $aliasCount) {
2525 // the last alias is the lowest-level section header; use count as-is
2526 $totals[$key] = $dao->ct
;
2529 // other aliases are higher level; roll count into their total
2530 $totals[$key] +
= $dao->ct
;
2534 $this->assign('sectionTotals', $totals);
2538 function modifyColumnHeaders() {
2539 // use this method to modify $this->_columnHeaders
2545 function doTemplateAssignment(&$rows) {
2546 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2547 $this->assign_by_ref('rows', $rows);
2548 $this->assign('statistics', $this->statistics($rows));
2551 // override this method to build your own statistics
2557 function statistics(&$rows) {
2558 $statistics = array();
2560 $count = count($rows);
2562 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2566 $this->countStat($statistics, $count);
2568 $this->groupByStat($statistics);
2570 $this->filterStat($statistics);
2576 * @param $statistics
2579 function countStat(&$statistics, $count) {
2580 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2584 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2585 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2586 'value' => $this->_rowsFound
,
2592 * @param $statistics
2594 function groupByStat(&$statistics) {
2595 if (!empty($this->_params
['group_bys']) &&
2596 is_array($this->_params
['group_bys']) &&
2597 !empty($this->_params
['group_bys'])
2599 foreach ($this->_columns
as $tableName => $table) {
2600 if (array_key_exists('group_bys', $table)) {
2601 foreach ($table['group_bys'] as $fieldName => $field) {
2602 if (!empty($this->_params
['group_bys'][$fieldName])) {
2603 $combinations[] = $field['title'];
2608 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2609 'value' => implode(' & ', $combinations),
2615 * @param $statistics
2617 function filterStat(&$statistics) {
2618 foreach ($this->_columns
as $tableName => $table) {
2619 if (array_key_exists('filters', $table)) {
2620 foreach ($table['filters'] as $fieldName => $field) {
2621 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2624 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2625 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2626 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2627 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2628 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2630 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2631 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2633 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2634 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2637 $statistics['filters'][] = array(
2638 'title' => $field['title'],
2639 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2642 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2643 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2645 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2646 $statistics['filters'][] = array(
2647 'title' => $field['title'],
2648 'value' => $pair[$rel],
2653 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2656 $pair = $this->getOperationPair(
2657 CRM_Utils_Array
::value('operatorType', $field),
2660 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2661 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2662 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2663 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
2664 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2666 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
2667 $this->setEntityRefDefaults($field, $tableName);
2668 $result = civicrm_api3($field['attributes']['entity'], 'getlist', array('id' => $val) + CRM_Utils_Array
::value('api', $field['attributes'], array()));
2670 foreach ($result['values'] as $v) {
2671 $values[] = $v['label'];
2673 $value = "{$pair[$op]} " . implode(', ', $values);
2675 elseif ($op == 'nll' ||
$op == 'nnll') {
2676 $value = $pair[$op];
2678 elseif (is_array($val) && (!empty($val))) {
2679 $options = CRM_Utils_Array
::value('options', $field, array());
2680 foreach ($val as $key => $valIds) {
2681 if (isset($options[$valIds])) {
2682 $val[$key] = $options[$valIds];
2685 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2686 $val = implode(', ', $val);
2687 $value = "{$pair[$op]} " . $val;
2689 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2690 is_array($field['options']) && !empty($field['options'])
2692 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2695 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2699 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2712 function endPostProcess(&$rows = NULL) {
2713 if ( $this->_storeResultSet
) {
2714 $this->_resultSet
= $rows;
2717 if ($this->_outputMode
== 'print' ||
2718 $this->_outputMode
== 'pdf' ||
2722 $content = $this->compileContent();
2723 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2727 if ($this->_sendmail
) {
2728 $config = CRM_Core_Config
::singleton();
2729 $attachments = array();
2731 if ($this->_outputMode
== 'csv') {
2732 $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'];
2734 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2735 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2736 file_put_contents($csvFullFilename, $csvContent);
2737 $attachments[] = array(
2738 'fullPath' => $csvFullFilename,
2739 'mime_type' => 'text/csv',
2740 'cleanName' => 'CiviReport.csv',
2743 if ($this->_outputMode
== 'pdf') {
2744 // generate PDF content
2745 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2746 file_put_contents($pdfFullFilename,
2747 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2748 TRUE, array('orientation' => 'landscape')
2751 // generate Email Content
2752 $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'];
2754 $attachments[] = array(
2755 'fullPath' => $pdfFullFilename,
2756 'mime_type' => 'application/pdf',
2757 'cleanName' => 'CiviReport.pdf',
2761 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2762 $this->_outputMode
, $attachments
2764 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2767 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2771 elseif ($this->_outputMode
== 'print') {
2775 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2776 $config = CRM_Core_Config
::singleton();
2777 //get chart image name
2778 $chartImg = $this->_chartId
. '.png';
2779 //get image url path
2780 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2781 $uploadUrl .= $chartImg;
2782 //get image doc path to overwrite
2783 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2785 $chart = imagecreatefrompng($uploadUrl);
2786 //convert it into formattd png
2787 header('Content-type: image/png');
2788 //overwrite with same image
2789 imagepng($chart, $uploadImg);
2791 imagedestroy($chart);
2793 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2795 CRM_Utils_System
::civiExit();
2797 elseif ($this->_outputMode
== 'csv') {
2798 CRM_Report_Utils_Report
::export2csv($this, $rows);
2800 elseif ($this->_outputMode
== 'group') {
2801 $group = $this->_params
['groups'];
2802 $this->add2group($group);
2804 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2805 CRM_Report_Form_Instance
::postProcess($this);
2807 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2808 $this->_outputMode
== 'create_report' ) {
2809 $this->_createNew
= TRUE;
2810 CRM_Report_Form_Instance
::postProcess($this);
2814 function storeResultSet() {
2815 $this->_storeResultSet
= TRUE;
2821 function getResultSet() {
2822 return $this->_resultSet
;
2826 * Get Template file name - use default form template if a specific one has not been set up for this report
2830 * Use the form name to create the tpl file name
2838 function getTemplateFileName(){
2839 $defaultTpl = parent
::getTemplateFileName();
2840 $template = CRM_Core_Smarty
::singleton();
2841 if (!$template->template_exists($defaultTpl)) {
2842 $defaultTpl = 'CRM/Report/Form.tpl';
2848 * Compile the report content
2850 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2855 function compileContent(){
2856 $templateFile = $this->getHookedTemplateFileName();
2857 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2861 function postProcess() {
2862 // get ready with post process params
2863 $this->beginPostProcess();
2866 $sql = $this->buildQuery();
2868 // build array of result based on column headers. This method also allows
2869 // modifying column headers before using it to build result set i.e $rows.
2871 $this->buildRows($sql, $rows);
2873 // format result set.
2874 $this->formatDisplay($rows);
2876 // assign variables to templates
2877 $this->doTemplateAssignment($rows);
2879 // do print / pdf / instance stuff if needed
2880 $this->endPostProcess($rows);
2884 * @param int $rowCount
2886 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2887 // lets do the pager if in html mode
2888 $this->_limit
= NULL;
2890 // CRM-14115, over-ride row count if rowCount is specified in URL
2891 if ($this->_dashBoardRowCount
) {
2892 $rowCount = $this->_dashBoardRowCount
;
2894 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2895 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2897 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2899 if (!$pageId && !empty($_POST)) {
2900 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2901 $pageId = max((int)@$_POST['crmPID_B'], 1);
2903 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2904 $pageId = max((int)@$_POST['crmPID'], 1);
2906 unset($_POST['crmPID_B'], $_POST['crmPID']);
2909 $pageId = $pageId ?
$pageId : 1;
2910 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2911 $offset = ($pageId - 1) * $rowCount;
2913 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2914 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2916 $this->_limit
= " LIMIT $offset, $rowCount";
2917 return array($offset, $rowCount);
2919 if($this->_limitValue
) {
2920 if($this->_offsetValue
) {
2921 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2924 $this->_limit
= " LIMIT " . $this->_limitValue
;
2930 * @param int $rowCount
2932 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2934 // CRM-14115, over-ride row count if rowCount is specified in URL
2935 if ($this->_dashBoardRowCount
) {
2936 $rowCount = $this->_dashBoardRowCount
;
2939 if ($this->_limit
&& ($this->_limit
!= '')) {
2940 $sql = "SELECT FOUND_ROWS();";
2941 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2943 'total' => $this->_rowsFound
,
2944 'rowCount' => $rowCount,
2945 'status' => ts('Records') . ' %%StatusMessage%%',
2946 'buttonBottom' => 'PagerBottomButton',
2947 'buttonTop' => 'PagerTopButton',
2948 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2951 $pager = new CRM_Utils_Pager($params);
2952 $this->assign_by_ref('pager', $pager);
2953 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2964 function whereGroupClause($field, $value, $op) {
2966 $smartGroupQuery = "";
2968 $group = new CRM_Contact_DAO_Group();
2969 $group->is_active
= 1;
2971 $smartGroups = array();
2972 while ($group->fetch()) {
2973 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2974 $smartGroups[] = $group->id
;
2978 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2980 $smartGroupQuery = '';
2981 if (!empty($smartGroups)) {
2982 $smartGroups = implode(',', $smartGroups);
2983 $smartGroupQuery = " UNION DISTINCT
2984 SELECT DISTINCT smartgroup_contact.contact_id
2985 FROM civicrm_group_contact_cache smartgroup_contact
2986 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2989 $sqlOp = $this->getSQLOperator($op);
2990 if (!is_array($value)) {
2991 $value = array($value);
2993 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2995 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2996 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2997 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2998 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2999 {$smartGroupQuery} ) ";
3009 function whereTagClause($field, $value, $op) {
3010 // not using left join in query because if any contact
3011 // belongs to more than one tag, results duplicate
3013 $sqlOp = $this->getSQLOperator($op);
3014 if (!is_array($value)) {
3015 $value = array($value);
3017 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3018 $entity_table = $this->_tagFilterTable
;
3019 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3020 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3021 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3022 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3025 function whereMembershipOrgClause($field, $value, $op) {
3026 $sqlOp = $this->getSQLOperator($op);
3027 if (!is_array($value)) {
3028 $value = array($value);
3031 $tmp_membership_org_sql_list = implode(', ', $value);
3032 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3033 SELECT DISTINCT mem.contact_id
3034 FROM civicrm_membership mem
3035 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3036 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3037 WHERE mt.member_of_contact_id IN (".$tmp_membership_org_sql_list.")
3038 AND mt.is_active = '1'
3039 AND mem_status.is_current_member = '1'
3040 AND mem_status.is_active = '1' ) ";
3043 function whereMembershipTypeClause($field, $value, $op) {
3044 $sqlOp = $this->getSQLOperator($op);
3045 if (!is_array($value)) {
3046 $value = array($value);
3049 $tmp_membership_sql_list = implode(', ', $value);
3050 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3051 SELECT DISTINCT mem.contact_id
3052 FROM civicrm_membership mem
3053 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3054 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3055 WHERE mem.membership_type_id IN (".$tmp_membership_sql_list.")
3056 AND mt.is_active = '1'
3057 AND mem_status.is_current_member = '1'
3058 AND mem_status.is_active = '1' ) ";
3062 * @param string $tableAlias
3064 function buildACLClause($tableAlias = 'contact_a') {
3065 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3069 * @param bool $addFields
3070 * @param array $permCustomGroupIds
3072 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3073 if (empty($this->_customGroupExtends
)) {
3076 if (!is_array($this->_customGroupExtends
)) {
3077 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3079 $customGroupWhere = '';
3080 if (!empty($permCustomGroupIds)) {
3081 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
3084 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3085 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3086 FROM civicrm_custom_group cg
3087 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3088 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3090 cg.is_active = 1 AND
3091 cf.is_active = 1 AND
3092 cf.is_searchable = 1
3093 ORDER BY cg.weight, cf.weight";
3094 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3097 while ($customDAO->fetch()) {
3098 if ($customDAO->table_name
!= $curTable) {
3099 $curTable = $customDAO->table_name
;
3100 $curFields = $curFilters = array();
3103 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3104 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3105 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3106 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3109 'fields', 'filters', 'group_bys') as $colKey) {
3110 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3111 $this->_columns
[$curTable][$colKey] = array();
3115 $fieldName = 'custom_' . $customDAO->cf_id
;
3118 // this makes aliasing work in favor
3119 $curFields[$fieldName] = array(
3120 'name' => $customDAO->column_name
,
3121 'title' => $customDAO->label
,
3122 'dataType' => $customDAO->data_type
,
3123 'htmlType' => $customDAO->html_type
,
3126 if ($this->_customGroupFilters
) {
3127 // this makes aliasing work in favor
3128 $curFilters[$fieldName] = array(
3129 'name' => $customDAO->column_name
,
3130 'title' => $customDAO->label
,
3131 'dataType' => $customDAO->data_type
,
3132 'htmlType' => $customDAO->html_type
,
3136 switch ($customDAO->data_type
) {
3139 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3140 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3141 // CRM-6946, show time part for datetime date fields
3142 if ($customDAO->time_format
) {
3143 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3148 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3149 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
3153 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3157 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3158 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3162 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3163 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3167 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3168 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3172 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3174 if (!empty($customDAO->option_group_id
)) {
3175 if (in_array($customDAO->html_type
, array(
3176 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
3177 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3180 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3182 if ($this->_customGroupFilters
) {
3183 $curFilters[$fieldName]['options'] = array();
3184 $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')));
3185 while ($ogDAO->fetch()) {
3186 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3192 case 'StateProvince':
3193 if (in_array($customDAO->html_type
, array(
3194 'Multi-Select State/Province'))) {
3195 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3198 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3200 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3204 if (in_array($customDAO->html_type
, array(
3205 'Multi-Select Country'))) {
3206 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3209 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3211 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3214 case 'ContactReference':
3215 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3216 $curFilters[$fieldName]['name'] = 'display_name';
3217 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3219 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3220 $curFields[$fieldName]['name'] = 'display_name';
3221 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3225 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3226 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3229 if (!array_key_exists('type', $curFields[$fieldName])) {
3230 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3234 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3236 if ($this->_customGroupFilters
) {
3237 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3239 if ($this->_customGroupGroupBy
) {
3240 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3245 function customDataFrom() {
3246 if (empty($this->_customGroupExtends
)) {
3249 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3251 foreach ($this->_columns
as $table => $prop) {
3252 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
3253 $extendsTable = $mapper[$prop['extends']];
3255 // check field is in params
3256 if (!$this->isFieldSelected($prop)) {
3259 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3261 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3263 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3264 // handle for ContactReference
3265 if (array_key_exists('fields', $prop)) {
3266 foreach ($prop['fields'] as $fieldName => $field) {
3267 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
3268 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3270 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3283 function isFieldSelected($prop) {
3288 if (!empty($this->_params
['fields'])) {
3289 foreach (array_keys($prop['fields']) as $fieldAlias) {
3290 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3291 if ($customFieldId) {
3292 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3296 //might be survey response field.
3297 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3304 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3305 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3306 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3312 if (!empty($this->_params
['order_bys'])) {
3313 foreach (array_keys($prop['fields']) as $fieldAlias) {
3314 foreach ($this->_params
['order_bys'] as $orderBy) {
3315 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3322 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3323 foreach ($prop['filters'] as $fieldAlias => $val) {
3325 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3326 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3327 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3328 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3334 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3335 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3346 * Check for empty order_by configurations and remove them; also set
3347 * template to hide them.
3349 function preProcessOrderBy(&$formValues) {
3350 // Object to show/hide form elements
3351 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3353 $_showHide->addShow('optionField_1');
3355 // Cycle through order_by options; skip any empty ones, and hide them as well
3358 if (!empty($formValues['order_bys'])) {
3359 foreach ($formValues['order_bys'] as $order_by) {
3360 if ($order_by['column'] && $order_by['column'] != '-') {
3361 $_showHide->addShow('optionField_' . $n);
3362 $orderBys[$n] = $order_by;
3367 for ($i = $n; $i <= 5; $i++
) {
3369 $_showHide->addHide('optionField_' . $i);
3373 // overwrite order_by options with modified values
3374 if (!empty($orderBys)) {
3375 $formValues['order_bys'] = $orderBys;
3378 $formValues['order_bys'] = array(1 => array('column' => '-'));
3381 // assign show/hide data to template
3382 $_showHide->addToTemplate();
3386 * Does table name have columns in SELECT clause?
3388 * @param string $tableName Name of table (index of $this->_columns array)
3392 function isTableSelected($tableName) {
3393 return in_array($tableName, $this->selectedTables());
3397 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3398 * (building the array if it's unset)
3400 * @return Array $this->_selectedTables
3402 function selectedTables() {
3403 if (!$this->_selectedTables
) {
3404 $orderByColumns = array();
3405 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3406 foreach ($this->_params
['order_bys'] as $orderBy) {
3407 $orderByColumns[] = $orderBy['column'];
3411 foreach ($this->_columns
as $tableName => $table) {
3412 if (array_key_exists('fields', $table)) {
3413 foreach ($table['fields'] as $fieldName => $field) {
3414 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3415 $this->_selectedTables
[] = $tableName;
3420 if (array_key_exists('order_bys', $table)) {
3421 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3422 if (in_array($orderByName, $orderByColumns)) {
3423 $this->_selectedTables
[] = $tableName;
3428 if (array_key_exists('filters', $table)) {
3429 foreach ($table['filters'] as $filterName => $filter) {
3430 if (!empty($this->_params
["{$filterName}_value"]) ||
3431 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3432 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3434 $this->_selectedTables
[] = $tableName;
3441 return $this->_selectedTables
;
3445 * @deprecated - use getAddressColumns which is a more accurate description
3446 * and also accepts an array of options rather than a long list
3448 * function for adding address fields to construct function in reports
3450 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3451 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3452 * @param bool $filters
3453 * @param array $defaults
3455 * @return array address fields for construct clause
3457 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3458 $addressFields = array(
3459 'civicrm_address' =>
3461 'dao' => 'CRM_Core_DAO_Address',
3465 array('title' => ts('Address Name'),
3466 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3469 array('title' => ts('Street Address'),
3470 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3472 'supplemental_address_1' =>
3473 array('title' => ts('Supplementary Address Field 1'),
3474 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3476 'supplemental_address_2' =>
3477 array('title' => ts('Supplementary Address Field 2'),
3478 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3482 'name' => 'street_number',
3483 'title' => ts('Street Number'),
3485 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3489 'name' => 'street_name',
3490 'title' => ts('Street Name'),
3492 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3496 'name' => 'street_unit',
3497 'title' => ts('Street Unit'),
3499 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3502 array('title' => ts('City'),
3503 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3506 array('title' => ts('Postal Code'),
3507 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3509 'postal_code_suffix' =>
3510 array('title' => ts('Postal Code Suffix'),
3511 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3514 array('title' => ts('Country'),
3515 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3517 'state_province_id' =>
3518 array('title' => ts('State/Province'),
3519 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3522 array('title' => ts('County'),
3523 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3526 'grouping' => 'location-fields',
3531 $addressFields['civicrm_address']['filters'] = array(
3532 'street_number' => array('title' => ts('Street Number'),
3534 'name' => 'street_number',
3536 'street_name' => array('title' => ts('Street Name'),
3537 'name' => 'street_name',
3538 'operator' => 'like',
3540 'postal_code' => array('title' => ts('Postal Code'),
3542 'name' => 'postal_code',
3544 'city' => array('title' => ts('City'),
3545 'operator' => 'like',
3548 'country_id' => array(
3549 'name' => 'country_id',
3550 'title' => ts('Country'),
3551 'type' => CRM_Utils_Type
::T_INT
,
3553 CRM_Report_Form
::OP_MULTISELECT
,
3554 'options' => CRM_Core_PseudoConstant
::country(),
3556 'state_province_id' => array(
3557 'name' => 'state_province_id',
3558 'title' => ts('State/Province'),
3559 'type' => CRM_Utils_Type
::T_INT
,
3560 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3561 'options' => array(),
3563 'county_id' => array(
3564 'name' => 'county_id',
3565 'title' => ts('County'),
3566 'type' => CRM_Utils_Type
::T_INT
,
3567 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3568 'options' => array(),
3574 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3575 'street_number' => array('title' => 'Odd / Even Street Number'),
3576 'street_address' => NULL,
3578 'postal_code' => NULL,
3583 $addressFields['civicrm_address']['group_bys'] = array(
3584 'street_address' => NULL,
3586 'postal_code' => NULL,
3587 'state_province_id' =>
3588 array('title' => ts('State/Province'),
3591 array('title' => ts('Country'),
3594 array('title' => ts('County'),
3598 return $addressFields;
3602 * Do AlterDisplay processing on Address Fields
3613 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3614 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3615 $entryFound = FALSE;
3617 if (array_key_exists('civicrm_address_country_id', $row)) {
3618 if ($value = $row['civicrm_address_country_id']) {
3619 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3620 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3621 "reset=1&force=1&{$criteriaQueryParams}&" .
3622 "country_id_op=in&country_id_value={$value}",
3623 $this->_absoluteUrl
, $this->_id
3625 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3626 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3633 if (array_key_exists('civicrm_address_county_id', $row)) {
3634 if ($value = $row['civicrm_address_county_id']) {
3635 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3636 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3637 "reset=1&force=1&{$criteriaQueryParams}&" .
3638 "county_id_op=in&county_id_value={$value}",
3639 $this->_absoluteUrl
, $this->_id
3641 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3642 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3648 // handle state province
3649 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3650 if ($value = $row['civicrm_address_state_province_id']) {
3651 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3653 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3654 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3655 $this->_absoluteUrl
, $this->_id
3657 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3658 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3669 * Adjusts dates passed in to YEAR() for fiscal year.
3676 function fiscalYearOffset($fieldName) {
3677 $config = CRM_Core_Config
::singleton();
3678 $fy = $config->fiscalYearStart
;
3679 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3680 return "YEAR( $fieldName )";
3682 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3686 * Add Address into From Table if required
3688 function addAddressFromClause() {
3689 // include address field if address column is to be included
3690 if ((isset($this->_addressField
) &&
3691 $this->_addressField
3693 $this->isTableSelected('civicrm_address')
3696 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3697 ON ({$this->_aliases['civicrm_contact']}.id =
3698 {$this->_aliases['civicrm_address']}.contact_id) AND
3699 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3704 * Add Phone into From Table if required
3706 function addPhoneFromClause() {
3707 // include address field if address column is to be included
3708 if ($this->isTableSelected('civicrm_phone')
3711 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3712 ON ({$this->_aliases['civicrm_contact']}.id =
3713 {$this->_aliases['civicrm_phone']}.contact_id) AND
3714 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3719 * Get phone columns to add to array
3720 * @param array $options
3721 * - prefix Prefix to add to table (in case of more than one instance of the table)
3722 * - prefix_label Label to give columns from this phone table instance
3723 * @return array phone columns definition
3725 function getPhoneColumns($options = array()){
3726 $defaultOptions = array(
3728 'prefix_label' => '',
3731 $options = array_merge($defaultOptions,$options);
3734 $options['prefix'] . 'civicrm_phone' => array(
3735 'dao' => 'CRM_Core_DAO_Phone',
3737 $options['prefix'] . 'phone' => array(
3738 'title' => ts($options['prefix_label'] . 'Phone'),
3748 * Get address columns to add to array
3749 * @param array $options
3750 * - prefix Prefix to add to table (in case of more than one instance of the table)
3751 * - prefix_label Label to give columns from this address table instance
3752 * @return array address columns definition
3754 function getAddressColumns($options = array()) {
3757 'prefix_label' => '',
3761 'defaults' => array(),
3763 return $this->addAddressFields(
3764 $options['group_by'],
3765 $options['order_by'],
3766 $options['filters'],
3767 $options['defaults']
3774 function add2group($groupID) {
3775 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3776 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3777 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3779 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3780 $dao = CRM_Core_DAO
::executeQuery($sql);
3782 $contact_ids = array();
3783 // Add resulting contacts to group
3784 while ($dao->fetch()) {
3785 if ($dao->addtogroup_contact_id
) {
3786 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3790 if ( !empty($contact_ids) ) {
3791 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3792 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3795 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3800 /* function used for showing charts on print screen */
3801 static function uploadChartImage() {
3802 // upload strictly for '.png' images
3803 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3804 if (preg_match('/\.png$/', $name)) {
3806 // POST data is usually string data, but we are passing a RAW .png
3807 // so PHP is a bit confused and $_POST is empty. But it has saved
3808 // the raw bits into $HTTP_RAW_POST_DATA
3810 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3812 // prepare the directory
3813 $config = CRM_Core_Config
::singleton();
3814 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3815 if (!file_exists($defaultPath)) {
3816 mkdir($defaultPath, 0777, TRUE);
3819 // full path to the saved image including filename
3820 $destination = $defaultPath . $name;
3823 $jfh = fopen($destination, 'w') or die("can't open file");
3824 fwrite($jfh, $httpRawPostData);
3826 CRM_Utils_System
::civiExit();
3831 * Apply common settings to entityRef fields
3832 * @param array $field
3833 * @param string $table
3835 private function setEntityRefDefaults(&$field, $table) {
3836 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
3837 $field['attributes'] +
= array(
3838 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
3840 'placeholder' => ts('- select -'),