3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 protected $_options = array();
93 protected $_defaults = array();
96 * By default most reports hide contact id.
97 * Setting this to true makes it available
99 protected $_exposeContactID = TRUE;
102 * Set of statistic fields
106 protected $_statFields = array();
109 * Set of statistics data
113 protected $_statistics = array();
116 * List of fields not to be repeated during display
120 protected $_noRepeats = array();
123 * List of fields not to be displayed
127 protected $_noDisplay = array();
130 * Object type that a custom group extends
134 protected $_customGroupExtends = NULL;
135 protected $_customGroupExtendsJoin = array();
136 protected $_customGroupFilters = TRUE;
137 protected $_customGroupGroupBy = FALSE;
138 protected $_customGroupJoin = 'LEFT JOIN';
143 protected $_tagFilter = FALSE;
146 * specify entity table for tags filter
148 protected $_tagFilterTable = 'civicrm_contact';
151 * Build groups filter.
155 protected $_groupFilter = FALSE;
162 public $_navigation = array();
164 public $_drilldownReport = array();
167 * Array of tabs to display on report.
169 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
171 * $this->tabs['OrderBy'] = array(
172 * 'title' => ts('Sorting'),
173 * 'tpl' => 'OrderBy',
174 * 'div_label' => 'order-by',
179 protected $tabs = array();
182 * An attribute for checkbox/radio form field layout
186 protected $_fourColumnAttribute = array(
187 '</td><td width="25%">',
188 '</td><td width="25%">',
189 '</td><td width="25%">',
193 protected $_force = 1;
195 protected $_params = NULL;
196 protected $_formValues = NULL;
197 protected $_instanceValues = NULL;
199 protected $_instanceForm = FALSE;
200 protected $_criteriaForm = FALSE;
202 protected $_instanceButtonName = NULL;
203 protected $_createNewButtonName = NULL;
204 protected $_printButtonName = NULL;
205 protected $_pdfButtonName = NULL;
206 protected $_csvButtonName = NULL;
207 protected $_groupButtonName = NULL;
208 protected $_chartButtonName = NULL;
209 protected $_csvSupported = TRUE;
210 protected $_add2groupSupported = TRUE;
211 protected $_groups = NULL;
212 protected $_grandFlag = FALSE;
213 protected $_rowsFound = NULL;
214 protected $_selectAliases = array();
215 protected $_rollup = NULL;
220 protected $_aliases = array();
236 protected $_limit = NULL;
239 * This can be set to specify a limit to the number of rows
240 * Since it is currently envisaged as part of the api usage it is only being applied
241 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
242 * of the code (see limit() fn
245 protected $_limitValue = NULL;
248 * This can be set to specify row offset
249 * See notes on _limitValue
252 protected $_offsetValue = NULL;
256 protected $_sections = NULL;
257 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
258 protected $_absoluteUrl = FALSE;
261 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
265 protected $_storeResultSet = FALSE;
268 * When _storeResultSet Flag is set use this var to store result set in form of array
272 protected $_resultSet = array();
275 * To what frequency group-by a date column
279 protected $_groupByDateFreq = array(
281 'YEARWEEK' => 'Week',
282 'QUARTER' => 'Quarter',
287 * Variables to hold the acl inner join and where clause
289 protected $_aclFrom = NULL;
290 protected $_aclWhere = NULL;
293 * Array of DAO tables having columns included in SELECT or ORDER BY clause
297 protected $_selectedTables;
300 * Output mode e.g 'print', 'csv', 'pdf'
303 protected $_outputMode;
305 public $_having = NULL;
306 public $_select = NULL;
307 public $_selectClauses = array();
308 public $_columnHeaders = array();
309 public $_orderBy = NULL;
310 public $_orderByFields = array();
311 public $_orderByArray = array();
312 public $_groupBy = NULL;
313 public $_whereClauses = array();
314 public $_havingClauses = array();
317 * DashBoardRowCount Dashboard row count
320 public $_dashBoardRowCount;
323 * Is this being called without a form controller (ie. the report is being render outside the normal form
324 * - e.g the api is retrieving the rows
327 public $noController = FALSE;
330 * Variable to hold the currency alias
332 protected $_currencyColumn = NULL;
337 protected $_interval;
342 protected $_sendmail;
355 * @var string Report description.
357 public $_description;
360 * @var bool Is an address field selected.
361 * This was intended to determine if the address table should be joined in
362 * The isTableSelected function is now preferred for this purpose
364 protected $_addressField;
367 * @var bool Is an email field selected.
368 * This was intended to determine if the email table should be joined in
369 * The isTableSelected function is now preferred for this purpose
371 protected $_emailField;
374 * @var bool Is a phone field selected.
375 * This was intended to determine if the phone table should be joined in
376 * The isTableSelected function is now preferred for this purpose
378 protected $_phoneField;
381 * @var bool Create new report instance? (or update existing) on save.
383 protected $_createNew;
388 public function __construct() {
389 parent
::__construct();
391 $this->addClass('crm-report-form');
393 if ($this->_tagFilter
) {
394 $this->buildTagFilter();
396 if ($this->_exposeContactID
) {
397 if (array_key_exists('civicrm_contact', $this->_columns
)) {
398 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
400 'title' => 'Contact ID',
406 if ($this->_groupFilter
) {
407 $this->buildGroupFilter();
410 // Get all custom groups
411 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
413 // Get the custom groupIds for which the user has VIEW permission
414 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
415 // and addCustomDataToColumns() will allow access to all custom groups.
416 $permCustomGroupIds = array();
417 if (!CRM_Core_Permission
::check('access all custom data')) {
418 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
419 // do not allow custom data for reports if user doesn't have
420 // permission to access custom data.
421 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
422 $this->_customGroupExtends
= array();
426 // merge custom data columns to _columns list, if any
427 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
429 // add / modify display columns, filters ..etc
430 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
432 //assign currencyColumn variable to tpl
433 $this->assign('currencyColumn', $this->_currencyColumn
);
437 * Shared pre-process function.
439 * If overriding preProcess function this should still be called.
443 public function preProcessCommon() {
445 = CRM_Utils_Request
::retrieve(
448 CRM_Core_DAO
::$_nullObject
451 $this->_dashBoardRowCount
452 = CRM_Utils_Request
::retrieve(
455 CRM_Core_DAO
::$_nullObject
458 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
460 $this->assign('section', $this->_section
);
461 CRM_Core_Region
::instance('page-header')->add(array(
462 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
464 if (!$this->noController
) {
465 $this->setID($this->get('instanceId'));
468 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
470 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
474 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
475 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
476 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
480 $this->assign('instanceId', $this->_id
);
481 $params = array('id' => $this->_id
);
482 $this->_instanceValues
= array();
483 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
485 $this->_instanceValues
487 if (empty($this->_instanceValues
)) {
488 CRM_Core_Error
::fatal("Report could not be loaded.");
490 $this->_title
= $this->_instanceValues
['title'];
491 if (!empty($this->_instanceValues
['permission']) &&
492 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
493 CRM_Core_Permission
::check('administer Reports')
496 CRM_Utils_System
::permissionDenied();
497 CRM_Utils_System
::civiExit();
500 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
502 $this->_formValues
= unserialize($formValues);
505 $this->_formValues
= NULL;
508 // lets always do a force if reset is found in the url.
509 if (!empty($_REQUEST['reset'])) {
514 $this->assign('mode', 'instance');
516 elseif (!$this->noController
) {
517 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
518 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
519 if (($instanceCount > 0) && $optionValueID) {
520 $this->assign('instanceUrl',
521 CRM_Utils_System
::url('civicrm/report/list',
522 "reset=1&ovid=$optionValueID"
526 if ($optionValueID) {
527 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
531 $this->assign('mode', 'template');
534 // lets display the Report Settings section
535 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
537 // Do not display Report Settings section if administer Reports permission is absent OR
538 // if report instance is reserved and administer reserved reports absent
539 if (!CRM_Core_Permission
::check('administer Reports') ||
540 ($this->_instanceValues
['is_reserved'] &&
541 !CRM_Core_Permission
::check('administer reserved reports'))
543 $this->_instanceForm
= FALSE;
546 $this->assign('criteriaForm', FALSE);
547 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
548 if (CRM_Core_Permission
::check('administer Reports') ||
549 CRM_Core_Permission
::check('access Report Criteria')
551 if (!$this->_instanceValues
['is_reserved'] ||
552 CRM_Core_Permission
::check('administer reserved reports')
554 $this->assign('criteriaForm', TRUE);
555 $this->_criteriaForm
= TRUE;
559 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
560 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
561 $this->_printButtonName
= $this->getButtonName('submit', 'print');
562 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
563 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
564 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
565 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
571 public function addBreadCrumb() {
575 'title' => ts('Report Templates'),
576 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
580 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
584 * Pre process function.
586 * Called prior to build form.
588 public function preProcess() {
589 $this->preProcessCommon();
592 $this->addBreadCrumb();
595 foreach ($this->_columns
as $tableName => $table) {
597 if (!isset($table['alias'])) {
598 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
602 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
605 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
607 $daoOrBaoName = NULL;
608 // higher preference to bao object
609 if (array_key_exists('bao', $table)) {
610 $daoOrBaoName = $table['bao'];
611 $expFields = $daoOrBaoName::exportableFields();
613 elseif (array_key_exists('dao', $table)) {
614 $daoOrBaoName = $table['dao'];
615 $expFields = $daoOrBaoName::export();
618 $expFields = array();
621 $doNotCopy = array('required');
623 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
624 foreach ($fieldGroups as $fieldGrp) {
625 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
626 foreach ($table[$fieldGrp] as $fieldName => $field) {
627 // $name is the field name used to reference the BAO/DAO export fields array
628 $name = isset($field['name']) ?
$field['name'] : $fieldName;
630 // Sometimes the field name key in the BAO/DAO export fields array is
631 // different from the actual database field name.
632 // Unset $field['name'] so that actual database field name can be obtained
633 // from the BAO/DAO export fields array.
634 unset($field['name']);
636 if (array_key_exists($name, $expFields)) {
637 foreach ($doNotCopy as $dnc) {
638 // unset the values we don't want to be copied.
639 unset($expFields[$name][$dnc]);
642 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
645 foreach ($expFields[$name] as $property => $val) {
646 if (!array_key_exists($property, $field)) {
647 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
654 if (!empty($field['no_repeat'])) {
655 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
657 if (!empty($field['no_display'])) {
658 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
661 // set alias = table-name, unless already set
662 $alias = isset($field['alias']) ?
$field['alias'] : (
663 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
665 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
667 // set name = fieldName, unless already set
668 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
669 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
672 // set dbAlias = alias.name, unless already set
673 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
674 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
676 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
679 // a few auto fills for filters
680 if ($fieldGrp == 'filters') {
681 // fill operator types
682 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
683 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
684 case CRM_Utils_Type
::T_MONEY
:
685 case CRM_Utils_Type
::T_FLOAT
:
686 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
689 case CRM_Utils_Type
::T_INT
:
690 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
693 case CRM_Utils_Type
::T_DATE
:
694 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
697 case CRM_Utils_Type
::T_BOOLEAN
:
698 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
699 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
700 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
711 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
713 // with multiple options operator-type is generally multi-select
714 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
715 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
717 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
728 // copy filters to a separate handy variable
729 if (array_key_exists('filters', $table)) {
730 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
733 if (array_key_exists('group_bys', $table)) {
734 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
737 if (array_key_exists('fields', $table)) {
738 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
743 $this->setDefaultValues(FALSE);
746 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
747 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
748 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
749 CRM_Report_Utils_Get
::processChart($this->_defaults
);
752 $this->_formValues
= $this->_defaults
;
753 $this->postProcess();
758 * Set default values.
760 * @param bool $freeze
764 public function setDefaultValues($freeze = TRUE) {
765 $freezeGroup = array();
767 // FIXME: generalizing form field naming conventions would reduce
768 // Lots of lines below.
769 foreach ($this->_columns
as $tableName => $table) {
770 if (array_key_exists('fields', $table)) {
771 foreach ($table['fields'] as $fieldName => $field) {
772 if (empty($field['no_display'])) {
773 if (isset($field['required'])) {
775 $this->_defaults
['fields'][$fieldName] = 1;
778 // find element object, so that we could use quickform's freeze method
779 // for required elements
780 $obj = $this->getElementFromGroup("fields", $fieldName);
782 $freezeGroup[] = $obj;
786 elseif (isset($field['default'])) {
787 $this->_defaults
['fields'][$fieldName] = $field['default'];
793 if (array_key_exists('group_bys', $table)) {
794 foreach ($table['group_bys'] as $fieldName => $field) {
795 if (isset($field['default'])) {
796 if (!empty($field['frequency'])) {
797 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
799 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
803 if (array_key_exists('filters', $table)) {
804 foreach ($table['filters'] as $fieldName => $field) {
805 if (isset($field['default'])) {
806 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
808 if (is_array($field['default'])) {
809 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
810 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
811 $this->_defaults
["{$fieldName}_relative"] = 0;
814 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
818 $this->_defaults
["{$fieldName}_value"] = $field['default'];
821 //assign default value as "in" for multiselect
822 //operator, To freeze the select element
823 if (CRM_Utils_Array
::value('operatorType', $field) ==
824 CRM_Report_Form
::OP_MULTISELECT
826 $this->_defaults
["{$fieldName}_op"] = 'in';
828 if (CRM_Utils_Array
::value('operatorType', $field) ==
829 CRM_Report_Form
::OP_ENTITYREF
831 $this->_defaults
["{$fieldName}_op"] = 'in';
833 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
834 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
836 $this->_defaults
["{$fieldName}_op"] = 'mhas';
838 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
839 $this->_defaults
["{$fieldName}_op"] = $op;
845 empty($this->_formValues
['order_bys']) &&
846 (array_key_exists('order_bys', $table) &&
847 is_array($table['order_bys']))
849 if (!array_key_exists('order_bys', $this->_defaults
)) {
850 $this->_defaults
['order_bys'] = array();
852 foreach ($table['order_bys'] as $fieldName => $field) {
853 if (!empty($field['default']) ||
!empty($field['default_order']) ||
854 CRM_Utils_Array
::value('default_is_section', $field) ||
855 !empty($field['default_weight'])
858 'column' => $fieldName,
859 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
860 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
863 if (!empty($field['default_weight'])) {
864 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
867 array_unshift($this->_defaults
['order_bys'], $order_by);
873 foreach ($this->_options
as $fieldName => $field) {
874 if (isset($field['default'])) {
875 $this->_defaults
['options'][$fieldName] = $field['default'];
880 if (!empty($this->_submitValues
)) {
881 $this->preProcessOrderBy($this->_submitValues
);
884 $this->preProcessOrderBy($this->_defaults
);
887 // lets finish freezing task here itself
888 if (!empty($freezeGroup)) {
889 foreach ($freezeGroup as $elem) {
894 if ($this->_formValues
) {
895 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
898 if ($this->_instanceValues
) {
899 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
902 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
904 return $this->_defaults
;
908 * Get element from group.
910 * @param string $group
911 * @param string $grpFieldName
915 public function getElementFromGroup($group, $grpFieldName) {
916 $eleObj = $this->getElement($group);
917 foreach ($eleObj->_elements
as $index => $obj) {
918 if ($grpFieldName == $obj->_attributes
['name']) {
926 * Setter for $_params.
928 * @param array $params
930 public function setParams($params) {
931 $this->_params
= $params;
937 * @param int $instanceID
939 public function setID($instanceID) {
940 $this->_id
= $instanceID;
944 * Setter for $_force.
948 public function setForce($isForce) {
949 $this->_force
= $isForce;
953 * Setter for $_limitValue.
955 * @param int $_limitValue
957 public function setLimitValue($_limitValue) {
958 $this->_limitValue
= $_limitValue;
962 * Setter for $_offsetValue.
964 * @param int $_offsetValue
966 public function setOffsetValue($_offsetValue) {
967 $this->_offsetValue
= $_offsetValue;
971 * Getter for $_defaultValues.
975 public function getDefaultValues() {
976 return $this->_defaults
;
980 * Add columns to report.
982 public function addColumns() {
985 foreach ($this->_columns
as $tableName => $table) {
986 if (array_key_exists('fields', $table)) {
987 foreach ($table['fields'] as $fieldName => $field) {
989 if (empty($field['no_display'])) {
990 foreach (array('table', 'field') as $var) {
991 if (!empty($
{$var}['grouping'])) {
992 if (!is_array($
{$var}['grouping'])) {
993 $tableName = $
{$var}['grouping'];
996 $tableName = array_keys($
{$var}['grouping']);
997 $tableName = $tableName[0];
998 $groupTitle = array_values($
{$var}['grouping']);
999 $groupTitle = $groupTitle[0];
1004 if (!$groupTitle && isset($table['group_title'])) {
1005 $groupTitle = $table['group_title'];
1008 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1009 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1010 $colGroups[$tableName]['group_title'] = $groupTitle;
1013 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1019 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1020 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1022 if (!empty($colGroups)) {
1023 $this->tabs
['FieldSelection'] = array(
1024 'title' => ts('Columns'),
1025 'tpl' => 'FieldSelection',
1026 'div_label' => 'col-groups',
1029 // Note this assignment is only really required in buildForm. It is being 'over-called'
1030 // to reduce risk of being missed due to overridden functions.
1031 $this->assign('tabs', $this->tabs
);
1034 $this->assign('colGroups', $colGroups);
1038 * Add filters to report.
1040 public function addFilters() {
1043 foreach ($this->_filters
as $table => $attributes) {
1044 foreach ($attributes as $fieldName => $field) {
1045 // get ready with option value pair
1046 // @ 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
1048 $operations = $this->getOperationPair(
1049 CRM_Utils_Array
::value('operatorType', $field),
1052 $filters[$table][$fieldName] = $field;
1054 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1055 case CRM_Report_Form
::OP_MONTH
:
1056 if (!array_key_exists('options', $field) ||
1057 !is_array($field['options']) ||
empty($field['options'])
1059 // If there's no option list for this filter, define one.
1060 $field['options'] = array(
1062 2 => ts('February'),
1069 9 => ts('September'),
1070 10 => ts('October'),
1071 11 => ts('November'),
1072 12 => ts('December'),
1074 // Add this option list to this column _columns. This is
1075 // required so that filter statistics show properly.
1076 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1078 case CRM_Report_Form
::OP_MULTISELECT
:
1079 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1080 // assume a multi-select field
1081 if (!empty($field['options']) ||
1082 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1084 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1085 if (count($operations) <= 1) {
1088 if ($fieldName == 'state_province_id' ||
1089 $fieldName == 'county_id'
1091 $this->addChainSelect($fieldName . '_value', array(
1098 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1099 'style' => 'min-width:250px',
1100 'class' => 'crm-select2 huge',
1102 'placeholder' => ts('- select -'),
1108 case CRM_Report_Form
::OP_SELECT
:
1109 // assume a select field
1110 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1111 if (!empty($field['options'])) {
1112 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1116 case CRM_Report_Form
::OP_ENTITYREF
:
1117 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1118 $this->setEntityRefDefaults($field, $table);
1119 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1122 case CRM_Report_Form
::OP_DATE
:
1123 // build datetime fields
1124 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1128 case CRM_Report_Form
::OP_DATETIME
:
1129 // build datetime fields
1130 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1134 case CRM_Report_Form
::OP_INT
:
1135 case CRM_Report_Form
::OP_FLOAT
:
1136 // and a min value input box
1137 $this->add('text', "{$fieldName}_min", ts('Min'));
1138 // and a max value input box
1139 $this->add('text', "{$fieldName}_max", ts('Max'));
1141 // default type is string
1142 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1143 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1145 // we need text box for value input
1146 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1151 if (!empty($filters)) {
1152 $this->tabs
['Filters'] = array(
1153 'title' => ts('Filters'),
1155 'div_label' => 'set-filters',
1158 $this->assign('filters', $filters);
1162 * Function to assign the tabs to the template in the correct order.
1164 * We want the tabs to wind up in this order (if not overridden).
1172 protected function assignTabs() {
1180 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1181 $order = array_merge($order, $this->tabs
);
1182 $this->assign('tabs', $order);
1186 * Add options defined in $this->_options to the report.
1188 public function addOptions() {
1189 if (!empty($this->_options
)) {
1190 // FIXME: For now lets build all elements as checkboxes.
1191 // Once we clear with the format we can build elements based on type
1194 foreach ($this->_options
as $fieldName => $field) {
1195 if ($field['type'] == 'select') {
1196 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1198 elseif ($field['type'] == 'checkbox') {
1199 $options[$field['title']] = $fieldName;
1200 $this->addCheckBox($fieldName, NULL,
1202 NULL, NULL, NULL, $this->_fourColumnAttribute
1207 if (!empty($this->_options
)) {
1208 $this->tabs
['ReportOptions'] = array(
1209 'title' => ts('Display Options'),
1210 'tpl' => 'ReportOptions',
1211 'div_label' => 'other-options',
1214 $this->assign('otherOptions', $this->_options
);
1218 * Add chart options to the report.
1220 public function addChartOptions() {
1221 if (!empty($this->_charts
)) {
1222 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1223 $this->assign('charts', $this->_charts
);
1224 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1229 * Add group by options to the report.
1231 public function addGroupBys() {
1232 $options = $freqElements = array();
1234 foreach ($this->_columns
as $tableName => $table) {
1235 if (array_key_exists('group_bys', $table)) {
1236 foreach ($table['group_bys'] as $fieldName => $field) {
1237 if (!empty($field)) {
1238 $options[$field['title']] = $fieldName;
1239 if (!empty($field['frequency'])) {
1240 $freqElements[$field['title']] = $fieldName;
1246 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1247 NULL, NULL, NULL, $this->_fourColumnAttribute
1249 $this->assign('groupByElements', $options);
1250 if (!empty($options)) {
1251 $this->tabs
['GroupBy'] = array(
1252 'title' => ts('Grouping'),
1254 'div_label' => 'group-by-elements',
1258 foreach ($freqElements as $name) {
1259 $this->addElement('select', "group_bys_freq[$name]",
1260 ts('Frequency'), $this->_groupByDateFreq
1266 * Add data for order by tab.
1268 public function addOrderBys() {
1270 foreach ($this->_columns
as $tableName => $table) {
1272 // Report developer may define any column to order by; include these as order-by options.
1273 if (array_key_exists('order_bys', $table)) {
1274 foreach ($table['order_bys'] as $fieldName => $field) {
1275 if (!empty($field)) {
1276 $options[$fieldName] = $field['title'];
1281 // Add searchable custom fields as order-by options, if so requested
1282 // (These are already indexed, so allowing to order on them is cheap.)
1284 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1285 array_key_exists('extends', $table) && !empty($table['extends'])
1287 foreach ($table['fields'] as $fieldName => $field) {
1288 if (empty($field['no_display'])) {
1289 $options[$fieldName] = $field['title'];
1297 $this->assign('orderByOptions', $options);
1298 if (!empty($options)) {
1299 $this->tabs
['OrderBy'] = array(
1300 'title' => ts('Sorting'),
1302 'div_label' => 'order-by-elements',
1306 if (!empty($options)) {
1308 '-' => ' - none - ',
1310 for ($i = 1; $i <= 5; $i++
) {
1311 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1312 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1313 'ASC' => 'Ascending',
1314 'DESC' => 'Descending',
1316 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1317 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1323 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1325 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1326 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1329 public function buildInstanceAndButtons() {
1330 CRM_Report_Form_Instance
::buildForm($this);
1332 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1334 $this->addElement('submit', $this->_instanceButtonName
, $label);
1335 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1336 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1339 $this->addElement('submit', $this->_createNewButtonName
,
1340 ts('Save a Copy') . '...');
1342 $this->assign('instanceForm', $this->_instanceForm
);
1344 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1345 $this->addElement('submit', $this->_printButtonName
, $label);
1347 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1348 $this->addElement('submit', $this->_pdfButtonName
, $label);
1350 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1352 if ($this->_csvSupported
) {
1353 $this->addElement('submit', $this->_csvButtonName
, $label);
1356 if (CRM_Core_Permission
::check('administer Reports') &&
1357 $this->_add2groupSupported
1359 $this->addElement('select', 'groups', ts('Group'),
1360 array('' => ts('Add Contacts to Group')) +
1361 CRM_Core_PseudoConstant
::nestedGroup(),
1362 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1364 $this->assign('group', TRUE);
1367 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1369 $this->addChartOptions();
1370 $this->addButtons(array(
1373 'name' => ts('Preview Report'),
1374 'isDefault' => TRUE,
1381 * Main build form function.
1383 public function buildQuickForm() {
1384 $this->addColumns();
1386 $this->addFilters();
1388 $this->addOptions();
1390 $this->addGroupBys();
1392 $this->addOrderBys();
1394 $this->buildInstanceAndButtons();
1396 // Add form rule for report.
1397 if (is_callable(array(
1401 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1403 $this->assignTabs();
1407 * A form rule function to ensure that fields selected in group_by
1408 * (if any) should only be the ones present in display/select fields criteria;
1409 * note: works if and only if any custom field selected in group_by.
1411 * @param array $fields
1412 * @param array $ignoreFields
1416 public function customDataFormRule($fields, $ignoreFields = array()) {
1418 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1419 !empty($fields['group_bys'])
1421 foreach ($this->_columns
as $tableName => $table) {
1422 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1423 substr($tableName, 0, 12) == 'custom_value') &&
1424 !empty($this->_columns
[$tableName]['fields'])
1426 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1427 if (array_key_exists($fieldName, $fields['group_bys']) &&
1428 !array_key_exists($fieldName, $fields['fields'])
1430 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1432 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1433 foreach ($fields['fields'] as $fld => $val) {
1434 if (!array_key_exists($fld, $fields['group_bys']) &&
1435 !in_array($fld, $ignoreFields)
1437 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1449 * Get operators to display on form.
1451 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1453 * @param string $type
1454 * @param string $fieldName
1458 public function getOperationPair($type = "string", $fieldName = NULL) {
1459 // FIXME: At some point we should move these key-val pairs
1460 // to option_group and option_value table.
1462 case CRM_Report_Form
::OP_INT
:
1463 case CRM_Report_Form
::OP_FLOAT
:
1466 'lte' => ts('Is less than or equal to'),
1467 'gte' => ts('Is greater than or equal to'),
1468 'bw' => ts('Is between'),
1469 'eq' => ts('Is equal to'),
1470 'lt' => ts('Is less than'),
1471 'gt' => ts('Is greater than'),
1472 'neq' => ts('Is not equal to'),
1473 'nbw' => ts('Is not between'),
1474 'nll' => ts('Is empty (Null)'),
1475 'nnll' => ts('Is not empty (Null)'),
1479 case CRM_Report_Form
::OP_SELECT
:
1481 'eq' => ts('Is equal to'),
1485 case CRM_Report_Form
::OP_MONTH
:
1486 case CRM_Report_Form
::OP_MULTISELECT
:
1487 case CRM_Report_Form
::OP_ENTITYREF
:
1490 'in' => ts('Is one of'),
1491 'notin' => ts('Is not one of'),
1495 case CRM_Report_Form
::OP_DATE
:
1498 'nll' => ts('Is empty (Null)'),
1499 'nnll' => ts('Is not empty (Null)'),
1503 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1504 // use this operator for the values, concatenated with separator. For e.g if
1505 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1507 'mhas' => ts('Is one of'),
1508 'mnot' => ts('Is not one of'),
1515 'has' => ts('Contains'),
1516 'sw' => ts('Starts with'),
1517 'ew' => ts('Ends with'),
1518 'nhas' => ts('Does not contain'),
1519 'eq' => ts('Is equal to'),
1520 'neq' => ts('Is not equal to'),
1521 'nll' => ts('Is empty (Null)'),
1522 'nnll' => ts('Is not empty (Null)'),
1529 * Build the tag filter field to display on the filters tab.
1531 public function buildTagFilter() {
1532 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1533 if (!empty($contactTags)) {
1534 $this->_columns
['civicrm_tag'] = array(
1535 'dao' => 'CRM_Core_DAO_Tag',
1539 'title' => ts('Tag'),
1541 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1542 'options' => $contactTags,
1550 * Adds group filters to _columns (called from _Construct).
1552 public function buildGroupFilter() {
1553 $this->_columns
['civicrm_group']['filters'] = array(
1555 'name' => 'group_id',
1556 'title' => ts('Group'),
1557 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1559 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1562 if (empty($this->_columns
['civicrm_group']['dao'])) {
1563 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1565 if (empty($this->_columns
['civicrm_group']['alias'])) {
1566 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1571 * Get SQL operator from form text version.
1573 * @param string $operator
1577 public function getSQLOperator($operator = "like") {
1578 switch ($operator) {
1611 return 'IS NOT NULL';
1620 * Generate where clause.
1622 * This can be overridden in reports for special treatment of a field
1624 * @param array $field Field specifications
1625 * @param string $op Query operator (not an exact match to sql)
1626 * @param mixed $value
1630 * @return null|string
1632 public function whereClause(&$field, $op, $value, $min, $max) {
1634 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1640 if (($min !== NULL && strlen($min) > 0) ||
1641 ($max !== NULL && strlen($max) > 0)
1643 $min = CRM_Utils_Type
::escape($min, $type);
1644 $max = CRM_Utils_Type
::escape($max, $type);
1648 $clauses[] = "( {$field['dbAlias']} >= $min )";
1651 $clauses[] = "( {$field['dbAlias']} < $min )";
1656 $clauses[] = "( {$field['dbAlias']} <= $max )";
1659 $clauses[] = "( {$field['dbAlias']} > $max )";
1663 if (!empty($clauses)) {
1665 $clause = implode(' AND ', $clauses);
1668 $clause = implode(' OR ', $clauses);
1676 if ($value !== NULL && strlen($value) > 0) {
1677 $value = CRM_Utils_Type
::escape($value, $type);
1678 if (strpos($value, '%') === FALSE) {
1679 $value = "'%{$value}%'";
1682 $value = "'{$value}'";
1684 $sqlOP = $this->getSQLOperator($op);
1685 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1691 if (is_string($value) && strlen($value)) {
1692 $value = explode(',', $value);
1694 if ($value !== NULL && is_array($value) && count($value) > 0) {
1695 $sqlOP = $this->getSQLOperator($op);
1696 if (CRM_Utils_Array
::value('type', $field) ==
1697 CRM_Utils_Type
::T_STRING
1699 //cycle through selections and escape values
1700 foreach ($value as $key => $selection) {
1701 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1704 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1708 // for numerical values
1709 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1712 if ($op == 'notin') {
1713 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1716 $clause = "( " . $clause . " )";
1722 // mhas == multiple has
1723 if ($value !== NULL && count($value) > 0) {
1724 $sqlOP = $this->getSQLOperator($op);
1726 = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) .
1732 // mnot == multiple is not one of
1733 if ($value !== NULL && count($value) > 0) {
1734 $sqlOP = $this->getSQLOperator($op);
1736 = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) .
1737 "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1743 if ($value !== NULL && strlen($value) > 0) {
1744 $value = CRM_Utils_Type
::escape($value, $type);
1745 if (strpos($value, '%') === FALSE) {
1747 $value = "'{$value}%'";
1750 $value = "'%{$value}'";
1754 $value = "'{$value}'";
1756 $sqlOP = $this->getSQLOperator($op);
1757 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1763 $sqlOP = $this->getSQLOperator($op);
1764 $clause = "( {$field['dbAlias']} $sqlOP )";
1768 if ($value !== NULL && strlen($value) > 0) {
1769 if (isset($field['clause'])) {
1770 // FIXME: we not doing escape here. Better solution is to use two
1771 // different types - data-type and filter-type
1772 $clause = $field['clause'];
1775 $value = CRM_Utils_Type
::escape($value, $type);
1776 $sqlOP = $this->getSQLOperator($op);
1777 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1778 $value = "'{$value}'";
1780 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1786 if (!empty($field['group']) && $clause) {
1787 $clause = $this->whereGroupClause($field, $value, $op);
1789 elseif (!empty($field['tag']) && $clause) {
1790 // not using left join in query because if any contact
1791 // belongs to more than one tag, results duplicate
1793 $clause = $this->whereTagClause($field, $value, $op);
1795 elseif (!empty($field['membership_org']) && $clause) {
1796 $clause = $this->whereMembershipOrgClause($value, $op);
1798 elseif (!empty($field['membership_type']) && $clause) {
1799 $clause = $this->whereMembershipTypeClause($value, $op);
1805 * Get SQL where clause for a date field.
1807 * @param string $fieldName
1809 * @param string $from
1811 * @param string $type
1812 * @param string $fromTime
1813 * @param string $toTime
1815 * @return null|string
1817 public function dateClause(
1819 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1822 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1823 $sqlOP = $this->getSQLOperator($relative);
1824 return "( {$fieldName} {$sqlOP} )";
1827 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1830 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1831 $clauses[] = "( {$fieldName} >= $from )";
1835 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1836 $clauses[] = "( {$fieldName} <= {$to} )";
1839 if (!empty($clauses)) {
1840 return implode(' AND ', $clauses);
1847 * @todo - could not find any instances where this is called
1849 * @param bool $relative
1850 * @param string $from
1853 * @return string|NULL
1855 public function dateDisplay($relative, $from, $to) {
1856 list($from, $to) = $this->getFromTo($relative, $from, $to);
1859 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1862 $clauses[] = 'Past';
1866 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1869 $clauses[] = 'Today';
1872 if (!empty($clauses)) {
1873 return implode(' - ', $clauses);
1880 * @param bool $relative
1881 * @param string $from
1883 * @param string $fromTime
1884 * @param string $toTime
1888 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1889 if (empty($toTime)) {
1892 //FIX ME not working for relative
1894 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1895 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1896 $from = substr($dateRange['from'], 0, 8);
1897 //Take only Date Part, Sometime Time part is also present in 'to'
1898 $to = substr($dateRange['to'], 0, 8);
1900 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1901 $to = CRM_Utils_Date
::processDate($to, $toTime);
1902 return array($from, $to);
1906 * Alter display of rows.
1908 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1909 * such as rendering contacts as links.
1911 * @param array $rows
1912 * Rows generated by SQL, with an array for each row.
1914 public function alterDisplay(&$rows) {
1920 public function alterCustomDataDisplay(&$rows) {
1921 // custom code to alter rows having custom values
1922 if (empty($this->_customGroupExtends
)) {
1926 $customFieldIds = array();
1927 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1928 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1929 $customFieldIds[$fieldAlias] = $fieldId;
1932 if (empty($customFieldIds)) {
1936 $customFields = $fieldValueMap = array();
1937 $customFieldCols = array(
1945 // skip for type date and ContactReference since date format is already handled
1947 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1948 FROM civicrm_custom_field cf
1949 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1950 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1951 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1952 cg.is_active = 1 AND
1953 cf.is_active = 1 AND
1954 cf.is_searchable = 1 AND
1955 cf.data_type NOT IN ('ContactReference', 'Date') AND
1956 cf.id IN (" . implode(",", $customFieldIds) . ")";
1958 $dao = CRM_Core_DAO
::executeQuery($query);
1959 while ($dao->fetch()) {
1960 foreach ($customFieldCols as $key) {
1961 $customFields[$dao->table_name
. '_custom_' .
1962 $dao->id
][$key] = $dao->$key;
1964 if ($dao->option_group_id
) {
1965 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1970 $entryFound = FALSE;
1971 foreach ($rows as $rowNum => $row) {
1972 foreach ($row as $tableCol => $val) {
1973 if (array_key_exists($tableCol, $customFields)) {
1974 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1979 // skip looking further in rows, if first row itself doesn't
1980 // have the column we need
1989 * @param $customField
1990 * @param $fieldValueMap
1992 * @return float|string|void
1994 public function formatCustomValues($value, $customField, $fieldValueMap) {
1995 if (CRM_Utils_System
::isNull($value)) {
1999 $htmlType = $customField['html_type'];
2001 switch ($customField['data_type']) {
2003 if ($value == '1') {
2004 $retValue = ts('Yes');
2007 $retValue = ts('No');
2012 $retValue = CRM_Utils_System
::formatWikiURL($value);
2024 if ($htmlType == 'Text') {
2025 $retValue = (float) $value;
2029 if ($htmlType == 'Text') {
2030 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2035 if (in_array($htmlType, array(
2042 case 'StateProvince':
2045 switch ($htmlType) {
2046 case 'Multi-Select Country':
2047 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2048 $customData = array();
2049 foreach ($value as $val) {
2051 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
2054 $retValue = implode(', ', $customData);
2057 case 'Select Country':
2058 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
2061 case 'Select State/Province':
2062 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2065 case 'Multi-Select State/Province':
2066 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2067 $customData = array();
2068 foreach ($value as $val) {
2070 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
2073 $retValue = implode(', ', $customData);
2078 case 'Autocomplete-Select':
2079 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2083 case 'AdvMulti-Select':
2084 case 'Multi-Select':
2085 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2086 $customData = array();
2087 foreach ($value as $val) {
2089 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2092 $retValue = implode(', ', $customData);
2110 public function removeDuplicates(&$rows) {
2111 if (empty($this->_noRepeats
)) {
2114 $checkList = array();
2116 foreach ($rows as $key => $list) {
2117 foreach ($list as $colName => $colVal) {
2118 if (array_key_exists($colName, $checkList) &&
2119 $checkList[$colName] == $colVal
2121 $rows[$key][$colName] = "";
2123 if (in_array($colName, $this->_noRepeats
)) {
2124 $checkList[$colName] = $colVal;
2133 * @param bool $subtotal
2135 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2136 foreach ($row as $colName => $colVal) {
2137 if (in_array($colName, $fields)) {
2139 elseif (isset($this->_columnHeaders
[$colName])) {
2141 $row[$colName] = "Subtotal";
2145 unset($row[$colName]);
2156 public function grandTotal(&$rows) {
2157 if (!$this->_rollup ||
($this->_rollup
== '') ||
2158 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2162 $lastRow = array_pop($rows);
2164 foreach ($this->_columnHeaders
as $fld => $val) {
2165 if (!in_array($fld, $this->_statFields
)) {
2166 if (!$this->_grandFlag
) {
2167 $lastRow[$fld] = "Grand Total";
2168 $this->_grandFlag
= TRUE;
2171 $lastRow[$fld] = "";
2176 $this->assign('grandStat', $lastRow);
2182 * @param bool $pager
2184 public function formatDisplay(&$rows, $pager = TRUE) {
2185 // set pager based on if any limit was applied in the query.
2190 // allow building charts if any
2191 if (!empty($this->_params
['charts']) && !empty($rows)) {
2192 $this->buildChart($rows);
2193 $this->assign('chartEnabled', TRUE);
2194 $this->_chartId
= "{$this->_params['charts']}_" .
2195 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2197 $this->assign('chartId', $this->_chartId
);
2200 // unset columns not to be displayed.
2201 foreach ($this->_columnHeaders
as $key => $value) {
2202 if (!empty($value['no_display'])) {
2203 unset($this->_columnHeaders
[$key]);
2207 // unset columns not to be displayed.
2208 if (!empty($rows)) {
2209 foreach ($this->_noDisplay
as $noDisplayField) {
2210 foreach ($rows as $rowNum => $row) {
2211 unset($this->_columnHeaders
[$noDisplayField]);
2216 // build array of section totals
2217 $this->sectionTotals();
2219 // process grand-total row
2220 $this->grandTotal($rows);
2222 // use this method for formatting rows for display purpose.
2223 $this->alterDisplay($rows);
2224 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2226 // use this method for formatting custom rows for display purpose.
2227 $this->alterCustomDataDisplay($rows);
2233 public function buildChart(&$rows) {
2234 // override this method for building charts.
2237 // select() method below has been added recently (v3.3), and many of the report templates might
2238 // still be having their own select() method. We should fix them as and when encountered and move
2239 // towards generalizing the select() method below.
2242 * Generate the SELECT clause and set class variable $_select
2244 public function select() {
2245 $select = $this->_selectAliases
= array();
2247 foreach ($this->_columns
as $tableName => $table) {
2248 if (array_key_exists('fields', $table)) {
2249 foreach ($table['fields'] as $fieldName => $field) {
2250 if ($tableName == 'civicrm_address') {
2251 $this->_addressField
= TRUE;
2253 if ($tableName == 'civicrm_email') {
2254 $this->_emailField
= TRUE;
2256 if ($tableName == 'civicrm_phone') {
2257 $this->_phoneField
= TRUE;
2260 if (!empty($field['required']) ||
2261 !empty($this->_params
['fields'][$fieldName])
2264 // 1. In many cases we want select clause to be built in slightly different way
2265 // for a particular field of a particular type.
2266 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2268 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2269 if ($selectClause) {
2270 $select[] = $selectClause;
2274 // include statistics columns only if set
2275 if (!empty($field['statistics'])) {
2276 foreach ($field['statistics'] as $stat => $label) {
2277 $alias = "{$tableName}_{$fieldName}_{$stat}";
2278 switch (strtolower($stat)) {
2281 $select[] = "$stat({$field['dbAlias']}) as $alias";
2282 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2283 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2284 $this->_statFields
[$label] = $alias;
2285 $this->_selectAliases
[] = $alias;
2289 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2290 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2291 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2292 $this->_statFields
[$label] = $alias;
2293 $this->_selectAliases
[] = $alias;
2296 case 'count_distinct':
2297 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2298 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2299 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2300 $this->_statFields
[$label] = $alias;
2301 $this->_selectAliases
[] = $alias;
2305 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2306 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2307 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2308 $this->_statFields
[$label] = $alias;
2309 $this->_selectAliases
[] = $alias;
2315 $alias = "{$tableName}_{$fieldName}";
2316 $select[] = "{$field['dbAlias']} as $alias";
2317 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2318 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2319 $this->_selectAliases
[] = $alias;
2325 // select for group bys
2326 if (array_key_exists('group_bys', $table)) {
2327 foreach ($table['group_bys'] as $fieldName => $field) {
2329 if ($tableName == 'civicrm_address') {
2330 $this->_addressField
= TRUE;
2332 if ($tableName == 'civicrm_email') {
2333 $this->_emailField
= TRUE;
2335 if ($tableName == 'civicrm_phone') {
2336 $this->_phoneField
= TRUE;
2338 // 1. In many cases we want select clause to be built in slightly different way
2339 // for a particular field of a particular type.
2340 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2342 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2343 if ($selectClause) {
2344 $select[] = $selectClause;
2348 if (!empty($this->_params
['group_bys']) &&
2349 !empty($this->_params
['group_bys'][$fieldName]) &&
2350 !empty($this->_params
['group_bys_freq'])
2352 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2354 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2355 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2356 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2357 $field['title'] = 'Week';
2361 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2362 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2363 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2364 $field['title'] = 'Year';
2368 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2369 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2370 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2371 $field['title'] = 'Month';
2375 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2376 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2377 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2378 $field['title'] = 'Quarter';
2381 // for graphs and charts -
2382 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2383 $this->_interval
= $field['title'];
2384 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2385 = $field['title'] . ' Beginning';
2386 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2387 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2389 // just to make sure these values are transferred to rows.
2390 // since we 'll need them for calculation purpose,
2391 // e.g making subtotals look nicer or graphs
2392 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2393 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2400 $this->_selectClauses
= $select;
2401 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2405 * @param string $tableName
2407 * @param string $fieldName
2412 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2416 public function where() {
2417 $this->storeWhereHavingClauseArray();
2419 if (empty($this->_whereClauses
)) {
2420 $this->_where
= "WHERE ( 1 ) ";
2421 $this->_having
= "";
2424 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2427 if ($this->_aclWhere
) {
2428 $this->_where
.= " AND {$this->_aclWhere} ";
2431 if (!empty($this->_havingClauses
)) {
2432 // use this clause to construct group by clause.
2433 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2438 * Store Where clauses into an array - breaking out this step makes
2439 * over-riding more flexible as the clauses can be used in constructing a
2440 * temp table that may not be part of the final where clause or added
2441 * in other functions
2443 public function storeWhereHavingClauseArray() {
2444 foreach ($this->_columns
as $tableName => $table) {
2445 if (array_key_exists('filters', $table)) {
2446 foreach ($table['filters'] as $fieldName => $field) {
2447 // respect pseudofield to filter spec so fields can be marked as
2448 // not to be handled here
2449 if (!empty($field['pseudofield'])) {
2453 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2454 if (CRM_Utils_Array
::value('operatorType', $field) ==
2455 CRM_Report_Form
::OP_MONTH
2457 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2458 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2459 if (is_array($value) && !empty($value)) {
2461 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2466 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2467 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2468 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2469 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2470 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2471 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2475 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2477 $clause = $this->whereClause($field,
2479 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2480 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2481 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2486 if (!empty($clause)) {
2487 if (!empty($field['having'])) {
2488 $this->_havingClauses
[] = $clause;
2491 $this->_whereClauses
[] = $clause;
2500 public function processReportMode() {
2501 $buttonName = $this->controller
->getButtonName();
2503 $output = CRM_Utils_Request
::retrieve(
2506 CRM_Core_DAO
::$_nullObject
2510 = CRM_Utils_Request
::retrieve(
2513 CRM_Core_DAO
::$_nullObject
2516 $this->_absoluteUrl
= FALSE;
2518 $this->assign('printOnly', FALSE);
2520 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2521 ($this->_sendmail
&& !$output)
2523 $this->assign('printOnly', TRUE);
2525 $this->assign('outputMode', 'print');
2526 $this->_outputMode
= 'print';
2527 if ($this->_sendmail
) {
2528 $this->_absoluteUrl
= TRUE;
2531 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2532 $this->assign('printOnly', TRUE);
2534 $this->assign('outputMode', 'pdf');
2535 $this->_outputMode
= 'pdf';
2536 $this->_absoluteUrl
= TRUE;
2538 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2539 $this->assign('printOnly', TRUE);
2541 $this->assign('outputMode', 'csv');
2542 $this->_outputMode
= 'csv';
2543 $this->_absoluteUrl
= TRUE;
2545 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2546 $this->assign('outputMode', 'group');
2547 $this->_outputMode
= 'group';
2549 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2550 $this->assign('outputMode', 'create_report');
2551 $this->_outputMode
= 'create_report';
2554 $this->assign('outputMode', 'html');
2555 $this->_outputMode
= 'html';
2558 // Get today's date to include in printed reports
2560 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2561 $this->assign('reportDate', $reportDate);
2566 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2568 public function beginPostProcess() {
2569 $this->setParams($this->controller
->exportValues($this->_name
));
2571 if (empty($this->_params
) &&
2574 $this->setParams($this->_formValues
);
2577 // hack to fix params when submitted from dashboard, CRM-8532
2578 // fields array is missing because form building etc is skipped
2579 // in dashboard mode for report
2580 //@todo - this could be done in the dashboard no we have a setter
2581 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2582 $this->setParams($this->_formValues
);
2585 $this->_formValues
= $this->_params
;
2586 if (CRM_Core_Permission
::check('administer Reports') &&
2587 isset($this->_id
) &&
2588 ($this->_instanceButtonName
==
2589 $this->controller
->getButtonName() . '_save' ||
2590 $this->_chartButtonName
== $this->controller
->getButtonName()
2593 $this->assign('updateReportButton', TRUE);
2595 $this->processReportMode();
2596 $this->beginPostProcessCommon();
2600 * BeginPostProcess function run in both report mode and non-report mode (api)
2602 public function beginPostProcessCommon() {
2607 * @param bool $applyLimit
2611 public function buildQuery($applyLimit = TRUE) {
2614 $this->customDataFrom();
2619 // order_by columns not selected for display need to be included in SELECT
2620 $unselectedSectionColumns = $this->unselectedSectionColumns();
2621 foreach ($unselectedSectionColumns as $alias => $section) {
2622 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2625 if ($applyLimit && empty($this->_params
['charts'])) {
2628 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2630 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2634 public function groupBy() {
2635 $groupBys = array();
2636 if (!empty($this->_params
['group_bys']) &&
2637 is_array($this->_params
['group_bys']) &&
2638 !empty($this->_params
['group_bys'])
2640 foreach ($this->_columns
as $tableName => $table) {
2641 if (array_key_exists('group_bys', $table)) {
2642 foreach ($table['group_bys'] as $fieldName => $field) {
2643 if (!empty($this->_params
['group_bys'][$fieldName])) {
2644 $groupBys[] = $field['dbAlias'];
2651 if (!empty($groupBys)) {
2652 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2656 public function orderBy() {
2657 $this->_orderBy
= "";
2658 $this->_sections
= array();
2659 $this->storeOrderByArray();
2660 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2661 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2663 $this->assign('sections', $this->_sections
);
2667 * In some cases other functions want to know which fields are selected for ordering by
2668 * Separating this into a separate function allows it to be called separately from constructing
2669 * the order by clause
2671 public function storeOrderByArray() {
2672 $orderBys = array();
2674 if (!empty($this->_params
['order_bys']) &&
2675 is_array($this->_params
['order_bys']) &&
2676 !empty($this->_params
['order_bys'])
2679 // Process order_bys in user-specified order
2680 foreach ($this->_params
['order_bys'] as $orderBy) {
2681 $orderByField = array();
2682 foreach ($this->_columns
as $tableName => $table) {
2683 if (array_key_exists('order_bys', $table)) {
2684 // For DAO columns defined in $this->_columns
2685 $fields = $table['order_bys'];
2687 elseif (array_key_exists('extends', $table)) {
2688 // For custom fields referenced in $this->_customGroupExtends
2689 $fields = CRM_Utils_Array
::value('fields', $table, array());
2694 if (!empty($fields) && is_array($fields)) {
2695 foreach ($fields as $fieldName => $field) {
2696 if ($fieldName == $orderBy['column']) {
2697 $orderByField = array_merge($field, $orderBy);
2698 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2705 if (!empty($orderByField)) {
2706 $this->_orderByFields
[] = $orderByField;
2707 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2709 // Record any section headers for assignment to the template
2710 if (!empty($orderBy['section'])) {
2711 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2712 $this->_sections
[$orderByField['tplField']] = $orderByField;
2718 $this->_orderByArray
= $orderBys;
2720 $this->assign('sections', $this->_sections
);
2726 public function unselectedSectionColumns() {
2727 $selectColumns = array();
2728 foreach ($this->_columns
as $tableName => $table) {
2729 if (array_key_exists('fields', $table)) {
2730 foreach ($table['fields'] as $fieldName => $field) {
2731 if (!empty($field['required']) ||
2732 !empty($this->_params
['fields'][$fieldName])
2735 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2741 if (is_array($this->_sections
)) {
2742 return array_diff_key($this->_sections
, $selectColumns);
2753 public function buildRows($sql, &$rows) {
2754 $dao = CRM_Core_DAO
::executeQuery($sql);
2755 if (!is_array($rows)) {
2759 // use this method to modify $this->_columnHeaders
2760 $this->modifyColumnHeaders();
2762 $unselectedSectionColumns = $this->unselectedSectionColumns();
2764 while ($dao->fetch()) {
2766 foreach ($this->_columnHeaders
as $key => $value) {
2767 if (property_exists($dao, $key)) {
2768 $row[$key] = $dao->$key;
2772 // section headers not selected for display need to be added to row
2773 foreach ($unselectedSectionColumns as $key => $values) {
2774 if (property_exists($dao, $key)) {
2775 $row[$key] = $dao->$key;
2784 * When "order by" fields are marked as sections, this assigns to the template
2785 * an array of total counts for each section. This data is used by the Smarty
2786 * plugin {sectionTotal}
2788 public function sectionTotals() {
2790 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2791 if (empty($this->_selectAliases
)) {
2795 if (!empty($this->_sections
)) {
2796 // build the query with no LIMIT clause
2797 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2798 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2800 // pull section aliases out of $this->_sections
2801 $sectionAliases = array_keys($this->_sections
);
2804 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2805 $ifnulls[] = "ifnull($alias, '') as $alias";
2808 // Group (un-limited) report by all aliases and get counts. This might
2809 // be done more efficiently when the contents of $sql are known, ie. by
2810 // overriding this method in the report class.
2812 $query = "select " . implode(", ", $ifnulls) .
2813 ", count(*) as ct from ($sql) as subquery group by " .
2814 implode(", ", $sectionAliases);
2816 // initialize array of total counts
2818 $dao = CRM_Core_DAO
::executeQuery($query);
2819 while ($dao->fetch()) {
2821 // let $this->_alterDisplay translate any integer ids to human-readable values.
2822 $rows[0] = $dao->toArray();
2823 $this->alterDisplay($rows);
2826 // add totals for all permutations of section values
2829 $aliasCount = count($sectionAliases);
2830 foreach ($sectionAliases as $alias) {
2831 $values[] = $row[$alias];
2832 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2833 if ($i == $aliasCount) {
2834 // the last alias is the lowest-level section header; use count as-is
2835 $totals[$key] = $dao->ct
;
2838 // other aliases are higher level; roll count into their total
2839 $totals[$key] +
= $dao->ct
;
2843 $this->assign('sectionTotals', $totals);
2847 public function modifyColumnHeaders() {
2848 // use this method to modify $this->_columnHeaders
2854 public function doTemplateAssignment(&$rows) {
2855 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2856 $this->assign_by_ref('rows', $rows);
2857 $this->assign('statistics', $this->statistics($rows));
2861 * override this method to build your own statistics
2866 public function statistics(&$rows) {
2867 $statistics = array();
2869 $count = count($rows);
2871 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2875 $this->countStat($statistics, $count);
2877 $this->groupByStat($statistics);
2879 $this->filterStat($statistics);
2885 * @param $statistics
2888 public function countStat(&$statistics, $count) {
2889 $statistics['counts']['rowCount'] = array(
2890 'title' => ts('Row(s) Listed'),
2894 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2895 $statistics['counts']['rowsFound'] = array(
2896 'title' => ts('Total Row(s)'),
2897 'value' => $this->_rowsFound
,
2903 * @param $statistics
2905 public function groupByStat(&$statistics) {
2906 if (!empty($this->_params
['group_bys']) &&
2907 is_array($this->_params
['group_bys']) &&
2908 !empty($this->_params
['group_bys'])
2910 foreach ($this->_columns
as $tableName => $table) {
2911 if (array_key_exists('group_bys', $table)) {
2912 foreach ($table['group_bys'] as $fieldName => $field) {
2913 if (!empty($this->_params
['group_bys'][$fieldName])) {
2914 $combinations[] = $field['title'];
2919 $statistics['groups'][] = array(
2920 'title' => ts('Grouping(s)'),
2921 'value' => implode(' & ', $combinations),
2927 * @param $statistics
2929 public function filterStat(&$statistics) {
2930 foreach ($this->_columns
as $tableName => $table) {
2931 if (array_key_exists('filters', $table)) {
2932 foreach ($table['filters'] as $fieldName => $field) {
2933 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
2934 CRM_Utils_Array
::value('operatorType', $field) !=
2935 CRM_Report_Form
::OP_MONTH
2939 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2940 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2941 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2942 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2943 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2945 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2946 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2948 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2949 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2952 $statistics['filters'][] = array(
2953 'title' => $field['title'],
2954 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2957 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2958 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2960 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2961 $statistics['filters'][] = array(
2962 'title' => $field['title'],
2963 'value' => $pair[$rel],
2968 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2971 $pair = $this->getOperationPair(
2972 CRM_Utils_Array
::value('operatorType', $field),
2975 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2976 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2977 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2978 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
2979 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2981 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
2982 $this->setEntityRefDefaults($field, $tableName);
2983 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
2984 array('id' => $val) +
2985 CRM_Utils_Array
::value('api', $field['attributes'], array()));
2987 foreach ($result['values'] as $v) {
2988 $values[] = $v['label'];
2990 $value = "{$pair[$op]} " . implode(', ', $values);
2992 elseif ($op == 'nll' ||
$op == 'nnll') {
2993 $value = $pair[$op];
2995 elseif (is_array($val) && (!empty($val))) {
2996 $options = CRM_Utils_Array
::value('options', $field, array());
2997 foreach ($val as $key => $valIds) {
2998 if (isset($options[$valIds])) {
2999 $val[$key] = $options[$valIds];
3002 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3003 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3004 $val = implode(', ', $val);
3005 $value = "{$pair[$op]} " . $val;
3007 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3008 isset($field['options']) &&
3009 is_array($field['options']) && !empty($field['options'])
3011 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3012 CRM_Utils_Array
::value($val, $field['options'], $val);
3015 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3019 $statistics['filters'][] = array(
3020 'title' => CRM_Utils_Array
::value('title', $field),
3031 * End post processing.
3033 * @param array|null $rows
3035 public function endPostProcess(&$rows = NULL) {
3036 if ($this->_storeResultSet
) {
3037 $this->_resultSet
= $rows;
3040 if ($this->_outputMode
== 'print' ||
3041 $this->_outputMode
== 'pdf' ||
3045 $content = $this->compileContent();
3046 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3050 if ($this->_sendmail
) {
3051 $config = CRM_Core_Config
::singleton();
3052 $attachments = array();
3054 if ($this->_outputMode
== 'csv') {
3056 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3057 ": {$url}</p>" . '<p>' .
3058 ts('The report is attached as a CSV file.') . '</p>' .
3059 $this->_formValues
['report_footer'];
3061 $csvFullFilename = $config->templateCompileDir
.
3062 CRM_Utils_File
::makeFileName('CiviReport.csv');
3063 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3064 file_put_contents($csvFullFilename, $csvContent);
3065 $attachments[] = array(
3066 'fullPath' => $csvFullFilename,
3067 'mime_type' => 'text/csv',
3068 'cleanName' => 'CiviReport.csv',
3071 if ($this->_outputMode
== 'pdf') {
3072 // generate PDF content
3073 $pdfFullFilename = $config->templateCompileDir
.
3074 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3075 file_put_contents($pdfFullFilename,
3076 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3077 TRUE, array('orientation' => 'landscape')
3080 // generate Email Content
3082 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3083 ": {$url}</p>" . '<p>' .
3084 ts('The report is attached as a PDF file.') . '</p>' .
3085 $this->_formValues
['report_footer'];
3087 $attachments[] = array(
3088 'fullPath' => $pdfFullFilename,
3089 'mime_type' => 'application/pdf',
3090 'cleanName' => 'CiviReport.pdf',
3094 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3095 $this->_outputMode
, $attachments
3098 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3101 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3105 elseif ($this->_outputMode
== 'print') {
3109 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3110 $config = CRM_Core_Config
::singleton();
3111 //get chart image name
3112 $chartImg = $this->_chartId
. '.png';
3113 //get image url path
3115 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3117 $uploadUrl .= $chartImg;
3118 //get image doc path to overwrite
3120 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3121 'openFlashChart/' . $chartImg;
3123 $chart = imagecreatefrompng($uploadUrl);
3124 //convert it into formatted png
3125 header('Content-type: image/png');
3126 //overwrite with same image
3127 imagepng($chart, $uploadImg);
3129 imagedestroy($chart);
3131 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3133 CRM_Utils_System
::civiExit();
3135 elseif ($this->_outputMode
== 'csv') {
3136 CRM_Report_Utils_Report
::export2csv($this, $rows);
3138 elseif ($this->_outputMode
== 'group') {
3139 $group = $this->_params
['groups'];
3140 $this->add2group($group);
3142 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3143 CRM_Report_Form_Instance
::postProcess($this);
3145 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3146 $this->_outputMode
== 'create_report'
3148 $this->_createNew
= TRUE;
3149 CRM_Report_Form_Instance
::postProcess($this);
3154 * Set store result set indicator to TRUE.
3156 * @todo explain what this does
3158 public function storeResultSet() {
3159 $this->_storeResultSet
= TRUE;
3167 public function getResultSet() {
3168 return $this->_resultSet
;
3172 * Use the form name to create the tpl file name.
3176 public function getTemplateFileName() {
3177 $defaultTpl = parent
::getTemplateFileName();
3178 $template = CRM_Core_Smarty
::singleton();
3179 if (!$template->template_exists($defaultTpl)) {
3180 $defaultTpl = 'CRM/Report/Form.tpl';
3186 * Compile the report content.
3187 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3191 public function compileContent() {
3192 $templateFile = $this->getHookedTemplateFileName();
3193 return $this->_formValues
['report_header'] .
3194 CRM_Core_Form
::$_template->fetch($templateFile) .
3195 $this->_formValues
['report_footer'];
3199 public function postProcess() {
3200 // get ready with post process params
3201 $this->beginPostProcess();
3204 $sql = $this->buildQuery();
3206 // build array of result based on column headers. This method also allows
3207 // modifying column headers before using it to build result set i.e $rows.
3209 $this->buildRows($sql, $rows);
3211 // format result set.
3212 $this->formatDisplay($rows);
3214 // assign variables to templates
3215 $this->doTemplateAssignment($rows);
3217 // do print / pdf / instance stuff if needed
3218 $this->endPostProcess($rows);
3222 * @param int $rowCount
3225 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3226 // lets do the pager if in html mode
3227 $this->_limit
= NULL;
3229 // CRM-14115, over-ride row count if rowCount is specified in URL
3230 if ($this->_dashBoardRowCount
) {
3231 $rowCount = $this->_dashBoardRowCount
;
3233 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3234 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3236 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3238 // @todo all http vars should be extracted in the preProcess
3239 // - not randomly in the class
3240 if (!$pageId && !empty($_POST)) {
3241 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3242 $pageId = max((int) $_POST['crmPID_B'], 1);
3244 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3245 $pageId = max((int) $_POST['crmPID'], 1);
3247 unset($_POST['crmPID_B'], $_POST['crmPID']);
3250 $pageId = $pageId ?
$pageId : 1;
3251 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3252 $offset = ($pageId - 1) * $rowCount;
3254 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3255 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3257 $this->_limit
= " LIMIT $offset, $rowCount";
3258 return array($offset, $rowCount);
3260 if ($this->_limitValue
) {
3261 if ($this->_offsetValue
) {
3262 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3265 $this->_limit
= " LIMIT " . $this->_limitValue
;
3271 * @param int $rowCount
3273 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3275 // CRM-14115, over-ride row count if rowCount is specified in URL
3276 if ($this->_dashBoardRowCount
) {
3277 $rowCount = $this->_dashBoardRowCount
;
3280 if ($this->_limit
&& ($this->_limit
!= '')) {
3281 $sql = "SELECT FOUND_ROWS();";
3282 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3284 'total' => $this->_rowsFound
,
3285 'rowCount' => $rowCount,
3286 'status' => ts('Records') . ' %%StatusMessage%%',
3287 'buttonBottom' => 'PagerBottomButton',
3288 'buttonTop' => 'PagerTopButton',
3289 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3292 $pager = new CRM_Utils_Pager($params);
3293 $this->assign_by_ref('pager', $pager);
3294 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3305 public function whereGroupClause($field, $value, $op) {
3307 $smartGroupQuery = "";
3309 $group = new CRM_Contact_DAO_Group();
3310 $group->is_active
= 1;
3312 $smartGroups = array();
3313 while ($group->fetch()) {
3314 if (in_array($group->id
, $this->_params
['gid_value']) &&
3315 $group->saved_search_id
3317 $smartGroups[] = $group->id
;
3321 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3323 $smartGroupQuery = '';
3324 if (!empty($smartGroups)) {
3325 $smartGroups = implode(',', $smartGroups);
3326 $smartGroupQuery = " UNION DISTINCT
3327 SELECT DISTINCT smartgroup_contact.contact_id
3328 FROM civicrm_group_contact_cache smartgroup_contact
3329 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3332 $sqlOp = $this->getSQLOperator($op);
3333 if (!is_array($value)) {
3334 $value = array($value);
3336 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3338 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3339 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3340 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3341 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3342 {$smartGroupQuery} ) ";
3352 public function whereTagClause($field, $value, $op) {
3353 // not using left join in query because if any contact
3354 // belongs to more than one tag, results duplicate
3356 $sqlOp = $this->getSQLOperator($op);
3357 if (!is_array($value)) {
3358 $value = array($value);
3360 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3361 $entity_table = $this->_tagFilterTable
;
3362 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3363 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3364 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3365 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3369 * Generate membership organization clause.
3371 * @param mixed $value
3372 * @param string $op SQL Operator
3376 public function whereMembershipOrgClause($value, $op) {
3377 $sqlOp = $this->getSQLOperator($op);
3378 if (!is_array($value)) {
3379 $value = array($value);
3382 $tmp_membership_org_sql_list = implode(', ', $value);
3383 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3384 SELECT DISTINCT mem.contact_id
3385 FROM civicrm_membership mem
3386 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3387 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3388 WHERE mt.member_of_contact_id IN (" .
3389 $tmp_membership_org_sql_list . ")
3390 AND mt.is_active = '1'
3391 AND mem_status.is_current_member = '1'
3392 AND mem_status.is_active = '1' ) ";
3396 * Generate Membership Type SQL Clause.
3397 * @param mixed $value
3403 public function whereMembershipTypeClause($value, $op) {
3404 $sqlOp = $this->getSQLOperator($op);
3405 if (!is_array($value)) {
3406 $value = array($value);
3409 $tmp_membership_sql_list = implode(', ', $value);
3410 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3411 SELECT DISTINCT mem.contact_id
3412 FROM civicrm_membership mem
3413 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3414 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3415 WHERE mem.membership_type_id IN (" .
3416 $tmp_membership_sql_list . ")
3417 AND mt.is_active = '1'
3418 AND mem_status.is_current_member = '1'
3419 AND mem_status.is_active = '1' ) ";
3423 * @param string $tableAlias
3425 public function buildACLClause($tableAlias = 'contact_a') {
3426 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3430 * @param bool $addFields
3431 * @param array $permCustomGroupIds
3433 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3434 if (empty($this->_customGroupExtends
)) {
3437 if (!is_array($this->_customGroupExtends
)) {
3438 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3440 $customGroupWhere = '';
3441 if (!empty($permCustomGroupIds)) {
3442 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3446 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3447 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3448 FROM civicrm_custom_group cg
3449 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3450 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3452 cg.is_active = 1 AND
3453 cf.is_active = 1 AND
3454 cf.is_searchable = 1
3455 ORDER BY cg.weight, cf.weight";
3456 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3459 while ($customDAO->fetch()) {
3460 if ($customDAO->table_name
!= $curTable) {
3461 $curTable = $customDAO->table_name
;
3462 $curFields = $curFilters = array();
3465 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3466 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3467 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3468 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3475 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3476 $this->_columns
[$curTable][$colKey] = array();
3480 $fieldName = 'custom_' . $customDAO->cf_id
;
3483 // this makes aliasing work in favor
3484 $curFields[$fieldName] = array(
3485 'name' => $customDAO->column_name
,
3486 'title' => $customDAO->label
,
3487 'dataType' => $customDAO->data_type
,
3488 'htmlType' => $customDAO->html_type
,
3491 if ($this->_customGroupFilters
) {
3492 // this makes aliasing work in favor
3493 $curFilters[$fieldName] = array(
3494 'name' => $customDAO->column_name
,
3495 'title' => $customDAO->label
,
3496 'dataType' => $customDAO->data_type
,
3497 'htmlType' => $customDAO->html_type
,
3501 switch ($customDAO->data_type
) {
3504 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3505 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3506 // CRM-6946, show time part for datetime date fields
3507 if ($customDAO->time_format
) {
3508 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3513 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3514 $curFilters[$fieldName]['options'] = array(
3515 '' => ts('- select -'),
3519 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3523 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3524 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3528 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3529 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3533 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3534 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3538 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3540 if (!empty($customDAO->option_group_id
)) {
3541 if (in_array($customDAO->html_type
, array(
3546 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3549 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3551 if ($this->_customGroupFilters
) {
3552 $curFilters[$fieldName]['options'] = array();
3553 $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(
3555 $customDAO->option_group_id
,
3559 while ($ogDAO->fetch()) {
3560 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3562 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3567 case 'StateProvince':
3568 if (in_array($customDAO->html_type
, array(
3569 'Multi-Select State/Province',
3571 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3574 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3576 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3580 if (in_array($customDAO->html_type
, array(
3581 'Multi-Select Country',
3583 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3586 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3588 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3591 case 'ContactReference':
3592 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3593 $curFilters[$fieldName]['name'] = 'display_name';
3594 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3596 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3597 $curFields[$fieldName]['name'] = 'display_name';
3598 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3602 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3603 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3606 if (!array_key_exists('type', $curFields[$fieldName])) {
3607 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3611 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3613 if ($this->_customGroupFilters
) {
3614 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3616 if ($this->_customGroupGroupBy
) {
3617 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3622 public function customDataFrom() {
3623 if (empty($this->_customGroupExtends
)) {
3626 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3628 foreach ($this->_columns
as $table => $prop) {
3629 if (substr($table, 0, 13) == 'civicrm_value' ||
3630 substr($table, 0, 12) == 'custom_value'
3632 $extendsTable = $mapper[$prop['extends']];
3634 // check field is in params
3635 if (!$this->isFieldSelected($prop)) {
3638 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3640 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3642 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3643 // handle for ContactReference
3644 if (array_key_exists('fields', $prop)) {
3645 foreach ($prop['fields'] as $fieldName => $field) {
3646 if (CRM_Utils_Array
::value('dataType', $field) ==
3649 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3651 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3664 public function isFieldSelected($prop) {
3669 if (!empty($this->_params
['fields'])) {
3670 foreach (array_keys($prop['fields']) as $fieldAlias) {
3671 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3672 if ($customFieldId) {
3673 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3677 //might be survey response field.
3678 if (!empty($this->_params
['fields']['survey_response']) &&
3679 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3687 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3688 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3689 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3690 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3697 if (!empty($this->_params
['order_bys'])) {
3698 foreach (array_keys($prop['fields']) as $fieldAlias) {
3699 foreach ($this->_params
['order_bys'] as $orderBy) {
3700 if ($fieldAlias == $orderBy['column'] &&
3701 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3709 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3710 foreach ($prop['filters'] as $fieldAlias => $val) {
3719 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3720 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3721 ||
($attach != 'relative' &&
3722 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3728 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3729 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3740 * Check for empty order_by configurations and remove them; also set
3741 * template to hide them.
3743 * @param array $formValues
3745 public function preProcessOrderBy(&$formValues) {
3746 // Object to show/hide form elements
3747 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3749 $_showHide->addShow('optionField_1');
3751 // Cycle through order_by options; skip any empty ones, and hide them as well
3754 if (!empty($formValues['order_bys'])) {
3755 foreach ($formValues['order_bys'] as $order_by) {
3756 if ($order_by['column'] && $order_by['column'] != '-') {
3757 $_showHide->addShow('optionField_' . $n);
3758 $orderBys[$n] = $order_by;
3763 for ($i = $n; $i <= 5; $i++
) {
3765 $_showHide->addHide('optionField_' . $i);
3769 // overwrite order_by options with modified values
3770 if (!empty($orderBys)) {
3771 $formValues['order_bys'] = $orderBys;
3774 $formValues['order_bys'] = array(1 => array('column' => '-'));
3777 // assign show/hide data to template
3778 $_showHide->addToTemplate();
3782 * Does table name have columns in SELECT clause?
3784 * @param string $tableName
3785 * Name of table (index of $this->_columns array).
3789 public function isTableSelected($tableName) {
3790 return in_array($tableName, $this->selectedTables());
3794 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3795 * (building the array if it's unset)
3800 public function selectedTables() {
3801 if (!$this->_selectedTables
) {
3802 $orderByColumns = array();
3803 if (array_key_exists('order_bys', $this->_params
) &&
3804 is_array($this->_params
['order_bys'])
3806 foreach ($this->_params
['order_bys'] as $orderBy) {
3807 $orderByColumns[] = $orderBy['column'];
3811 foreach ($this->_columns
as $tableName => $table) {
3812 if (array_key_exists('fields', $table)) {
3813 foreach ($table['fields'] as $fieldName => $field) {
3814 if (!empty($field['required']) ||
3815 !empty($this->_params
['fields'][$fieldName])
3817 $this->_selectedTables
[] = $tableName;
3822 if (array_key_exists('order_bys', $table)) {
3823 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3824 if (in_array($orderByName, $orderByColumns)) {
3825 $this->_selectedTables
[] = $tableName;
3830 if (array_key_exists('filters', $table)) {
3831 foreach ($table['filters'] as $filterName => $filter) {
3832 if (!empty($this->_params
["{$filterName}_value"]) ||
3833 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3835 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3838 $this->_selectedTables
[] = $tableName;
3845 return $this->_selectedTables
;
3849 * @deprecated - use getAddressColumns which is a more accurate description
3850 * and also accepts an array of options rather than a long list
3852 * adding address fields to construct function in reports
3854 * @param bool $groupBy
3855 * Add GroupBy? Not appropriate for detail report.
3856 * @param bool $orderBy
3857 * Add GroupBy? Not appropriate for detail report.
3858 * @param bool $filters
3859 * @param array $defaults
3862 * address fields for construct clause
3864 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3865 $addressFields = array(
3866 'civicrm_address' => array(
3867 'dao' => 'CRM_Core_DAO_Address',
3870 'title' => ts('Address Name'),
3871 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3873 'street_address' => array(
3874 'title' => ts('Street Address'),
3875 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3877 'supplemental_address_1' => array(
3878 'title' => ts('Supplementary Address Field 1'),
3879 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3881 'supplemental_address_2' => array(
3882 'title' => ts('Supplementary Address Field 2'),
3883 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3885 'street_number' => array(
3886 'name' => 'street_number',
3887 'title' => ts('Street Number'),
3889 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3891 'street_name' => array(
3892 'name' => 'street_name',
3893 'title' => ts('Street Name'),
3895 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3897 'street_unit' => array(
3898 'name' => 'street_unit',
3899 'title' => ts('Street Unit'),
3901 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3904 'title' => ts('City'),
3905 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3907 'postal_code' => array(
3908 'title' => ts('Postal Code'),
3909 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3911 'postal_code_suffix' => array(
3912 'title' => ts('Postal Code Suffix'),
3913 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3915 'country_id' => array(
3916 'title' => ts('Country'),
3917 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3919 'state_province_id' => array(
3920 'title' => ts('State/Province'),
3921 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3923 'county_id' => array(
3924 'title' => ts('County'),
3925 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3928 'grouping' => 'location-fields',
3933 $addressFields['civicrm_address']['filters'] = array(
3934 'street_number' => array(
3935 'title' => ts('Street Number'),
3937 'name' => 'street_number',
3939 'street_name' => array(
3940 'title' => ts('Street Name'),
3941 'name' => 'street_name',
3942 'operator' => 'like',
3944 'postal_code' => array(
3945 'title' => ts('Postal Code'),
3947 'name' => 'postal_code',
3950 'title' => ts('City'),
3951 'operator' => 'like',
3954 'country_id' => array(
3955 'name' => 'country_id',
3956 'title' => ts('Country'),
3957 'type' => CRM_Utils_Type
::T_INT
,
3958 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3959 'options' => CRM_Core_PseudoConstant
::country(),
3961 'state_province_id' => array(
3962 'name' => 'state_province_id',
3963 'title' => ts('State/Province'),
3964 'type' => CRM_Utils_Type
::T_INT
,
3965 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3966 'options' => array(),
3968 'county_id' => array(
3969 'name' => 'county_id',
3970 'title' => ts('County'),
3971 'type' => CRM_Utils_Type
::T_INT
,
3972 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3973 'options' => array(),
3979 $addressFields['civicrm_address']['order_bys'] = array(
3980 'street_name' => array('title' => ts('Street Name')),
3981 'street_number' => array('title' => 'Odd / Even Street Number'),
3982 'street_address' => NULL,
3984 'postal_code' => NULL,
3989 $addressFields['civicrm_address']['group_bys'] = array(
3990 'street_address' => NULL,
3992 'postal_code' => NULL,
3993 'state_province_id' => array(
3994 'title' => ts('State/Province'),
3996 'country_id' => array(
3997 'title' => ts('Country'),
3999 'county_id' => array(
4000 'title' => ts('County'),
4004 return $addressFields;
4008 * Do AlterDisplay processing on Address Fields.
4018 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
4019 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4020 $entryFound = FALSE;
4022 if (array_key_exists('civicrm_address_country_id', $row)) {
4023 if ($value = $row['civicrm_address_country_id']) {
4024 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4025 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4026 "reset=1&force=1&{$criteriaQueryParams}&" .
4027 "country_id_op=in&country_id_value={$value}",
4028 $this->_absoluteUrl
, $this->_id
4030 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4031 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4038 if (array_key_exists('civicrm_address_county_id', $row)) {
4039 if ($value = $row['civicrm_address_county_id']) {
4040 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4041 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4042 "reset=1&force=1&{$criteriaQueryParams}&" .
4043 "county_id_op=in&county_id_value={$value}",
4044 $this->_absoluteUrl
, $this->_id
4046 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4047 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4053 // handle state province
4054 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4055 if ($value = $row['civicrm_address_state_province_id']) {
4056 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4058 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4059 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4060 $this->_absoluteUrl
, $this->_id
4062 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4063 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4074 * Adjusts dates passed in to YEAR() for fiscal year.
4076 * @param string $fieldName
4080 public function fiscalYearOffset($fieldName) {
4081 $config = CRM_Core_Config
::singleton();
4082 $fy = $config->fiscalYearStart
;
4083 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4084 ($fy['d'] == 1 && $fy['M'] == 1)
4086 return "YEAR( $fieldName )";
4088 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4089 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4093 * Add Address into From Table if required.
4095 public function addAddressFromClause() {
4096 // include address field if address column is to be included
4097 if ((isset($this->_addressField
) &&
4098 $this->_addressField
4100 $this->isTableSelected('civicrm_address')
4103 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4104 ON ({$this->_aliases['civicrm_contact']}.id =
4105 {$this->_aliases['civicrm_address']}.contact_id) AND
4106 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4111 * Add Phone into From Table if required.
4113 public function addPhoneFromClause() {
4114 // include address field if address column is to be included
4115 if ($this->isTableSelected('civicrm_phone')
4118 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4119 ON ({$this->_aliases['civicrm_contact']}.id =
4120 {$this->_aliases['civicrm_phone']}.contact_id) AND
4121 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4126 * Get phone columns to add to array.
4128 * @param array $options
4129 * - prefix Prefix to add to table (in case of more than one instance of the table)
4130 * - prefix_label Label to give columns from this phone table instance
4133 * phone columns definition
4135 public function getPhoneColumns($options = array()) {
4136 $defaultOptions = array(
4138 'prefix_label' => '',
4141 $options = array_merge($defaultOptions, $options);
4144 $options['prefix'] . 'civicrm_phone' => array(
4145 'dao' => 'CRM_Core_DAO_Phone',
4147 $options['prefix'] . 'phone' => array(
4148 'title' => ts($options['prefix_label'] . 'Phone'),
4158 * Get address columns to add to array.
4160 * @param array $options
4161 * - prefix Prefix to add to table (in case of more than one instance of the table)
4162 * - prefix_label Label to give columns from this address table instance
4165 * address columns definition
4167 public function getAddressColumns($options = array()) {
4170 'prefix_label' => '',
4174 'defaults' => array(),
4176 return $this->addAddressFields(
4177 $options['group_by'],
4178 $options['order_by'],
4179 $options['filters'],
4180 $options['defaults']
4185 * @param int $groupID
4187 public function add2group($groupID) {
4188 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4189 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4190 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4192 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4193 $dao = CRM_Core_DAO
::executeQuery($sql);
4195 $contact_ids = array();
4196 // Add resulting contacts to group
4197 while ($dao->fetch()) {
4198 if ($dao->addtogroup_contact_id
) {
4199 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4203 if (!empty($contact_ids)) {
4204 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4205 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4208 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4214 * function used for showing charts on print screen.
4216 public static function uploadChartImage() {
4217 // upload strictly for '.png' images
4218 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4219 if (preg_match('/\.png$/', $name)) {
4221 // POST data is usually string data, but we are passing a RAW .png
4222 // so PHP is a bit confused and $_POST is empty. But it has saved
4223 // the raw bits into $HTTP_RAW_POST_DATA
4225 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4227 // prepare the directory
4228 $config = CRM_Core_Config
::singleton();
4230 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4232 if (!file_exists($defaultPath)) {
4233 mkdir($defaultPath, 0777, TRUE);
4236 // full path to the saved image including filename
4237 $destination = $defaultPath . $name;
4240 $jfh = fopen($destination, 'w') or die("can't open file");
4241 fwrite($jfh, $httpRawPostData);
4243 CRM_Utils_System
::civiExit();
4248 * Apply common settings to entityRef fields.
4250 * @param array $field
4251 * @param string $table
4253 private function setEntityRefDefaults(&$field, $table) {
4254 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4255 $field['attributes'] +
= array(
4256 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4258 'placeholder' => ts('- select -'),