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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 const ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
54 * The id of the report instance
61 * The id of the report template
65 protected $_templateID;
73 protected $_noFields = FALSE;
76 * The set of all columns in the report. An associative array
77 * with column name as the key and attributes as the value
81 protected $_columns = array();
84 * The set of filters in the report
88 protected $_filters = array();
91 * The set of optional columns in the report
95 protected $_options = array();
97 protected $_defaults = array();
100 * By default most reports hide contact id.
101 * Setting this to true makes it available
103 protected $_exposeContactID = TRUE;
106 * Set of statistic fields
110 protected $_statFields = array();
113 * Set of statistics data
117 protected $_statistics = array();
120 * List of fields not to be repeated during display
124 protected $_noRepeats = array();
127 * List of fields not to be displayed
131 protected $_noDisplay = array();
134 * Object type that a custom group extends
138 protected $_customGroupExtends = NULL;
139 protected $_customGroupExtendsJoin = array();
140 protected $_customGroupFilters = TRUE;
141 protected $_customGroupGroupBy = FALSE;
142 protected $_customGroupJoin = 'LEFT JOIN';
147 protected $_tagFilter = FALSE;
150 * specify entity table for tags filter
153 protected $_tagFilterTable = 'civicrm_contact';
156 * build groups filter
160 protected $_groupFilter = FALSE;
167 public $_navigation = array();
169 public $_drilldownReport = array();
172 * An attribute for checkbox/radio form field layout
176 protected $_fourColumnAttribute = array(
177 '</td><td width="25%">',
178 '</td><td width="25%">',
179 '</td><td width="25%">',
183 protected $_force = 1;
185 protected $_params = NULL;
186 protected $_formValues = NULL;
187 protected $_instanceValues = NULL;
189 protected $_instanceForm = FALSE;
190 protected $_criteriaForm = FALSE;
192 protected $_instanceButtonName = NULL;
193 protected $_createNewButtonName = NULL;
194 protected $_printButtonName = NULL;
195 protected $_pdfButtonName = NULL;
196 protected $_csvButtonName = NULL;
197 protected $_groupButtonName = NULL;
198 protected $_chartButtonName = NULL;
199 protected $_csvSupported = TRUE;
200 protected $_add2groupSupported = TRUE;
201 protected $_groups = NULL;
202 protected $_grandFlag = FALSE;
203 protected $_rowsFound = NULL;
204 protected $_selectAliases = array();
205 protected $_rollup = NULL;
210 protected $_aliases = array();
226 protected $_limit = NULL;
229 * This can be set to specify a limit to the number of rows
230 * Since it is currently envisaged as part of the api usage it is only being applied
231 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
232 * of the code (see limit() fn
235 protected $_limitValue = NULL;
238 * This can be set to specify row offset
239 * See notes on _limitValue
242 protected $_offsetValue = NULL;
246 protected $_sections = NULL;
247 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
248 protected $_absoluteUrl = FALSE;
251 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
255 protected $_storeResultSet = FALSE;
258 * When _storeResultSet Flag is set use this var to store result set in form of array
262 protected $_resultSet = array();
265 * To what frequency group-by a date column
269 protected $_groupByDateFreq = array(
271 'YEARWEEK' => 'Week',
272 'QUARTER' => 'Quarter',
277 * Variables to hold the acl inner join and where clause
279 protected $_aclFrom = NULL;
280 protected $_aclWhere = NULL;
283 * Array of DAO tables having columns included in SELECT or ORDER BY clause
287 protected $_selectedTables;
290 * Output mode e.g 'print', 'csv', 'pdf'
293 protected $_outputMode;
295 public $_having = NULL;
296 public $_select = NULL;
297 public $_selectClauses = array();
298 public $_columnHeaders = array();
299 public $_orderBy = NULL;
300 public $_orderByFields = array();
301 public $_orderByArray = array();
302 public $_groupBy = NULL;
303 public $_whereClauses = array();
304 public $_havingClauses = array();
307 * DashBoardRowCount Dashboard row count
310 public $_dashBoardRowCount;
313 * Is this being called without a form controller (ie. the report is being render outside the normal form
314 * - e.g the api is retrieving the rows
317 public $noController = FALSE;
320 * Variable to hold the currency alias
322 protected $_currencyColumn = NULL;
327 protected $_interval;
332 protected $_sendmail;
345 * @var string Report description.
347 public $_description;
350 * @var bool Is an address field selected.
351 * This was intended to determine if the address table should be joined in
352 * The isTableSelected function is now preferred for this purpose
354 protected $_addressField;
357 * @var bool Is an email field selected.
358 * This was intended to determine if the email table should be joined in
359 * The isTableSelected function is now preferred for this purpose
361 protected $_emailField;
364 * @var bool Is a phone field selected.
365 * This was intended to determine if the phone table should be joined in
366 * The isTableSelected function is now preferred for this purpose
368 protected $_phoneField;
371 * @var bool Create new report instance? (or update existing) on save.
373 protected $_createNew;
377 public function __construct() {
378 parent
::__construct();
380 $this->addClass('crm-report-form');
383 if ($this->_tagFilter
) {
384 $this->buildTagFilter();
386 if ($this->_exposeContactID
) {
387 if (array_key_exists('civicrm_contact', $this->_columns
)) {
388 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
390 'title' => 'Contact ID',
396 if ($this->_groupFilter
) {
397 $this->buildGroupFilter();
400 // Get all custom groups
401 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
403 // Get the custom groupIds for which the user has VIEW permission
404 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
405 // and addCustomDataToColumns() will allow access to all custom groups.
406 $permCustomGroupIds = array();
407 if (!CRM_Core_Permission
::check('access all custom data')) {
408 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
409 // do not allow custom data for reports if user doesn't have
410 // permission to access custom data.
411 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
412 $this->_customGroupExtends
= array();
416 // merge custom data columns to _columns list, if any
417 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
419 // add / modify display columns, filters ..etc
420 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
422 //assign currencyColumn variable to tpl
423 $this->assign('currencyColumn', $this->_currencyColumn
);
426 public function preProcessCommon() {
428 = CRM_Utils_Request
::retrieve(
431 CRM_Core_DAO
::$_nullObject
434 $this->_dashBoardRowCount
435 = CRM_Utils_Request
::retrieve(
438 CRM_Core_DAO
::$_nullObject
441 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
443 $this->assign('section', $this->_section
);
444 CRM_Core_Region
::instance('page-header')->add(array(
445 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
447 if (!$this->noController
) {
448 $this->setID($this->get('instanceId'));
451 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
453 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
457 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
458 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
459 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
463 $this->assign('instanceId', $this->_id
);
464 $params = array('id' => $this->_id
);
465 $this->_instanceValues
= array();
466 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
468 $this->_instanceValues
470 if (empty($this->_instanceValues
)) {
471 CRM_Core_Error
::fatal("Report could not be loaded.");
473 $this->_title
= $this->_instanceValues
['title'];
474 if (!empty($this->_instanceValues
['permission']) &&
475 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
476 CRM_Core_Permission
::check('administer Reports')
479 CRM_Utils_System
::permissionDenied();
480 CRM_Utils_System
::civiExit();
483 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
485 $this->_formValues
= unserialize($formValues);
488 $this->_formValues
= NULL;
491 // lets always do a force if reset is found in the url.
492 if (!empty($_REQUEST['reset'])) {
497 $this->assign('mode', 'instance');
499 elseif (!$this->noController
) {
500 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
501 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
502 if (($instanceCount > 0) && $optionValueID) {
503 $this->assign('instanceUrl',
504 CRM_Utils_System
::url('civicrm/report/list',
505 "reset=1&ovid=$optionValueID"
509 if ($optionValueID) {
510 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
514 $this->assign('mode', 'template');
517 // lets display the Report Settings section
518 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
520 // Do not display Report Settings section if administer Reports permission is absent OR
521 // if report instance is reserved and administer reserved reports absent
522 if (!CRM_Core_Permission
::check('administer Reports') ||
523 ($this->_instanceValues
['is_reserved'] &&
524 !CRM_Core_Permission
::check('administer reserved reports'))
526 $this->_instanceForm
= FALSE;
529 $this->assign('criteriaForm', FALSE);
530 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
531 if (CRM_Core_Permission
::check('administer Reports') ||
532 CRM_Core_Permission
::check('access Report Criteria')
534 if (!$this->_instanceValues
['is_reserved'] ||
535 CRM_Core_Permission
::check('administer reserved reports')
537 $this->assign('criteriaForm', TRUE);
538 $this->_criteriaForm
= TRUE;
542 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
543 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
544 $this->_printButtonName
= $this->getButtonName('submit', 'print');
545 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
546 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
547 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
548 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
551 public function addBreadCrumb() {
555 'title' => ts('Report Templates'),
556 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
560 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
563 public function preProcess() {
564 $this->preProcessCommon();
567 $this->addBreadCrumb();
570 foreach ($this->_columns
as $tableName => $table) {
572 if (!isset($table['alias'])) {
573 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
577 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
580 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
582 $daoOrBaoName = NULL;
583 // higher preference to bao object
584 if (array_key_exists('bao', $table)) {
585 $daoOrBaoName = $table['bao'];
586 $expFields = $daoOrBaoName::exportableFields();
588 elseif (array_key_exists('dao', $table)) {
589 $daoOrBaoName = $table['dao'];
590 $expFields = $daoOrBaoName::export();
593 $expFields = array();
596 $doNotCopy = array('required');
598 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
599 foreach ($fieldGroups as $fieldGrp) {
600 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
601 foreach ($table[$fieldGrp] as $fieldName => $field) {
602 // $name is the field name used to reference the BAO/DAO export fields array
603 $name = isset($field['name']) ?
$field['name'] : $fieldName;
605 // Sometimes the field name key in the BAO/DAO export fields array is
606 // different from the actual database field name.
607 // Unset $field['name'] so that actual database field name can be obtained
608 // from the BAO/DAO export fields array.
609 unset($field['name']);
611 if (array_key_exists($name, $expFields)) {
612 foreach ($doNotCopy as $dnc) {
613 // unset the values we don't want to be copied.
614 unset($expFields[$name][$dnc]);
617 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
620 foreach ($expFields[$name] as $property => $val) {
621 if (!array_key_exists($property, $field)) {
622 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
629 if (!empty($field['no_repeat'])) {
630 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
632 if (!empty($field['no_display'])) {
633 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
636 // set alias = table-name, unless already set
637 $alias = isset($field['alias']) ?
$field['alias'] : (
638 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
640 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
642 // set name = fieldName, unless already set
643 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
644 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
647 // set dbAlias = alias.name, unless already set
648 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
649 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
651 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
654 // a few auto fills for filters
655 if ($fieldGrp == 'filters') {
656 // fill operator types
657 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
658 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
659 case CRM_Utils_Type
::T_MONEY
:
660 case CRM_Utils_Type
::T_FLOAT
:
661 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
664 case CRM_Utils_Type
::T_INT
:
665 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
668 case CRM_Utils_Type
::T_DATE
:
669 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
672 case CRM_Utils_Type
::T_BOOLEAN
:
673 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
674 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
675 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
686 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
688 // with multiple options operator-type is generally multi-select
689 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
690 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
692 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
703 // copy filters to a separate handy variable
704 if (array_key_exists('filters', $table)) {
705 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
708 if (array_key_exists('group_bys', $table)) {
709 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
712 if (array_key_exists('fields', $table)) {
713 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
718 $this->setDefaultValues(FALSE);
721 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
722 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
723 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
724 CRM_Report_Utils_Get
::processChart($this->_defaults
);
727 $this->_formValues
= $this->_defaults
;
728 $this->postProcess();
733 * @param bool $freeze
737 public function setDefaultValues($freeze = TRUE) {
738 $freezeGroup = array();
740 // FIXME: generalizing form field naming conventions would reduce
741 // lots of lines below.
742 foreach ($this->_columns
as $tableName => $table) {
743 if (array_key_exists('fields', $table)) {
744 foreach ($table['fields'] as $fieldName => $field) {
745 if (empty($field['no_display'])) {
746 if (isset($field['required'])) {
748 $this->_defaults
['fields'][$fieldName] = 1;
751 // find element object, so that we could use quickform's freeze method
752 // for required elements
753 $obj = $this->getElementFromGroup("fields", $fieldName);
755 $freezeGroup[] = $obj;
759 elseif (isset($field['default'])) {
760 $this->_defaults
['fields'][$fieldName] = $field['default'];
766 if (array_key_exists('group_bys', $table)) {
767 foreach ($table['group_bys'] as $fieldName => $field) {
768 if (isset($field['default'])) {
769 if (!empty($field['frequency'])) {
770 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
772 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
776 if (array_key_exists('filters', $table)) {
777 foreach ($table['filters'] as $fieldName => $field) {
778 if (isset($field['default'])) {
779 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
781 if (is_array($field['default'])) {
782 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
783 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
784 $this->_defaults
["{$fieldName}_relative"] = 0;
787 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
791 $this->_defaults
["{$fieldName}_value"] = $field['default'];
794 //assign default value as "in" for multiselect
795 //operator, To freeze the select element
796 if (CRM_Utils_Array
::value('operatorType', $field) ==
797 CRM_Report_Form
::OP_MULTISELECT
799 $this->_defaults
["{$fieldName}_op"] = 'in';
801 if (CRM_Utils_Array
::value('operatorType', $field) ==
802 CRM_Report_Form
::OP_ENTITYREF
804 $this->_defaults
["{$fieldName}_op"] = 'in';
806 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
807 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
809 $this->_defaults
["{$fieldName}_op"] = 'mhas';
811 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
812 $this->_defaults
["{$fieldName}_op"] = $op;
818 empty($this->_formValues
['order_bys']) &&
819 (array_key_exists('order_bys', $table) &&
820 is_array($table['order_bys']))
822 if (!array_key_exists('order_bys', $this->_defaults
)) {
823 $this->_defaults
['order_bys'] = array();
825 foreach ($table['order_bys'] as $fieldName => $field) {
826 if (!empty($field['default']) ||
!empty($field['default_order']) ||
827 CRM_Utils_Array
::value('default_is_section', $field) ||
828 !empty($field['default_weight'])
831 'column' => $fieldName,
832 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
833 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
836 if (!empty($field['default_weight'])) {
837 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
840 array_unshift($this->_defaults
['order_bys'], $order_by);
846 foreach ($this->_options
as $fieldName => $field) {
847 if (isset($field['default'])) {
848 $this->_defaults
['options'][$fieldName] = $field['default'];
853 if (!empty($this->_submitValues
)) {
854 $this->preProcessOrderBy($this->_submitValues
);
857 $this->preProcessOrderBy($this->_defaults
);
860 // lets finish freezing task here itself
861 if (!empty($freezeGroup)) {
862 foreach ($freezeGroup as $elem) {
867 if ($this->_formValues
) {
868 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
871 if ($this->_instanceValues
) {
872 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
875 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
877 return $this->_defaults
;
881 * @param string $group
882 * @param string $grpFieldName
886 public function getElementFromGroup($group, $grpFieldName) {
887 $eleObj = $this->getElement($group);
888 foreach ($eleObj->_elements
as $index => $obj) {
889 if ($grpFieldName == $obj->_attributes
['name']) {
897 * Setter for $_params
899 * @param array $params
901 public function setParams($params) {
902 $this->_params
= $params;
908 * @param int $instanceID
910 public function setID($instanceID) {
911 $this->_id
= $instanceID;
919 public function setForce($isForce) {
920 $this->_force
= $isForce;
924 * Setter for $_limitValue
926 * @param int $_limitValue
928 public function setLimitValue($_limitValue) {
929 $this->_limitValue
= $_limitValue;
933 * Setter for $_offsetValue
935 * @param int $_offsetValue
937 public function setOffsetValue($_offsetValue) {
938 $this->_offsetValue
= $_offsetValue;
942 * Getter for $_defaultValues
945 public function getDefaultValues() {
946 return $this->_defaults
;
949 public function addColumns() {
952 foreach ($this->_columns
as $tableName => $table) {
953 if (array_key_exists('fields', $table)) {
954 foreach ($table['fields'] as $fieldName => $field) {
956 if (empty($field['no_display'])) {
957 foreach (array('table', 'field') as $var) {
958 if (!empty($
{$var}['grouping'])) {
959 if (!is_array($
{$var}['grouping'])) {
960 $tableName = $
{$var}['grouping'];
963 $tableName = array_keys($
{$var}['grouping']);
964 $tableName = $tableName[0];
965 $groupTitle = array_values($
{$var}['grouping']);
966 $groupTitle = $groupTitle[0];
971 if (!$groupTitle && isset($table['group_title'])) {
972 $groupTitle = $table['group_title'];
975 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
976 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
977 $colGroups[$tableName]['group_title'] = $groupTitle;
980 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
986 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
987 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
989 $this->assign('colGroups', $colGroups);
992 public function addFilters() {
995 foreach ($this->_filters
as $table => $attributes) {
996 foreach ($attributes as $fieldName => $field) {
997 // get ready with option value pair
998 // @ 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
1000 $operations = $this->getOperationPair(
1001 CRM_Utils_Array
::value('operatorType', $field),
1004 $filters[$table][$fieldName] = $field;
1006 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1007 case CRM_Report_Form
::OP_MONTH
:
1008 if (!array_key_exists('options', $field) ||
1009 !is_array($field['options']) ||
empty($field['options'])
1011 // If there's no option list for this filter, define one.
1012 $field['options'] = array(
1014 2 => ts('February'),
1021 9 => ts('September'),
1022 10 => ts('October'),
1023 11 => ts('November'),
1024 12 => ts('December'),
1026 // Add this option list to this column _columns. This is
1027 // required so that filter statistics show properly.
1028 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1030 case CRM_Report_Form
::OP_MULTISELECT
:
1031 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1032 // assume a multi-select field
1033 if (!empty($field['options']) ||
1034 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1036 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1037 if (count($operations) <= 1) {
1040 if ($fieldName == 'state_province_id' ||
1041 $fieldName == 'county_id'
1043 $this->addChainSelect($fieldName . '_value', array(
1050 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1051 'style' => 'min-width:250px',
1052 'class' => 'crm-select2 huge',
1054 'placeholder' => ts('- select -'),
1060 case CRM_Report_Form
::OP_SELECT
:
1061 // assume a select field
1062 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1063 if (!empty($field['options'])) {
1064 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1068 case CRM_Report_Form
::OP_ENTITYREF
:
1069 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1070 $this->setEntityRefDefaults($field, $table);
1071 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1074 case CRM_Report_Form
::OP_DATE
:
1075 // build datetime fields
1076 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1080 case CRM_Report_Form
::OP_DATETIME
:
1081 // build datetime fields
1082 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1086 case CRM_Report_Form
::OP_INT
:
1087 case CRM_Report_Form
::OP_FLOAT
:
1088 // and a min value input box
1089 $this->add('text', "{$fieldName}_min", ts('Min'));
1090 // and a max value input box
1091 $this->add('text', "{$fieldName}_max", ts('Max'));
1093 // default type is string
1094 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1095 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1097 // we need text box for value input
1098 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1103 $this->assign('filters', $filters);
1106 public function addOptions() {
1107 if (!empty($this->_options
)) {
1108 // FIXME: For now lets build all elements as checkboxes.
1109 // Once we clear with the format we can build elements based on type
1112 foreach ($this->_options
as $fieldName => $field) {
1113 if ($field['type'] == 'select') {
1114 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1116 elseif ($field['type'] == 'checkbox') {
1117 $options[$field['title']] = $fieldName;
1118 $this->addCheckBox($fieldName, NULL,
1120 NULL, NULL, NULL, $this->_fourColumnAttribute
1125 $this->assign('otherOptions', $this->_options
);
1128 public function addChartOptions() {
1129 if (!empty($this->_charts
)) {
1130 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1131 $this->assign('charts', $this->_charts
);
1132 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1136 public function addGroupBys() {
1137 $options = $freqElements = array();
1139 foreach ($this->_columns
as $tableName => $table) {
1140 if (array_key_exists('group_bys', $table)) {
1141 foreach ($table['group_bys'] as $fieldName => $field) {
1142 if (!empty($field)) {
1143 $options[$field['title']] = $fieldName;
1144 if (!empty($field['frequency'])) {
1145 $freqElements[$field['title']] = $fieldName;
1151 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1152 NULL, NULL, NULL, $this->_fourColumnAttribute
1154 $this->assign('groupByElements', $options);
1156 foreach ($freqElements as $name) {
1157 $this->addElement('select', "group_bys_freq[$name]",
1158 ts('Frequency'), $this->_groupByDateFreq
1163 public function addOrderBys() {
1165 foreach ($this->_columns
as $tableName => $table) {
1167 // Report developer may define any column to order by; include these as order-by options
1168 if (array_key_exists('order_bys', $table)) {
1169 foreach ($table['order_bys'] as $fieldName => $field) {
1170 if (!empty($field)) {
1171 $options[$fieldName] = $field['title'];
1176 // Add searchable custom fields as order-by options, if so requested
1177 // (These are already indexed, so allowing to order on them is cheap.)
1179 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1180 array_key_exists('extends', $table) && !empty($table['extends'])
1182 foreach ($table['fields'] as $fieldName => $field) {
1183 if (empty($field['no_display'])) {
1184 $options[$fieldName] = $field['title'];
1192 $this->assign('orderByOptions', $options);
1194 if (!empty($options)) {
1196 '-' => ' - none - ',
1198 for ($i = 1; $i <= 5; $i++
) {
1199 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1200 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1201 'ASC' => 'Ascending',
1202 'DESC' => 'Descending',
1204 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1205 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1210 public function buildInstanceAndButtons() {
1211 CRM_Report_Form_Instance
::buildForm($this);
1213 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1215 $this->addElement('submit', $this->_instanceButtonName
, $label);
1216 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1217 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1220 $this->addElement('submit', $this->_createNewButtonName
,
1221 ts('Save a Copy') . '...');
1223 $this->assign('instanceForm', $this->_instanceForm
);
1225 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1226 $this->addElement('submit', $this->_printButtonName
, $label);
1228 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1229 $this->addElement('submit', $this->_pdfButtonName
, $label);
1231 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1233 if ($this->_csvSupported
) {
1234 $this->addElement('submit', $this->_csvButtonName
, $label);
1237 if (CRM_Core_Permission
::check('administer Reports') &&
1238 $this->_add2groupSupported
1240 $this->addElement('select', 'groups', ts('Group'),
1241 array('' => ts('Add Contacts to Group')) +
1242 CRM_Core_PseudoConstant
::nestedGroup(),
1243 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1245 $this->assign('group', TRUE);
1248 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1250 $this->addChartOptions();
1251 $this->addButtons(array(
1254 'name' => ts('Preview Report'),
1255 'isDefault' => TRUE,
1261 public function buildQuickForm() {
1262 $this->addColumns();
1264 $this->addFilters();
1266 $this->addOptions();
1268 $this->addGroupBys();
1270 $this->addOrderBys();
1272 $this->buildInstanceAndButtons();
1274 //add form rule for report
1275 if (is_callable(array(
1279 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1284 * A form rule function to ensure that fields selected in group_by
1285 * (if any) should only be the ones present in display/select fields criteria;
1286 * note: works if and only if any custom field selected in group_by.
1287 * @param array $fields
1288 * @param array $ignoreFields
1292 public function customDataFormRule($fields, $ignoreFields = array()) {
1294 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1295 !empty($fields['group_bys'])
1297 foreach ($this->_columns
as $tableName => $table) {
1298 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1299 substr($tableName, 0, 12) == 'custom_value') &&
1300 !empty($this->_columns
[$tableName]['fields'])
1302 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1303 if (array_key_exists($fieldName, $fields['group_bys']) &&
1304 !array_key_exists($fieldName, $fields['fields'])
1306 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1308 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1309 foreach ($fields['fields'] as $fld => $val) {
1310 if (!array_key_exists($fld, $fields['group_bys']) &&
1311 !in_array($fld, $ignoreFields)
1313 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1325 * Note: $fieldName param allows inheriting class to build operationPairs
1326 * specific to a field.
1327 * @param string $type
1328 * @param string $fieldName
1332 public function getOperationPair($type = "string", $fieldName = NULL) {
1333 // FIXME: At some point we should move these key-val pairs
1334 // to option_group and option_value table.
1336 case CRM_Report_Form
::OP_INT
:
1337 case CRM_Report_Form
::OP_FLOAT
:
1340 'lte' => ts('Is less than or equal to'),
1341 'gte' => ts('Is greater than or equal to'),
1342 'bw' => ts('Is between'),
1343 'eq' => ts('Is equal to'),
1344 'lt' => ts('Is less than'),
1345 'gt' => ts('Is greater than'),
1346 'neq' => ts('Is not equal to'),
1347 'nbw' => ts('Is not between'),
1348 'nll' => ts('Is empty (Null)'),
1349 'nnll' => ts('Is not empty (Null)'),
1353 case CRM_Report_Form
::OP_SELECT
:
1355 'eq' => ts('Is equal to'),
1359 case CRM_Report_Form
::OP_MONTH
:
1360 case CRM_Report_Form
::OP_MULTISELECT
:
1361 case CRM_Report_Form
::OP_ENTITYREF
:
1364 'in' => ts('Is one of'),
1365 'notin' => ts('Is not one of'),
1369 case CRM_Report_Form
::OP_DATE
:
1372 'nll' => ts('Is empty (Null)'),
1373 'nnll' => ts('Is not empty (Null)'),
1377 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1378 // use this operator for the values, concatenated with separator. For e.g if
1379 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1381 'mhas' => ts('Is one of'),
1382 'mnot' => ts('Is not one of'),
1389 'has' => ts('Contains'),
1390 'sw' => ts('Starts with'),
1391 'ew' => ts('Ends with'),
1392 'nhas' => ts('Does not contain'),
1393 'eq' => ts('Is equal to'),
1394 'neq' => ts('Is not equal to'),
1395 'nll' => ts('Is empty (Null)'),
1396 'nnll' => ts('Is not empty (Null)'),
1402 public function buildTagFilter() {
1403 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1404 if (!empty($contactTags)) {
1405 $this->_columns
['civicrm_tag'] = array(
1406 'dao' => 'CRM_Core_DAO_Tag',
1410 'title' => ts('Tag'),
1412 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1413 'options' => $contactTags,
1421 * Adds group filters to _columns (called from _Construct
1423 public function buildGroupFilter() {
1424 $this->_columns
['civicrm_group']['filters'] = array(
1426 'name' => 'group_id',
1427 'title' => ts('Group'),
1428 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1430 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1433 if (empty($this->_columns
['civicrm_group']['dao'])) {
1434 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1436 if (empty($this->_columns
['civicrm_group']['alias'])) {
1437 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1442 * @param string $operator
1446 public function getSQLOperator($operator = "like") {
1447 switch ($operator) {
1480 return 'IS NOT NULL';
1489 * Generate where clause.
1490 * This can be overridden in reports for special treatment of a field
1492 * @param array $field Field specifications
1493 * @param string $op Query operator (not an exact match to sql)
1494 * @param mixed $value
1498 * @return null|string
1500 public function whereClause(&$field, $op, $value, $min, $max) {
1502 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1508 if (($min !== NULL && strlen($min) > 0) ||
1509 ($max !== NULL && strlen($max) > 0)
1511 $min = CRM_Utils_Type
::escape($min, $type);
1512 $max = CRM_Utils_Type
::escape($max, $type);
1516 $clauses[] = "( {$field['dbAlias']} >= $min )";
1519 $clauses[] = "( {$field['dbAlias']} < $min )";
1524 $clauses[] = "( {$field['dbAlias']} <= $max )";
1527 $clauses[] = "( {$field['dbAlias']} > $max )";
1531 if (!empty($clauses)) {
1533 $clause = implode(' AND ', $clauses);
1536 $clause = implode(' OR ', $clauses);
1544 if ($value !== NULL && strlen($value) > 0) {
1545 $value = CRM_Utils_Type
::escape($value, $type);
1546 if (strpos($value, '%') === FALSE) {
1547 $value = "'%{$value}%'";
1550 $value = "'{$value}'";
1552 $sqlOP = $this->getSQLOperator($op);
1553 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1559 if (is_string($value) && strlen($value)) {
1560 $value = explode(',', $value);
1562 if ($value !== NULL && is_array($value) && count($value) > 0) {
1563 $sqlOP = $this->getSQLOperator($op);
1564 if (CRM_Utils_Array
::value('type', $field) ==
1565 CRM_Utils_Type
::T_STRING
1567 //cycle through selections and escape values
1568 foreach ($value as $key => $selection) {
1569 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1572 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1576 // for numerical values
1577 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1580 if ($op == 'notin') {
1581 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1584 $clause = "( " . $clause . " )";
1590 // mhas == multiple has
1591 if ($value !== NULL && count($value) > 0) {
1592 $sqlOP = $this->getSQLOperator($op);
1594 = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) .
1600 // mnot == multiple is not one of
1601 if ($value !== NULL && count($value) > 0) {
1602 $sqlOP = $this->getSQLOperator($op);
1604 = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) .
1605 "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1611 if ($value !== NULL && strlen($value) > 0) {
1612 $value = CRM_Utils_Type
::escape($value, $type);
1613 if (strpos($value, '%') === FALSE) {
1615 $value = "'{$value}%'";
1618 $value = "'%{$value}'";
1622 $value = "'{$value}'";
1624 $sqlOP = $this->getSQLOperator($op);
1625 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1631 $sqlOP = $this->getSQLOperator($op);
1632 $clause = "( {$field['dbAlias']} $sqlOP )";
1636 if ($value !== NULL && strlen($value) > 0) {
1637 if (isset($field['clause'])) {
1638 // FIXME: we not doing escape here. Better solution is to use two
1639 // different types - data-type and filter-type
1640 $clause = $field['clause'];
1643 $value = CRM_Utils_Type
::escape($value, $type);
1644 $sqlOP = $this->getSQLOperator($op);
1645 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1646 $value = "'{$value}'";
1648 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1654 if (!empty($field['group']) && $clause) {
1655 $clause = $this->whereGroupClause($field, $value, $op);
1657 elseif (!empty($field['tag']) && $clause) {
1658 // not using left join in query because if any contact
1659 // belongs to more than one tag, results duplicate
1661 $clause = $this->whereTagClause($field, $value, $op);
1663 elseif (!empty($field['membership_org']) && $clause) {
1664 $clause = $this->whereMembershipOrgClause($value, $op);
1666 elseif (!empty($field['membership_type']) && $clause) {
1667 $clause = $this->whereMembershipTypeClause($value, $op);
1673 * @param string $fieldName
1675 * @param string $from
1678 * @param null $fromTime
1679 * @param null $toTime
1681 * @return null|string
1683 public function dateClause(
1685 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1688 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1689 $sqlOP = $this->getSQLOperator($relative);
1690 return "( {$fieldName} {$sqlOP} )";
1693 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1696 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1697 $clauses[] = "( {$fieldName} >= $from )";
1701 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1702 $clauses[] = "( {$fieldName} <= {$to} )";
1705 if (!empty($clauses)) {
1706 return implode(' AND ', $clauses);
1713 * @todo - could not find any instances where this is called
1715 * @param bool $relative
1716 * @param string $from
1717 * @param string_type $to
1719 * @return string|NULL
1721 public function dateDisplay($relative, $from, $to) {
1722 list($from, $to) = $this->getFromTo($relative, $from, $to);
1725 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1728 $clauses[] = 'Past';
1732 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1735 $clauses[] = 'Today';
1738 if (!empty($clauses)) {
1739 return implode(' - ', $clauses);
1746 * @param bool $relative
1747 * @param string $from
1749 * @param string $fromTime
1750 * @param string $toTime
1754 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1755 if (empty($toTime)) {
1758 //FIX ME not working for relative
1760 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1761 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1762 $from = substr($dateRange['from'], 0, 8);
1763 //Take only Date Part, Sometime Time part is also present in 'to'
1764 $to = substr($dateRange['to'], 0, 8);
1766 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1767 $to = CRM_Utils_Date
::processDate($to, $toTime);
1768 return array($from, $to);
1772 * Alter display of rows.
1774 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1775 * such as rendering contacts as links.
1777 * @param array $rows
1778 * Rows generated by SQL, with an array for each row.
1780 public function alterDisplay(&$rows) {
1786 public function alterCustomDataDisplay(&$rows) {
1787 // custom code to alter rows having custom values
1788 if (empty($this->_customGroupExtends
)) {
1792 $customFieldIds = array();
1793 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1794 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1795 $customFieldIds[$fieldAlias] = $fieldId;
1798 if (empty($customFieldIds)) {
1802 $customFields = $fieldValueMap = array();
1803 $customFieldCols = array(
1811 // skip for type date and ContactReference since date format is already handled
1813 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1814 FROM civicrm_custom_field cf
1815 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1816 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1817 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1818 cg.is_active = 1 AND
1819 cf.is_active = 1 AND
1820 cf.is_searchable = 1 AND
1821 cf.data_type NOT IN ('ContactReference', 'Date') AND
1822 cf.id IN (" . implode(",", $customFieldIds) . ")";
1824 $dao = CRM_Core_DAO
::executeQuery($query);
1825 while ($dao->fetch()) {
1826 foreach ($customFieldCols as $key) {
1827 $customFields[$dao->table_name
. '_custom_' .
1828 $dao->id
][$key] = $dao->$key;
1830 if ($dao->option_group_id
) {
1831 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1836 $entryFound = FALSE;
1837 foreach ($rows as $rowNum => $row) {
1838 foreach ($row as $tableCol => $val) {
1839 if (array_key_exists($tableCol, $customFields)) {
1840 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1845 // skip looking further in rows, if first row itself doesn't
1846 // have the column we need
1855 * @param $customField
1856 * @param $fieldValueMap
1858 * @return float|string|void
1860 public function formatCustomValues($value, $customField, $fieldValueMap) {
1861 if (CRM_Utils_System
::isNull($value)) {
1865 $htmlType = $customField['html_type'];
1867 switch ($customField['data_type']) {
1869 if ($value == '1') {
1870 $retValue = ts('Yes');
1873 $retValue = ts('No');
1878 $retValue = CRM_Utils_System
::formatWikiURL($value);
1890 if ($htmlType == 'Text') {
1891 $retValue = (float) $value;
1895 if ($htmlType == 'Text') {
1896 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1901 if (in_array($htmlType, array(
1908 case 'StateProvince':
1911 switch ($htmlType) {
1912 case 'Multi-Select Country':
1913 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1914 $customData = array();
1915 foreach ($value as $val) {
1917 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1920 $retValue = implode(', ', $customData);
1923 case 'Select Country':
1924 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1927 case 'Select State/Province':
1928 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1931 case 'Multi-Select State/Province':
1932 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1933 $customData = array();
1934 foreach ($value as $val) {
1936 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1939 $retValue = implode(', ', $customData);
1944 case 'Autocomplete-Select':
1945 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1949 case 'AdvMulti-Select':
1950 case 'Multi-Select':
1951 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1952 $customData = array();
1953 foreach ($value as $val) {
1955 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1958 $retValue = implode(', ', $customData);
1976 public function removeDuplicates(&$rows) {
1977 if (empty($this->_noRepeats
)) {
1980 $checkList = array();
1982 foreach ($rows as $key => $list) {
1983 foreach ($list as $colName => $colVal) {
1984 if (array_key_exists($colName, $checkList) &&
1985 $checkList[$colName] == $colVal
1987 $rows[$key][$colName] = "";
1989 if (in_array($colName, $this->_noRepeats
)) {
1990 $checkList[$colName] = $colVal;
1999 * @param bool $subtotal
2001 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2002 foreach ($row as $colName => $colVal) {
2003 if (in_array($colName, $fields)) {
2005 elseif (isset($this->_columnHeaders
[$colName])) {
2007 $row[$colName] = "Subtotal";
2011 unset($row[$colName]);
2022 public function grandTotal(&$rows) {
2023 if (!$this->_rollup ||
($this->_rollup
== '') ||
2024 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2028 $lastRow = array_pop($rows);
2030 foreach ($this->_columnHeaders
as $fld => $val) {
2031 if (!in_array($fld, $this->_statFields
)) {
2032 if (!$this->_grandFlag
) {
2033 $lastRow[$fld] = "Grand Total";
2034 $this->_grandFlag
= TRUE;
2037 $lastRow[$fld] = "";
2042 $this->assign('grandStat', $lastRow);
2048 * @param bool $pager
2050 public function formatDisplay(&$rows, $pager = TRUE) {
2051 // set pager based on if any limit was applied in the query.
2056 // allow building charts if any
2057 if (!empty($this->_params
['charts']) && !empty($rows)) {
2058 $this->buildChart($rows);
2059 $this->assign('chartEnabled', TRUE);
2060 $this->_chartId
= "{$this->_params['charts']}_" .
2061 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2063 $this->assign('chartId', $this->_chartId
);
2066 // unset columns not to be displayed.
2067 foreach ($this->_columnHeaders
as $key => $value) {
2068 if (!empty($value['no_display'])) {
2069 unset($this->_columnHeaders
[$key]);
2073 // unset columns not to be displayed.
2074 if (!empty($rows)) {
2075 foreach ($this->_noDisplay
as $noDisplayField) {
2076 foreach ($rows as $rowNum => $row) {
2077 unset($this->_columnHeaders
[$noDisplayField]);
2082 // build array of section totals
2083 $this->sectionTotals();
2085 // process grand-total row
2086 $this->grandTotal($rows);
2088 // use this method for formatting rows for display purpose.
2089 $this->alterDisplay($rows);
2090 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2092 // use this method for formatting custom rows for display purpose.
2093 $this->alterCustomDataDisplay($rows);
2099 public function buildChart(&$rows) {
2100 // override this method for building charts.
2103 // select() method below has been added recently (v3.3), and many of the report templates might
2104 // still be having their own select() method. We should fix them as and when encountered and move
2105 // towards generalizing the select() method below.
2108 * Generate the SELECT clause and set class variable $_select
2110 public function select() {
2111 $select = $this->_selectAliases
= array();
2113 foreach ($this->_columns
as $tableName => $table) {
2114 if (array_key_exists('fields', $table)) {
2115 foreach ($table['fields'] as $fieldName => $field) {
2116 if ($tableName == 'civicrm_address') {
2117 $this->_addressField
= TRUE;
2119 if ($tableName == 'civicrm_email') {
2120 $this->_emailField
= TRUE;
2122 if ($tableName == 'civicrm_phone') {
2123 $this->_phoneField
= TRUE;
2126 if (!empty($field['required']) ||
2127 !empty($this->_params
['fields'][$fieldName])
2130 // 1. In many cases we want select clause to be built in slightly different way
2131 // for a particular field of a particular type.
2132 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2134 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2135 if ($selectClause) {
2136 $select[] = $selectClause;
2140 // include statistics columns only if set
2141 if (!empty($field['statistics'])) {
2142 foreach ($field['statistics'] as $stat => $label) {
2143 $alias = "{$tableName}_{$fieldName}_{$stat}";
2144 switch (strtolower($stat)) {
2147 $select[] = "$stat({$field['dbAlias']}) as $alias";
2148 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2149 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2150 $this->_statFields
[$label] = $alias;
2151 $this->_selectAliases
[] = $alias;
2155 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2156 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2157 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2158 $this->_statFields
[$label] = $alias;
2159 $this->_selectAliases
[] = $alias;
2162 case 'count_distinct':
2163 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2164 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2165 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2166 $this->_statFields
[$label] = $alias;
2167 $this->_selectAliases
[] = $alias;
2171 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2172 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2173 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2174 $this->_statFields
[$label] = $alias;
2175 $this->_selectAliases
[] = $alias;
2181 $alias = "{$tableName}_{$fieldName}";
2182 $select[] = "{$field['dbAlias']} as $alias";
2183 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2184 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2185 $this->_selectAliases
[] = $alias;
2191 // select for group bys
2192 if (array_key_exists('group_bys', $table)) {
2193 foreach ($table['group_bys'] as $fieldName => $field) {
2195 if ($tableName == 'civicrm_address') {
2196 $this->_addressField
= TRUE;
2198 if ($tableName == 'civicrm_email') {
2199 $this->_emailField
= TRUE;
2201 if ($tableName == 'civicrm_phone') {
2202 $this->_phoneField
= TRUE;
2204 // 1. In many cases we want select clause to be built in slightly different way
2205 // for a particular field of a particular type.
2206 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2208 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2209 if ($selectClause) {
2210 $select[] = $selectClause;
2214 if (!empty($this->_params
['group_bys']) &&
2215 !empty($this->_params
['group_bys'][$fieldName]) &&
2216 !empty($this->_params
['group_bys_freq'])
2218 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2220 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2221 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2222 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2223 $field['title'] = 'Week';
2227 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2228 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2229 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2230 $field['title'] = 'Year';
2234 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2235 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2236 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2237 $field['title'] = 'Month';
2241 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2242 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2243 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2244 $field['title'] = 'Quarter';
2247 // for graphs and charts -
2248 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2249 $this->_interval
= $field['title'];
2250 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2251 = $field['title'] . ' Beginning';
2252 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2253 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2255 // just to make sure these values are transfered to rows.
2256 // since we 'll need them for calculation purpose,
2257 // e.g making subtotals look nicer or graphs
2258 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2259 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2266 $this->_selectClauses
= $select;
2267 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2271 * @param string $tableName
2273 * @param string $fieldName
2278 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2282 public function where() {
2283 $this->storeWhereHavingClauseArray();
2285 if (empty($this->_whereClauses
)) {
2286 $this->_where
= "WHERE ( 1 ) ";
2287 $this->_having
= "";
2290 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2293 if ($this->_aclWhere
) {
2294 $this->_where
.= " AND {$this->_aclWhere} ";
2297 if (!empty($this->_havingClauses
)) {
2298 // use this clause to construct group by clause.
2299 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2304 * Store Where clauses into an array - breaking out this step makes
2305 * over-riding more flexible as the clauses can be used in constructing a
2306 * temp table that may not be part of the final where clause or added
2307 * in other functions
2309 public function storeWhereHavingClauseArray() {
2310 foreach ($this->_columns
as $tableName => $table) {
2311 if (array_key_exists('filters', $table)) {
2312 foreach ($table['filters'] as $fieldName => $field) {
2313 // respect pseudofield to filter spec so fields can be marked as
2314 // not to be handled here
2315 if (!empty($field['pseudofield'])) {
2319 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2320 if (CRM_Utils_Array
::value('operatorType', $field) ==
2321 CRM_Report_Form
::OP_MONTH
2323 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2324 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2325 if (is_array($value) && !empty($value)) {
2327 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2332 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2333 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2334 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2335 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2336 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2337 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2341 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2343 $clause = $this->whereClause($field,
2345 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2346 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2347 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2352 if (!empty($clause)) {
2353 if (!empty($field['having'])) {
2354 $this->_havingClauses
[] = $clause;
2357 $this->_whereClauses
[] = $clause;
2366 public function processReportMode() {
2367 $buttonName = $this->controller
->getButtonName();
2369 $output = CRM_Utils_Request
::retrieve(
2372 CRM_Core_DAO
::$_nullObject
2376 = CRM_Utils_Request
::retrieve(
2379 CRM_Core_DAO
::$_nullObject
2382 $this->_absoluteUrl
= FALSE;
2384 $this->assign('printOnly', FALSE);
2386 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2387 ($this->_sendmail
&& !$output)
2389 $this->assign('printOnly', TRUE);
2391 $this->assign('outputMode', 'print');
2392 $this->_outputMode
= 'print';
2393 if ($this->_sendmail
) {
2394 $this->_absoluteUrl
= TRUE;
2397 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2398 $this->assign('printOnly', TRUE);
2400 $this->assign('outputMode', 'pdf');
2401 $this->_outputMode
= 'pdf';
2402 $this->_absoluteUrl
= TRUE;
2404 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2405 $this->assign('printOnly', TRUE);
2407 $this->assign('outputMode', 'csv');
2408 $this->_outputMode
= 'csv';
2409 $this->_absoluteUrl
= TRUE;
2411 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2412 $this->assign('outputMode', 'group');
2413 $this->_outputMode
= 'group';
2415 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2416 $this->assign('outputMode', 'create_report');
2417 $this->_outputMode
= 'create_report';
2420 $this->assign('outputMode', 'html');
2421 $this->_outputMode
= 'html';
2424 // Get today's date to include in printed reports
2426 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2427 $this->assign('reportDate', $reportDate);
2432 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2434 public function beginPostProcess() {
2435 $this->setParams($this->controller
->exportValues($this->_name
));
2437 if (empty($this->_params
) &&
2440 $this->setParams($this->_formValues
);
2443 // hack to fix params when submitted from dashboard, CRM-8532
2444 // fields array is missing because form building etc is skipped
2445 // in dashboard mode for report
2446 //@todo - this could be done in the dashboard no we have a setter
2447 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2448 $this->setParams($this->_formValues
);
2451 $this->_formValues
= $this->_params
;
2452 if (CRM_Core_Permission
::check('administer Reports') &&
2453 isset($this->_id
) &&
2454 ($this->_instanceButtonName
==
2455 $this->controller
->getButtonName() . '_save' ||
2456 $this->_chartButtonName
== $this->controller
->getButtonName()
2459 $this->assign('updateReportButton', TRUE);
2461 $this->processReportMode();
2462 $this->beginPostProcessCommon();
2466 * BeginPostProcess function run in both report mode and non-report mode (api)
2468 public function beginPostProcessCommon() {
2473 * @param bool $applyLimit
2477 public function buildQuery($applyLimit = TRUE) {
2480 $this->customDataFrom();
2485 // order_by columns not selected for display need to be included in SELECT
2486 $unselectedSectionColumns = $this->unselectedSectionColumns();
2487 foreach ($unselectedSectionColumns as $alias => $section) {
2488 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2491 if ($applyLimit && empty($this->_params
['charts'])) {
2494 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2496 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2500 public function groupBy() {
2501 $groupBys = array();
2502 if (!empty($this->_params
['group_bys']) &&
2503 is_array($this->_params
['group_bys']) &&
2504 !empty($this->_params
['group_bys'])
2506 foreach ($this->_columns
as $tableName => $table) {
2507 if (array_key_exists('group_bys', $table)) {
2508 foreach ($table['group_bys'] as $fieldName => $field) {
2509 if (!empty($this->_params
['group_bys'][$fieldName])) {
2510 $groupBys[] = $field['dbAlias'];
2517 if (!empty($groupBys)) {
2518 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2522 public function orderBy() {
2523 $this->_orderBy
= "";
2524 $this->_sections
= array();
2525 $this->storeOrderByArray();
2526 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2527 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2529 $this->assign('sections', $this->_sections
);
2533 * In some cases other functions want to know which fields are selected for ordering by
2534 * Separating this into a separate function allows it to be called separately from constructing
2535 * the order by clause
2537 public function storeOrderByArray() {
2538 $orderBys = array();
2540 if (!empty($this->_params
['order_bys']) &&
2541 is_array($this->_params
['order_bys']) &&
2542 !empty($this->_params
['order_bys'])
2545 // Process order_bys in user-specified order
2546 foreach ($this->_params
['order_bys'] as $orderBy) {
2547 $orderByField = array();
2548 foreach ($this->_columns
as $tableName => $table) {
2549 if (array_key_exists('order_bys', $table)) {
2550 // For DAO columns defined in $this->_columns
2551 $fields = $table['order_bys'];
2553 elseif (array_key_exists('extends', $table)) {
2554 // For custom fields referenced in $this->_customGroupExtends
2555 $fields = CRM_Utils_Array
::value('fields', $table, array());
2560 if (!empty($fields) && is_array($fields)) {
2561 foreach ($fields as $fieldName => $field) {
2562 if ($fieldName == $orderBy['column']) {
2563 $orderByField = array_merge($field, $orderBy);
2564 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2571 if (!empty($orderByField)) {
2572 $this->_orderByFields
[] = $orderByField;
2573 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2575 // Record any section headers for assignment to the template
2576 if (!empty($orderBy['section'])) {
2577 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2578 $this->_sections
[$orderByField['tplField']] = $orderByField;
2584 $this->_orderByArray
= $orderBys;
2586 $this->assign('sections', $this->_sections
);
2592 public function unselectedSectionColumns() {
2593 $selectColumns = array();
2594 foreach ($this->_columns
as $tableName => $table) {
2595 if (array_key_exists('fields', $table)) {
2596 foreach ($table['fields'] as $fieldName => $field) {
2597 if (!empty($field['required']) ||
2598 !empty($this->_params
['fields'][$fieldName])
2601 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2607 if (is_array($this->_sections
)) {
2608 return array_diff_key($this->_sections
, $selectColumns);
2619 public function buildRows($sql, &$rows) {
2620 $dao = CRM_Core_DAO
::executeQuery($sql);
2621 if (!is_array($rows)) {
2625 // use this method to modify $this->_columnHeaders
2626 $this->modifyColumnHeaders();
2628 $unselectedSectionColumns = $this->unselectedSectionColumns();
2630 while ($dao->fetch()) {
2632 foreach ($this->_columnHeaders
as $key => $value) {
2633 if (property_exists($dao, $key)) {
2634 $row[$key] = $dao->$key;
2638 // section headers not selected for display need to be added to row
2639 foreach ($unselectedSectionColumns as $key => $values) {
2640 if (property_exists($dao, $key)) {
2641 $row[$key] = $dao->$key;
2650 * When "order by" fields are marked as sections, this assigns to the template
2651 * an array of total counts for each section. This data is used by the Smarty
2652 * plugin {sectionTotal}
2654 public function sectionTotals() {
2656 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2657 if (empty($this->_selectAliases
)) {
2661 if (!empty($this->_sections
)) {
2662 // build the query with no LIMIT clause
2663 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2664 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2666 // pull section aliases out of $this->_sections
2667 $sectionAliases = array_keys($this->_sections
);
2670 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2671 $ifnulls[] = "ifnull($alias, '') as $alias";
2674 // Group (un-limited) report by all aliases and get counts. This might
2675 // be done more efficiently when the contents of $sql are known, ie. by
2676 // overriding this method in the report class.
2678 $query = "select " . implode(", ", $ifnulls) .
2679 ", count(*) as ct from ($sql) as subquery group by " .
2680 implode(", ", $sectionAliases);
2682 // initialize array of total counts
2684 $dao = CRM_Core_DAO
::executeQuery($query);
2685 while ($dao->fetch()) {
2687 // let $this->_alterDisplay translate any integer ids to human-readable values.
2688 $rows[0] = $dao->toArray();
2689 $this->alterDisplay($rows);
2692 // add totals for all permutations of section values
2695 $aliasCount = count($sectionAliases);
2696 foreach ($sectionAliases as $alias) {
2697 $values[] = $row[$alias];
2698 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2699 if ($i == $aliasCount) {
2700 // the last alias is the lowest-level section header; use count as-is
2701 $totals[$key] = $dao->ct
;
2704 // other aliases are higher level; roll count into their total
2705 $totals[$key] +
= $dao->ct
;
2709 $this->assign('sectionTotals', $totals);
2713 public function modifyColumnHeaders() {
2714 // use this method to modify $this->_columnHeaders
2720 public function doTemplateAssignment(&$rows) {
2721 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2722 $this->assign_by_ref('rows', $rows);
2723 $this->assign('statistics', $this->statistics($rows));
2727 * override this method to build your own statistics
2732 public function statistics(&$rows) {
2733 $statistics = array();
2735 $count = count($rows);
2737 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2741 $this->countStat($statistics, $count);
2743 $this->groupByStat($statistics);
2745 $this->filterStat($statistics);
2751 * @param $statistics
2754 public function countStat(&$statistics, $count) {
2755 $statistics['counts']['rowCount'] = array(
2756 'title' => ts('Row(s) Listed'),
2760 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2761 $statistics['counts']['rowsFound'] = array(
2762 'title' => ts('Total Row(s)'),
2763 'value' => $this->_rowsFound
,
2769 * @param $statistics
2771 public function groupByStat(&$statistics) {
2772 if (!empty($this->_params
['group_bys']) &&
2773 is_array($this->_params
['group_bys']) &&
2774 !empty($this->_params
['group_bys'])
2776 foreach ($this->_columns
as $tableName => $table) {
2777 if (array_key_exists('group_bys', $table)) {
2778 foreach ($table['group_bys'] as $fieldName => $field) {
2779 if (!empty($this->_params
['group_bys'][$fieldName])) {
2780 $combinations[] = $field['title'];
2785 $statistics['groups'][] = array(
2786 'title' => ts('Grouping(s)'),
2787 'value' => implode(' & ', $combinations),
2793 * @param $statistics
2795 public function filterStat(&$statistics) {
2796 foreach ($this->_columns
as $tableName => $table) {
2797 if (array_key_exists('filters', $table)) {
2798 foreach ($table['filters'] as $fieldName => $field) {
2799 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
2800 CRM_Utils_Array
::value('operatorType', $field) !=
2801 CRM_Report_Form
::OP_MONTH
2805 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2806 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2807 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2808 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2809 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2811 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2812 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2814 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2815 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2818 $statistics['filters'][] = array(
2819 'title' => $field['title'],
2820 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2823 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2824 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2826 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2827 $statistics['filters'][] = array(
2828 'title' => $field['title'],
2829 'value' => $pair[$rel],
2834 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2837 $pair = $this->getOperationPair(
2838 CRM_Utils_Array
::value('operatorType', $field),
2841 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2842 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2843 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2844 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
2845 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2847 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
2848 $this->setEntityRefDefaults($field, $tableName);
2849 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
2850 array('id' => $val) +
2851 CRM_Utils_Array
::value('api', $field['attributes'], array()));
2853 foreach ($result['values'] as $v) {
2854 $values[] = $v['label'];
2856 $value = "{$pair[$op]} " . implode(', ', $values);
2858 elseif ($op == 'nll' ||
$op == 'nnll') {
2859 $value = $pair[$op];
2861 elseif (is_array($val) && (!empty($val))) {
2862 $options = CRM_Utils_Array
::value('options', $field, array());
2863 foreach ($val as $key => $valIds) {
2864 if (isset($options[$valIds])) {
2865 $val[$key] = $options[$valIds];
2868 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
2869 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2870 $val = implode(', ', $val);
2871 $value = "{$pair[$op]} " . $val;
2873 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
2874 isset($field['options']) &&
2875 is_array($field['options']) && !empty($field['options'])
2877 $value = CRM_Utils_Array
::value($op, $pair) . " " .
2878 CRM_Utils_Array
::value($val, $field['options'], $val);
2881 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2885 $statistics['filters'][] = array(
2886 'title' => CRM_Utils_Array
::value('title', $field),
2899 public function endPostProcess(&$rows = NULL) {
2900 if ($this->_storeResultSet
) {
2901 $this->_resultSet
= $rows;
2904 if ($this->_outputMode
== 'print' ||
2905 $this->_outputMode
== 'pdf' ||
2909 $content = $this->compileContent();
2910 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2914 if ($this->_sendmail
) {
2915 $config = CRM_Core_Config
::singleton();
2916 $attachments = array();
2918 if ($this->_outputMode
== 'csv') {
2920 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
2921 ": {$url}</p>" . '<p>' .
2922 ts('The report is attached as a CSV file.') . '</p>' .
2923 $this->_formValues
['report_footer'];
2925 $csvFullFilename = $config->templateCompileDir
.
2926 CRM_Utils_File
::makeFileName('CiviReport.csv');
2927 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2928 file_put_contents($csvFullFilename, $csvContent);
2929 $attachments[] = array(
2930 'fullPath' => $csvFullFilename,
2931 'mime_type' => 'text/csv',
2932 'cleanName' => 'CiviReport.csv',
2935 if ($this->_outputMode
== 'pdf') {
2936 // generate PDF content
2937 $pdfFullFilename = $config->templateCompileDir
.
2938 CRM_Utils_File
::makeFileName('CiviReport.pdf');
2939 file_put_contents($pdfFullFilename,
2940 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2941 TRUE, array('orientation' => 'landscape')
2944 // generate Email Content
2946 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
2947 ": {$url}</p>" . '<p>' .
2948 ts('The report is attached as a PDF file.') . '</p>' .
2949 $this->_formValues
['report_footer'];
2951 $attachments[] = array(
2952 'fullPath' => $pdfFullFilename,
2953 'mime_type' => 'application/pdf',
2954 'cleanName' => 'CiviReport.pdf',
2958 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2959 $this->_outputMode
, $attachments
2962 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2965 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2969 elseif ($this->_outputMode
== 'print') {
2973 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2974 $config = CRM_Core_Config
::singleton();
2975 //get chart image name
2976 $chartImg = $this->_chartId
. '.png';
2977 //get image url path
2979 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
2981 $uploadUrl .= $chartImg;
2982 //get image doc path to overwrite
2984 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
2985 'openFlashChart/' . $chartImg;
2987 $chart = imagecreatefrompng($uploadUrl);
2988 //convert it into formatted png
2989 header('Content-type: image/png');
2990 //overwrite with same image
2991 imagepng($chart, $uploadImg);
2993 imagedestroy($chart);
2995 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2997 CRM_Utils_System
::civiExit();
2999 elseif ($this->_outputMode
== 'csv') {
3000 CRM_Report_Utils_Report
::export2csv($this, $rows);
3002 elseif ($this->_outputMode
== 'group') {
3003 $group = $this->_params
['groups'];
3004 $this->add2group($group);
3006 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3007 CRM_Report_Form_Instance
::postProcess($this);
3009 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3010 $this->_outputMode
== 'create_report'
3012 $this->_createNew
= TRUE;
3013 CRM_Report_Form_Instance
::postProcess($this);
3018 * Set store result set indicator to TRUE
3019 * @todo explain what this does
3021 public function storeResultSet() {
3022 $this->_storeResultSet
= TRUE;
3028 public function getResultSet() {
3029 return $this->_resultSet
;
3033 * Use the form name to create the tpl file name.
3037 public function getTemplateFileName() {
3038 $defaultTpl = parent
::getTemplateFileName();
3039 $template = CRM_Core_Smarty
::singleton();
3040 if (!$template->template_exists($defaultTpl)) {
3041 $defaultTpl = 'CRM/Report/Form.tpl';
3047 * Compile the report content.
3048 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3052 public function compileContent() {
3053 $templateFile = $this->getHookedTemplateFileName();
3054 return $this->_formValues
['report_header'] .
3055 CRM_Core_Form
::$_template->fetch($templateFile) .
3056 $this->_formValues
['report_footer'];
3060 public function postProcess() {
3061 // get ready with post process params
3062 $this->beginPostProcess();
3065 $sql = $this->buildQuery();
3067 // build array of result based on column headers. This method also allows
3068 // modifying column headers before using it to build result set i.e $rows.
3070 $this->buildRows($sql, $rows);
3072 // format result set.
3073 $this->formatDisplay($rows);
3075 // assign variables to templates
3076 $this->doTemplateAssignment($rows);
3078 // do print / pdf / instance stuff if needed
3079 $this->endPostProcess($rows);
3083 * @param int $rowCount
3086 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3087 // lets do the pager if in html mode
3088 $this->_limit
= NULL;
3090 // CRM-14115, over-ride row count if rowCount is specified in URL
3091 if ($this->_dashBoardRowCount
) {
3092 $rowCount = $this->_dashBoardRowCount
;
3094 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3095 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3097 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3099 // @todo all http vars should be extracted in the preProcess
3100 // - not randomly in the class
3101 if (!$pageId && !empty($_POST)) {
3102 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3103 $pageId = max((int) $_POST['crmPID_B'], 1);
3105 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3106 $pageId = max((int) $_POST['crmPID'], 1);
3108 unset($_POST['crmPID_B'], $_POST['crmPID']);
3111 $pageId = $pageId ?
$pageId : 1;
3112 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3113 $offset = ($pageId - 1) * $rowCount;
3115 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3116 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3118 $this->_limit
= " LIMIT $offset, $rowCount";
3119 return array($offset, $rowCount);
3121 if ($this->_limitValue
) {
3122 if ($this->_offsetValue
) {
3123 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3126 $this->_limit
= " LIMIT " . $this->_limitValue
;
3132 * @param int $rowCount
3134 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3136 // CRM-14115, over-ride row count if rowCount is specified in URL
3137 if ($this->_dashBoardRowCount
) {
3138 $rowCount = $this->_dashBoardRowCount
;
3141 if ($this->_limit
&& ($this->_limit
!= '')) {
3142 $sql = "SELECT FOUND_ROWS();";
3143 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3145 'total' => $this->_rowsFound
,
3146 'rowCount' => $rowCount,
3147 'status' => ts('Records') . ' %%StatusMessage%%',
3148 'buttonBottom' => 'PagerBottomButton',
3149 'buttonTop' => 'PagerTopButton',
3150 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3153 $pager = new CRM_Utils_Pager($params);
3154 $this->assign_by_ref('pager', $pager);
3155 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3166 public function whereGroupClause($field, $value, $op) {
3168 $smartGroupQuery = "";
3170 $group = new CRM_Contact_DAO_Group();
3171 $group->is_active
= 1;
3173 $smartGroups = array();
3174 while ($group->fetch()) {
3175 if (in_array($group->id
, $this->_params
['gid_value']) &&
3176 $group->saved_search_id
3178 $smartGroups[] = $group->id
;
3182 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3184 $smartGroupQuery = '';
3185 if (!empty($smartGroups)) {
3186 $smartGroups = implode(',', $smartGroups);
3187 $smartGroupQuery = " UNION DISTINCT
3188 SELECT DISTINCT smartgroup_contact.contact_id
3189 FROM civicrm_group_contact_cache smartgroup_contact
3190 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3193 $sqlOp = $this->getSQLOperator($op);
3194 if (!is_array($value)) {
3195 $value = array($value);
3197 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3199 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3200 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3201 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3202 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3203 {$smartGroupQuery} ) ";
3213 public function whereTagClause($field, $value, $op) {
3214 // not using left join in query because if any contact
3215 // belongs to more than one tag, results duplicate
3217 $sqlOp = $this->getSQLOperator($op);
3218 if (!is_array($value)) {
3219 $value = array($value);
3221 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3222 $entity_table = $this->_tagFilterTable
;
3223 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3224 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3225 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3226 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3230 * Generate membership organization clause.
3232 * @param mixed $value
3233 * @param string $op SQL Operator
3237 public function whereMembershipOrgClause($value, $op) {
3238 $sqlOp = $this->getSQLOperator($op);
3239 if (!is_array($value)) {
3240 $value = array($value);
3243 $tmp_membership_org_sql_list = implode(', ', $value);
3244 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3245 SELECT DISTINCT mem.contact_id
3246 FROM civicrm_membership mem
3247 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3248 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3249 WHERE mt.member_of_contact_id IN (" .
3250 $tmp_membership_org_sql_list . ")
3251 AND mt.is_active = '1'
3252 AND mem_status.is_current_member = '1'
3253 AND mem_status.is_active = '1' ) ";
3257 * Generate Membership Type SQL Clause.
3258 * @param mixed $value
3264 public function whereMembershipTypeClause($value, $op) {
3265 $sqlOp = $this->getSQLOperator($op);
3266 if (!is_array($value)) {
3267 $value = array($value);
3270 $tmp_membership_sql_list = implode(', ', $value);
3271 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3272 SELECT DISTINCT mem.contact_id
3273 FROM civicrm_membership mem
3274 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3275 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3276 WHERE mem.membership_type_id IN (" .
3277 $tmp_membership_sql_list . ")
3278 AND mt.is_active = '1'
3279 AND mem_status.is_current_member = '1'
3280 AND mem_status.is_active = '1' ) ";
3284 * @param string $tableAlias
3286 public function buildACLClause($tableAlias = 'contact_a') {
3287 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3291 * @param bool $addFields
3292 * @param array $permCustomGroupIds
3294 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3295 if (empty($this->_customGroupExtends
)) {
3298 if (!is_array($this->_customGroupExtends
)) {
3299 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3301 $customGroupWhere = '';
3302 if (!empty($permCustomGroupIds)) {
3303 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3307 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3308 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3309 FROM civicrm_custom_group cg
3310 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3311 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3313 cg.is_active = 1 AND
3314 cf.is_active = 1 AND
3315 cf.is_searchable = 1
3316 ORDER BY cg.weight, cf.weight";
3317 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3320 while ($customDAO->fetch()) {
3321 if ($customDAO->table_name
!= $curTable) {
3322 $curTable = $customDAO->table_name
;
3323 $curFields = $curFilters = array();
3326 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3327 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3328 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3329 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3336 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3337 $this->_columns
[$curTable][$colKey] = array();
3341 $fieldName = 'custom_' . $customDAO->cf_id
;
3344 // this makes aliasing work in favor
3345 $curFields[$fieldName] = array(
3346 'name' => $customDAO->column_name
,
3347 'title' => $customDAO->label
,
3348 'dataType' => $customDAO->data_type
,
3349 'htmlType' => $customDAO->html_type
,
3352 if ($this->_customGroupFilters
) {
3353 // this makes aliasing work in favor
3354 $curFilters[$fieldName] = array(
3355 'name' => $customDAO->column_name
,
3356 'title' => $customDAO->label
,
3357 'dataType' => $customDAO->data_type
,
3358 'htmlType' => $customDAO->html_type
,
3362 switch ($customDAO->data_type
) {
3365 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3366 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3367 // CRM-6946, show time part for datetime date fields
3368 if ($customDAO->time_format
) {
3369 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3374 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3375 $curFilters[$fieldName]['options'] = array(
3376 '' => ts('- select -'),
3380 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3384 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3385 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3389 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3390 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3394 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3395 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3399 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3401 if (!empty($customDAO->option_group_id
)) {
3402 if (in_array($customDAO->html_type
, array(
3407 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3410 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3412 if ($this->_customGroupFilters
) {
3413 $curFilters[$fieldName]['options'] = array();
3414 $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(
3416 $customDAO->option_group_id
,
3420 while ($ogDAO->fetch()) {
3421 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3423 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3428 case 'StateProvince':
3429 if (in_array($customDAO->html_type
, array(
3430 'Multi-Select State/Province',
3432 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3435 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3437 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3441 if (in_array($customDAO->html_type
, array(
3442 'Multi-Select Country',
3444 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3447 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3449 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3452 case 'ContactReference':
3453 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3454 $curFilters[$fieldName]['name'] = 'display_name';
3455 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3457 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3458 $curFields[$fieldName]['name'] = 'display_name';
3459 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3463 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3464 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3467 if (!array_key_exists('type', $curFields[$fieldName])) {
3468 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3472 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3474 if ($this->_customGroupFilters
) {
3475 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3477 if ($this->_customGroupGroupBy
) {
3478 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3483 public function customDataFrom() {
3484 if (empty($this->_customGroupExtends
)) {
3487 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3489 foreach ($this->_columns
as $table => $prop) {
3490 if (substr($table, 0, 13) == 'civicrm_value' ||
3491 substr($table, 0, 12) == 'custom_value'
3493 $extendsTable = $mapper[$prop['extends']];
3495 // check field is in params
3496 if (!$this->isFieldSelected($prop)) {
3499 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3501 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3503 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3504 // handle for ContactReference
3505 if (array_key_exists('fields', $prop)) {
3506 foreach ($prop['fields'] as $fieldName => $field) {
3507 if (CRM_Utils_Array
::value('dataType', $field) ==
3510 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3512 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3525 public function isFieldSelected($prop) {
3530 if (!empty($this->_params
['fields'])) {
3531 foreach (array_keys($prop['fields']) as $fieldAlias) {
3532 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3533 if ($customFieldId) {
3534 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3538 //might be survey response field.
3539 if (!empty($this->_params
['fields']['survey_response']) &&
3540 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3548 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3549 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3550 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3551 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3558 if (!empty($this->_params
['order_bys'])) {
3559 foreach (array_keys($prop['fields']) as $fieldAlias) {
3560 foreach ($this->_params
['order_bys'] as $orderBy) {
3561 if ($fieldAlias == $orderBy['column'] &&
3562 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3570 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3571 foreach ($prop['filters'] as $fieldAlias => $val) {
3580 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3581 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3582 ||
($attach != 'relative' &&
3583 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3589 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3590 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3601 * Check for empty order_by configurations and remove them; also set
3602 * template to hide them.
3604 * @param array $formValues
3606 public function preProcessOrderBy(&$formValues) {
3607 // Object to show/hide form elements
3608 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3610 $_showHide->addShow('optionField_1');
3612 // Cycle through order_by options; skip any empty ones, and hide them as well
3615 if (!empty($formValues['order_bys'])) {
3616 foreach ($formValues['order_bys'] as $order_by) {
3617 if ($order_by['column'] && $order_by['column'] != '-') {
3618 $_showHide->addShow('optionField_' . $n);
3619 $orderBys[$n] = $order_by;
3624 for ($i = $n; $i <= 5; $i++
) {
3626 $_showHide->addHide('optionField_' . $i);
3630 // overwrite order_by options with modified values
3631 if (!empty($orderBys)) {
3632 $formValues['order_bys'] = $orderBys;
3635 $formValues['order_bys'] = array(1 => array('column' => '-'));
3638 // assign show/hide data to template
3639 $_showHide->addToTemplate();
3643 * Does table name have columns in SELECT clause?
3645 * @param string $tableName
3646 * Name of table (index of $this->_columns array).
3650 public function isTableSelected($tableName) {
3651 return in_array($tableName, $this->selectedTables());
3655 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3656 * (building the array if it's unset)
3661 public function selectedTables() {
3662 if (!$this->_selectedTables
) {
3663 $orderByColumns = array();
3664 if (array_key_exists('order_bys', $this->_params
) &&
3665 is_array($this->_params
['order_bys'])
3667 foreach ($this->_params
['order_bys'] as $orderBy) {
3668 $orderByColumns[] = $orderBy['column'];
3672 foreach ($this->_columns
as $tableName => $table) {
3673 if (array_key_exists('fields', $table)) {
3674 foreach ($table['fields'] as $fieldName => $field) {
3675 if (!empty($field['required']) ||
3676 !empty($this->_params
['fields'][$fieldName])
3678 $this->_selectedTables
[] = $tableName;
3683 if (array_key_exists('order_bys', $table)) {
3684 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3685 if (in_array($orderByName, $orderByColumns)) {
3686 $this->_selectedTables
[] = $tableName;
3691 if (array_key_exists('filters', $table)) {
3692 foreach ($table['filters'] as $filterName => $filter) {
3693 if (!empty($this->_params
["{$filterName}_value"]) ||
3694 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3696 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3699 $this->_selectedTables
[] = $tableName;
3706 return $this->_selectedTables
;
3710 * @deprecated - use getAddressColumns which is a more accurate description
3711 * and also accepts an array of options rather than a long list
3713 * adding address fields to construct function in reports
3715 * @param bool $groupBy
3716 * Add GroupBy? Not appropriate for detail report.
3717 * @param bool $orderBy
3718 * Add GroupBy? Not appropriate for detail report.
3719 * @param bool $filters
3720 * @param array $defaults
3723 * address fields for construct clause
3725 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3726 $addressFields = array(
3727 'civicrm_address' => array(
3728 'dao' => 'CRM_Core_DAO_Address',
3731 'title' => ts('Address Name'),
3732 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3734 'street_address' => array(
3735 'title' => ts('Street Address'),
3736 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3738 'supplemental_address_1' => array(
3739 'title' => ts('Supplementary Address Field 1'),
3740 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3742 'supplemental_address_2' => array(
3743 'title' => ts('Supplementary Address Field 2'),
3744 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3746 'street_number' => array(
3747 'name' => 'street_number',
3748 'title' => ts('Street Number'),
3750 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3752 'street_name' => array(
3753 'name' => 'street_name',
3754 'title' => ts('Street Name'),
3756 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3758 'street_unit' => array(
3759 'name' => 'street_unit',
3760 'title' => ts('Street Unit'),
3762 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3765 'title' => ts('City'),
3766 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3768 'postal_code' => array(
3769 'title' => ts('Postal Code'),
3770 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3772 'postal_code_suffix' => array(
3773 'title' => ts('Postal Code Suffix'),
3774 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3776 'country_id' => array(
3777 'title' => ts('Country'),
3778 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3780 'state_province_id' => array(
3781 'title' => ts('State/Province'),
3782 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3784 'county_id' => array(
3785 'title' => ts('County'),
3786 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3789 'grouping' => 'location-fields',
3794 $addressFields['civicrm_address']['filters'] = array(
3795 'street_number' => array(
3796 'title' => ts('Street Number'),
3798 'name' => 'street_number',
3800 'street_name' => array(
3801 'title' => ts('Street Name'),
3802 'name' => 'street_name',
3803 'operator' => 'like',
3805 'postal_code' => array(
3806 'title' => ts('Postal Code'),
3808 'name' => 'postal_code',
3811 'title' => ts('City'),
3812 'operator' => 'like',
3815 'country_id' => array(
3816 'name' => 'country_id',
3817 'title' => ts('Country'),
3818 'type' => CRM_Utils_Type
::T_INT
,
3819 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3820 'options' => CRM_Core_PseudoConstant
::country(),
3822 'state_province_id' => array(
3823 'name' => 'state_province_id',
3824 'title' => ts('State/Province'),
3825 'type' => CRM_Utils_Type
::T_INT
,
3826 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3827 'options' => array(),
3829 'county_id' => array(
3830 'name' => 'county_id',
3831 'title' => ts('County'),
3832 'type' => CRM_Utils_Type
::T_INT
,
3833 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3834 'options' => array(),
3840 $addressFields['civicrm_address']['order_bys'] = array(
3841 'street_name' => array('title' => ts('Street Name')),
3842 'street_number' => array('title' => 'Odd / Even Street Number'),
3843 'street_address' => NULL,
3845 'postal_code' => NULL,
3850 $addressFields['civicrm_address']['group_bys'] = array(
3851 'street_address' => NULL,
3853 'postal_code' => NULL,
3854 'state_province_id' => array(
3855 'title' => ts('State/Province'),
3857 'country_id' => array(
3858 'title' => ts('Country'),
3860 'county_id' => array(
3861 'title' => ts('County'),
3865 return $addressFields;
3869 * Do AlterDisplay processing on Address Fields.
3879 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3880 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3881 $entryFound = FALSE;
3883 if (array_key_exists('civicrm_address_country_id', $row)) {
3884 if ($value = $row['civicrm_address_country_id']) {
3885 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3886 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3887 "reset=1&force=1&{$criteriaQueryParams}&" .
3888 "country_id_op=in&country_id_value={$value}",
3889 $this->_absoluteUrl
, $this->_id
3891 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3892 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3899 if (array_key_exists('civicrm_address_county_id', $row)) {
3900 if ($value = $row['civicrm_address_county_id']) {
3901 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3902 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3903 "reset=1&force=1&{$criteriaQueryParams}&" .
3904 "county_id_op=in&county_id_value={$value}",
3905 $this->_absoluteUrl
, $this->_id
3907 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3908 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3914 // handle state province
3915 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3916 if ($value = $row['civicrm_address_state_province_id']) {
3917 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3919 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3920 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3921 $this->_absoluteUrl
, $this->_id
3923 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3924 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3935 * Adjusts dates passed in to YEAR() for fiscal year.
3937 * @param string $fieldName
3941 public function fiscalYearOffset($fieldName) {
3942 $config = CRM_Core_Config
::singleton();
3943 $fy = $config->fiscalYearStart
;
3944 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
3945 ($fy['d'] == 1 && $fy['M'] == 1)
3947 return "YEAR( $fieldName )";
3949 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
3950 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3954 * Add Address into From Table if required.
3956 public function addAddressFromClause() {
3957 // include address field if address column is to be included
3958 if ((isset($this->_addressField
) &&
3959 $this->_addressField
3961 $this->isTableSelected('civicrm_address')
3964 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3965 ON ({$this->_aliases['civicrm_contact']}.id =
3966 {$this->_aliases['civicrm_address']}.contact_id) AND
3967 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3972 * Add Phone into From Table if required.
3974 public function addPhoneFromClause() {
3975 // include address field if address column is to be included
3976 if ($this->isTableSelected('civicrm_phone')
3979 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3980 ON ({$this->_aliases['civicrm_contact']}.id =
3981 {$this->_aliases['civicrm_phone']}.contact_id) AND
3982 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3987 * Get phone columns to add to array.
3989 * @param array $options
3990 * - prefix Prefix to add to table (in case of more than one instance of the table)
3991 * - prefix_label Label to give columns from this phone table instance
3994 * phone columns definition
3996 public function getPhoneColumns($options = array()) {
3997 $defaultOptions = array(
3999 'prefix_label' => '',
4002 $options = array_merge($defaultOptions, $options);
4005 $options['prefix'] . 'civicrm_phone' => array(
4006 'dao' => 'CRM_Core_DAO_Phone',
4008 $options['prefix'] . 'phone' => array(
4009 'title' => ts($options['prefix_label'] . 'Phone'),
4019 * Get address columns to add to array.
4021 * @param array $options
4022 * - prefix Prefix to add to table (in case of more than one instance of the table)
4023 * - prefix_label Label to give columns from this address table instance
4026 * address columns definition
4028 public function getAddressColumns($options = array()) {
4031 'prefix_label' => '',
4035 'defaults' => array(),
4037 return $this->addAddressFields(
4038 $options['group_by'],
4039 $options['order_by'],
4040 $options['filters'],
4041 $options['defaults']
4046 * @param int $groupID
4048 public function add2group($groupID) {
4049 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4050 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4051 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4053 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4054 $dao = CRM_Core_DAO
::executeQuery($sql);
4056 $contact_ids = array();
4057 // Add resulting contacts to group
4058 while ($dao->fetch()) {
4059 if ($dao->addtogroup_contact_id
) {
4060 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4064 if (!empty($contact_ids)) {
4065 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4066 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4069 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4075 * function used for showing charts on print screen.
4077 public static function uploadChartImage() {
4078 // upload strictly for '.png' images
4079 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4080 if (preg_match('/\.png$/', $name)) {
4082 // POST data is usually string data, but we are passing a RAW .png
4083 // so PHP is a bit confused and $_POST is empty. But it has saved
4084 // the raw bits into $HTTP_RAW_POST_DATA
4086 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4088 // prepare the directory
4089 $config = CRM_Core_Config
::singleton();
4091 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4093 if (!file_exists($defaultPath)) {
4094 mkdir($defaultPath, 0777, TRUE);
4097 // full path to the saved image including filename
4098 $destination = $defaultPath . $name;
4101 $jfh = fopen($destination, 'w') or die("can't open file");
4102 fwrite($jfh, $httpRawPostData);
4104 CRM_Utils_System
::civiExit();
4109 * Apply common settings to entityRef fields.
4111 * @param array $field
4112 * @param string $table
4114 private function setEntityRefDefaults(&$field, $table) {
4115 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4116 $field['attributes'] +
= array(
4117 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4119 'placeholder' => ts('- select -'),