3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 CONST ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
53 * The id of the report instance
60 * The id of the report template
64 protected $_templateID;
72 protected $_noFields = FALSE;
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attribues as the value
80 protected $_columns = array();
83 * The set of filters in the report
87 protected $_filters = array();
90 * The set of optional columns in the report
94 protected $_options = array();
96 protected $_defaults = array();
99 * By default most reports hide contact id.
100 * Setting this to true makes it available
102 protected $_exposeContactID = TRUE;
105 * Set of statistic fields
109 protected $_statFields = array();
112 * Set of statistics data
116 protected $_statistics = array();
119 * List of fields not to be repeated during display
123 protected $_noRepeats = array();
126 * List of fields not to be displayed
130 protected $_noDisplay = array();
133 * Object type that a custom group extends
137 protected $_customGroupExtends = NULL;
138 protected $_customGroupExtendsJoin = array();
139 protected $_customGroupFilters = TRUE;
140 protected $_customGroupGroupBy = FALSE;
141 protected $_customGroupJoin = 'LEFT JOIN';
147 protected $_tagFilter = FALSE;
150 * build groups filter
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * An attribute for checkbox/radio form field layout
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
174 protected $_force = 1;
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_grandFlag = FALSE;
194 protected $_rowsFound = NULL;
195 protected $_selectAliases = array();
196 protected $_rollup = NULL;
202 protected $_limit = NULL;
205 * This can be set to specify a limit to the number of rows
206 * Since it is currently envisaged as part of the api usage it is only being applied
207 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
208 * of the code (see limit() fn
211 protected $_limitValue = NULL;
214 * This can be set to specify row offset
215 * See notes on _limitValue
218 protected $_offsetValue = NULL;
219 protected $_sections = NULL;
220 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
221 protected $_absoluteUrl = FALSE;
224 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
228 protected $_storeResultSet = FALSE;
231 * When _storeResultSet Flag is set use this var to store result set in form of array
235 protected $_resultSet = array();
238 * To what frequency group-by a date column
242 protected $_groupByDateFreq = array(
244 'YEARWEEK' => 'Week',
245 'QUARTER' => 'Quarter',
250 * Variables to hold the acl inner join and where clause
252 protected $_aclFrom = NULL;
253 protected $_aclWhere = NULL;
256 * Array of DAO tables having columns included in SELECT or ORDER BY clause
260 protected $_selectedTables;
263 * outputmode e.g 'print', 'csv', 'pdf'
266 protected $_outputMode;
268 public $_having = NULL;
269 public $_select = NULL;
270 public $_selectClauses = array();
271 public $_columnHeaders = array();
272 public $_orderBy = NULL;
273 public $_orderByFields = array();
274 public $_orderByArray = array();
275 public $_groupBy = NULL;
276 public $_whereClauses = array();
277 public $_havingClauses = array();
280 * Is this being called without a form controller (ie. the report is being render outside the normal form
281 * - e.g the api is retrieving the rows
284 public $noController = FALSE;
287 * Variable to hold the currency alias
289 protected $_currencyColumn = NULL;
294 function __construct() {
295 parent
::__construct();
298 if ($this->_tagFilter
) {
299 $this->buildTagFilter();
301 if ($this->_exposeContactID
) {
302 if (array_key_exists('civicrm_contact', $this->_columns
)) {
303 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
305 'title' => 'Contact ID',
311 if ($this->_groupFilter
) {
312 $this->buildGroupFilter();
315 // Get all custom groups
316 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
318 // Get the custom groupIds for which the user has VIEW permission
319 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
320 // and addCustomDataToColumns() will allow access to all custom groups.
321 $permCustomGroupIds = array();
322 if (!CRM_Core_Permission
::check('access all custom data')) {
323 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
324 // do not allow custom data for reports if user doesn't have
325 // permission to access custom data.
326 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
327 $this->_customGroupExtends
= array();
331 // merge custom data columns to _columns list, if any
332 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
334 // add / modify display columns, filters ..etc
335 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
337 //assign currencyColumn variable to tpl
338 $this->assign('currencyColumn', $this->_currencyColumn
);
341 function preProcessCommon() {
343 CRM_Utils_Request
::retrieve(
346 CRM_Core_DAO
::$_nullObject
349 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
351 $this->assign('section', $this->_section
);
352 CRM_Core_Region
::instance('page-header')->add(array(
353 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
355 if(!$this->noController
) {
356 $this->setID($this->get('instanceId'));
359 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
361 $this->setID( CRM_Report_Utils_Report
::getInstanceIDForPath());
365 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
366 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
367 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
371 $this->assign('instanceId', $this->_id
);
372 $params = array('id' => $this->_id
);
373 $this->_instanceValues
= array();
374 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
376 $this->_instanceValues
378 if (empty($this->_instanceValues
)) {
379 CRM_Core_Error
::fatal("Report could not be loaded.");
381 $this->_title
= $this->_instanceValues
['title'];
382 if (!empty($this->_instanceValues
['permission']) &&
383 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
384 CRM_Core_Permission
::check('administer Reports')
387 CRM_Utils_System
::permissionDenied();
388 CRM_Utils_System
::civiExit();
391 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
393 $this->_formValues
= unserialize($formValues);
396 $this->_formValues
= NULL;
399 // lets always do a force if reset is found in the url.
400 if (!empty($_REQUEST['reset'])) {
405 $this->assign('mode', 'instance');
407 elseif (!$this->noController
) {
408 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
409 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
410 if (($instanceCount > 0) && $optionValueID) {
411 $this->assign('instanceUrl',
412 CRM_Utils_System
::url('civicrm/report/list',
413 "reset=1&ovid=$optionValueID"
417 if ($optionValueID) {
418 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
422 $this->assign('mode', 'template');
425 // lets display the Report Settings section
426 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
428 // Do not display Report Settings section if administer Reports permission is absent OR
429 // if report instance is reserved and administer reserved reports absent
430 if (!CRM_Core_Permission
::check('administer Reports') ||
431 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
432 $this->_instanceForm
= FALSE;
435 $this->assign('criteriaForm', FALSE);
436 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
437 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
438 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
439 $this->assign('criteriaForm', TRUE);
440 $this->_criteriaForm
= TRUE;
444 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
445 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
446 $this->_printButtonName
= $this->getButtonName('submit', 'print');
447 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
448 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
449 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
450 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
453 function addBreadCrumb() {
457 'title' => ts('Report Templates'),
458 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
462 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
465 function preProcess() {
466 $this->preProcessCommon();
469 $this->addBreadCrumb();
472 foreach ($this->_columns
as $tableName => $table) {
474 if (!isset($table['alias'])) {
475 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
478 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
481 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
483 $daoOrBaoName = NULL;
484 // higher preference to bao object
485 if (array_key_exists('bao', $table)) {
486 $daoOrBaoName = $table['bao'];
487 $expFields = $daoOrBaoName::exportableFields( );
489 elseif (array_key_exists('dao', $table)){
490 $daoOrBaoName = $table['dao'];
491 $expFields = $daoOrBaoName::export( );
494 $expFields = array();
497 $doNotCopy = array('required');
499 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
500 foreach ($fieldGroups as $fieldGrp) {
501 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
502 foreach ($table[$fieldGrp] as $fieldName => $field) {
503 // $name is the field name used to reference the BAO/DAO export fields array
504 $name = isset($field['name']) ?
$field['name'] : $fieldName;
506 // Sometimes the field name key in the BAO/DAO export fields array is
507 // different from the actual database field name.
508 // Unset $field['name'] so that actual database field name can be obtained
509 // from the BAO/DAO export fields array.
510 unset($field['name']);
512 if (array_key_exists($name, $expFields)) {
513 foreach ($doNotCopy as $dnc) {
514 // unset the values we don't want to be copied.
515 unset($expFields[$name][$dnc]);
518 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
521 foreach ($expFields[$name] as $property => $val) {
522 if (!array_key_exists($property, $field)) {
523 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
530 if (!empty($field['no_repeat'])) {
531 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
533 if (!empty($field['no_display'])) {
534 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
537 // set alias = table-name, unless already set
538 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
539 $this->_columns
[$tableName]['alias'] : $tableName
541 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
543 // set name = fieldName, unless already set
544 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
545 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
548 // set dbAlias = alias.name, unless already set
549 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
550 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
553 // a few auto fills for filters
554 if ($fieldGrp == 'filters') {
555 // fill operator types
556 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
557 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
558 case CRM_Utils_Type
::T_MONEY
:
559 case CRM_Utils_Type
::T_FLOAT
:
560 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
562 case CRM_Utils_Type
::T_INT
:
563 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
565 case CRM_Utils_Type
::T_DATE
:
566 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
568 case CRM_Utils_Type
::T_BOOLEAN
:
569 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
570 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
571 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
572 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
577 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
578 // with multiple options operator-type is generally multi-select
579 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
580 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
582 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
593 // copy filters to a separate handy variable
594 if (array_key_exists('filters', $table)) {
595 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
598 if (array_key_exists('group_bys', $table)) {
599 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
602 if (array_key_exists('fields', $table)) {
603 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
608 $this->setDefaultValues(FALSE);
611 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
612 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
613 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
614 CRM_Report_Utils_Get
::processChart($this->_defaults
);
617 $this->_formValues
= $this->_defaults
;
618 $this->postProcess();
622 function setDefaultValues($freeze = TRUE) {
623 $freezeGroup = array();
625 // FIXME: generalizing form field naming conventions would reduce
626 // lots of lines below.
627 foreach ($this->_columns
as $tableName => $table) {
628 if (array_key_exists('fields', $table)) {
629 foreach ($table['fields'] as $fieldName => $field) {
630 if (empty($field['no_display'])) {
631 if (isset($field['required'])) {
633 $this->_defaults
['fields'][$fieldName] = 1;
636 // find element object, so that we could use quickform's freeze method
637 // for required elements
638 $obj = $this->getElementFromGroup("fields", $fieldName);
640 $freezeGroup[] = $obj;
644 elseif (isset($field['default'])) {
645 $this->_defaults
['fields'][$fieldName] = $field['default'];
651 if (array_key_exists('group_bys', $table)) {
652 foreach ($table['group_bys'] as $fieldName => $field) {
653 if (isset($field['default'])) {
654 if (!empty($field['frequency'])) {
655 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
657 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
661 if (array_key_exists('filters', $table)) {
662 foreach ($table['filters'] as $fieldName => $field) {
663 if (isset($field['default'])) {
664 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
665 if(is_array($field['default'])){
666 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
667 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
668 $this->_defaults
["{$fieldName}_relative"] = 0;
671 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
675 $this->_defaults
["{$fieldName}_value"] = $field['default'];
678 //assign default value as "in" for multiselect
679 //operator, To freeze the select element
680 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT
) {
681 $this->_defaults
["{$fieldName}_op"] = 'in';
683 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
) {
684 $this->_defaults
["{$fieldName}_op"] = 'mhas';
686 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
687 $this->_defaults
["{$fieldName}_op"] = $op;
693 array_key_exists('order_bys', $table) &&
694 is_array($table['order_bys'])
696 if (!array_key_exists('order_bys', $this->_defaults
)) {
697 $this->_defaults
['order_bys'] = array();
699 foreach ($table['order_bys'] as $fieldName => $field) {
700 if (!empty($field['default']) ||
!empty($field['default_order']) ||
701 CRM_Utils_Array
::value('default_is_section', $field) ||
!empty($field['default_weight'])) {
703 'column' => $fieldName,
704 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
705 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
708 if (!empty($field['default_weight'])) {
709 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
712 array_unshift($this->_defaults
['order_bys'], $order_by);
718 foreach ($this->_options
as $fieldName => $field) {
719 if (isset($field['default'])) {
720 $this->_defaults
['options'][$fieldName] = $field['default'];
725 if (!empty($this->_submitValues
)) {
726 $this->preProcessOrderBy($this->_submitValues
);
729 $this->preProcessOrderBy($this->_defaults
);
732 // lets finish freezing task here itself
733 if (!empty($freezeGroup)) {
734 foreach ($freezeGroup as $elem) {
739 if ($this->_formValues
) {
740 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
743 if ($this->_instanceValues
) {
744 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
747 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
749 return $this->_defaults
;
752 function getElementFromGroup($group, $grpFieldName) {
753 $eleObj = $this->getElement($group);
754 foreach ($eleObj->_elements
as $index => $obj) {
755 if ($grpFieldName == $obj->_attributes
['name']) {
763 * Setter for $_params
764 * @param array $params
766 function setParams($params) {
767 $this->_params
= $params;
774 function setID($instanceid) {
775 $this->_id
= $instanceid;
780 * @param boolean $force
782 function setForce($isForce) {
783 $this->_force
= $isForce;
787 * Setter for $_limitValue
788 * @param number $_limitValue
790 function setLimitValue($_limitValue) {
791 $this->_limitValue
= $_limitValue;
795 * Setter for $_offsetValue
796 * @param number $_offsetValue
798 function setOffsetValue($_offsetValue) {
799 $this->_offsetValue
= $_offsetValue;
803 * Getter for $_defaultValues
804 * @return array $_defaultValues
806 function getDefaultValues() {
807 return $this->_defaults
;
810 function addColumns() {
813 foreach ($this->_columns
as $tableName => $table) {
814 if (array_key_exists('fields', $table)) {
815 foreach ($table['fields'] as $fieldName => $field) {
817 if (empty($field['no_display'])) {
818 foreach ( array('table', 'field') as $var) {
819 if (!empty($
{$var}['grouping'])) {
820 if (!is_array($
{$var}['grouping'])) {
821 $tableName = $
{$var}['grouping'];
823 $tableName = array_keys($
{$var}['grouping']);
824 $tableName = $tableName[0];
825 $groupTitle = array_values($
{$var}['grouping']);
826 $groupTitle = $groupTitle[0];
831 if (!$groupTitle && isset($table['group_title'])) {
832 $groupTitle = $table['group_title'];
835 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
836 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
837 $colGroups[$tableName]['group_title'] = $groupTitle;
840 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
846 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
847 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
849 $this->assign('colGroups', $colGroups);
852 function addFilters() {
853 $options = $filters = array();
855 foreach ($this->_filters
as $table => $attributes) {
856 foreach ($attributes as $fieldName => $field) {
857 // get ready with option value pair
858 // @ 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
860 $operations = $this->getOperationPair(
861 CRM_Utils_Array
::value('operatorType', $field),
864 $filters[$table][$fieldName] = $field;
866 switch (CRM_Utils_Array
::value('operatorType', $field)) {
867 case CRM_Report_Form
::OP_MONTH
:
868 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
869 // If there's no option list for this filter, define one.
870 $field['options'] = array(
879 9 => ts('September'),
881 11 => ts('November'),
882 12 => ts('December'),
884 // Add this option list to this column _columns. This is
885 // required so that filter statistics show properly.
886 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
888 case CRM_Report_Form
::OP_MULTISELECT
:
889 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
890 // assume a multi-select field
891 if (!empty($field['options'])) {
892 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
893 if (count($operations) <= 1) {
896 $select = $this->addElement('select', "{$fieldName}_value", NULL,
897 $field['options'], array(
899 'style' => 'min-width:250px',
902 $select->setMultiple(TRUE);
906 case CRM_Report_Form
::OP_SELECT
:
907 // assume a select field
908 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
909 if (!empty($field['options']))
910 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
913 case CRM_Report_Form
::OP_DATE
:
914 // build datetime fields
915 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
919 case CRM_Report_Form
::OP_DATETIME
:
920 // build datetime fields
921 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
925 case CRM_Report_Form
::OP_INT
:
926 case CRM_Report_Form
::OP_FLOAT
:
927 // and a min value input box
928 $this->add('text', "{$fieldName}_min", ts('Min'));
929 // and a max value input box
930 $this->add('text', "{$fieldName}_max", ts('Max'));
932 // default type is string
933 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
934 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
936 // we need text box for value input
937 $this->add('text', "{$fieldName}_value", NULL);
942 $this->assign('filters', $filters);
945 function addOptions() {
946 if (!empty($this->_options
)) {
947 // FIXME: For now lets build all elements as checkboxes.
948 // Once we clear with the format we can build elements based on type
951 foreach ($this->_options
as $fieldName => $field) {
952 if ($field['type'] == 'select') {
953 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
955 else if ($field['type'] == 'checkbox') {
956 $options[$field['title']] = $fieldName;
957 $this->addCheckBox($fieldName, NULL,
959 NULL, NULL, NULL, $this->_fourColumnAttribute
964 $this->assign('otherOptions', $this->_options
);
967 function addChartOptions() {
968 if (!empty($this->_charts
)) {
969 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
970 $this->assign('charts', $this->_charts
);
971 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
975 function addGroupBys() {
976 $options = $freqElements = array();
978 foreach ($this->_columns
as $tableName => $table) {
979 if (array_key_exists('group_bys', $table)) {
980 foreach ($table['group_bys'] as $fieldName => $field) {
981 if (!empty($field)) {
982 $options[$field['title']] = $fieldName;
983 if (!empty($field['frequency'])) {
984 $freqElements[$field['title']] = $fieldName;
990 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
991 NULL, NULL, NULL, $this->_fourColumnAttribute
993 $this->assign('groupByElements', $options);
995 foreach ($freqElements as $name) {
996 $this->addElement('select', "group_bys_freq[$name]",
997 ts('Frequency'), $this->_groupByDateFreq
1002 function addOrderBys() {
1004 foreach ($this->_columns
as $tableName => $table) {
1006 // Report developer may define any column to order by; include these as order-by options
1007 if (array_key_exists('order_bys', $table)) {
1008 foreach ($table['order_bys'] as $fieldName => $field) {
1009 if (!empty($field)) {
1010 $options[$fieldName] = $field['title'];
1015 /* Add searchable custom fields as order-by options, if so requested
1016 * (These are already indexed, so allowing to order on them is cheap.)
1020 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1021 foreach ($table['fields'] as $fieldName => $field) {
1022 if (empty($field['no_display'])) {
1023 $options[$fieldName] = $field['title'];
1031 $this->assign('orderByOptions', $options);
1033 if (!empty($options)) {
1035 '-' => ' - none - ') +
$options;
1036 for ($i = 1; $i <= 5; $i++
) {
1037 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1038 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1039 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1040 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1045 function buildInstanceAndButtons() {
1046 CRM_Report_Form_Instance
::buildForm($this);
1048 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1050 $this->addElement('submit', $this->_instanceButtonName
, $label);
1051 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1052 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1055 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1057 if ($this->_instanceForm
) {
1058 $this->assign('instanceForm', TRUE);
1061 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1062 $this->addElement('submit', $this->_printButtonName
, $label);
1064 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1065 $this->addElement('submit', $this->_pdfButtonName
, $label);
1067 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1069 if ($this->_csvSupported
) {
1070 $this->addElement('submit', $this->_csvButtonName
, $label);
1073 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1074 $this->addElement('select', 'groups', ts('Group'),
1075 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
1077 $this->assign('group', TRUE);
1080 $label = ts('Add These Contacts to Group');
1081 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1083 $this->addChartOptions();
1084 $this->addButtons(array(
1087 'name' => ts('Preview Report'),
1088 'isDefault' => TRUE,
1094 function buildQuickForm() {
1095 $this->addColumns();
1097 $this->addFilters();
1099 $this->addOptions();
1101 $this->addGroupBys();
1103 $this->addOrderBys();
1105 $this->buildInstanceAndButtons();
1107 //add form rule for report
1108 if (is_callable(array(
1109 $this, 'formRule'))) {
1110 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1114 // a formrule function to ensure that fields selected in group_by
1115 // (if any) should only be the ones present in display/select fields criteria;
1116 // note: works if and only if any custom field selected in group_by.
1117 function customDataFormRule($fields, $ignoreFields = array( )) {
1119 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1120 foreach ($this->_columns
as $tableName => $table) {
1121 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1122 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1123 if (array_key_exists($fieldName, $fields['group_bys']) &&
1124 !array_key_exists($fieldName, $fields['fields'])
1126 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1128 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1129 foreach ($fields['fields'] as $fld => $val) {
1130 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1131 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1142 // Note: $fieldName param allows inheriting class to build operationPairs
1143 // specific to a field.
1144 function getOperationPair($type = "string", $fieldName = NULL) {
1145 // FIXME: At some point we should move these key-val pairs
1146 // to option_group and option_value table.
1148 case CRM_Report_Form
::OP_INT
:
1149 case CRM_Report_Form
::OP_FLOAT
:
1151 'lte' => ts('Is less than or equal to'),
1152 'gte' => ts('Is greater than or equal to'),
1153 'bw' => ts('Is between'),
1154 'eq' => ts('Is equal to'),
1155 'lt' => ts('Is less than'),
1156 'gt' => ts('Is greater than'),
1157 'neq' => ts('Is not equal to'),
1158 'nbw' => ts('Is not between'),
1159 'nll' => ts('Is empty (Null)'),
1160 'nnll' => ts('Is not empty (Null)'),
1164 case CRM_Report_Form
::OP_SELECT
:
1166 'eq' => ts('Is equal to'),
1169 case CRM_Report_Form
::OP_MONTH
:
1170 case CRM_Report_Form
::OP_MULTISELECT
:
1172 'in' => ts('Is one of'),
1173 'notin' => ts('Is not one of'),
1177 case CRM_Report_Form
::OP_DATE
:
1179 'nll' => ts('Is empty (Null)'),
1180 'nnll' => ts('Is not empty (Null)'),
1184 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1185 // use this operator for the values, concatenated with separator. For e.g if
1186 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1188 'mhas' => ts('Is one of'),
1189 'mnot' => ts('Is not one of'),
1195 'has' => ts('Contains'),
1196 'sw' => ts('Starts with'),
1197 'ew' => ts('Ends with'),
1198 'nhas' => ts('Does not contain'),
1199 'eq' => ts('Is equal to'),
1200 'neq' => ts('Is not equal to'),
1201 'nll' => ts('Is empty (Null)'),
1202 'nnll' => ts('Is not empty (Null)'),
1207 function buildTagFilter() {
1208 $contactTags = CRM_Core_BAO_Tag
::getTags();
1209 if (!empty($contactTags)) {
1210 $this->_columns
['civicrm_tag'] = array(
1211 'dao' => 'CRM_Core_DAO_Tag',
1217 'title' => ts('Tag'),
1219 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1220 'options' => $contactTags,
1228 * Adds group filters to _columns (called from _Constuct
1230 function buildGroupFilter() {
1231 $this->_columns
['civicrm_group']['filters'] = array(
1234 'name' => 'group_id',
1235 'title' => ts('Group'),
1236 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1238 'options' => CRM_Core_PseudoConstant
::group(),
1241 if (empty($this->_columns
['civicrm_group']['dao'])) {
1242 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1244 if (empty($this->_columns
['civicrm_group']['alias'])) {
1245 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1249 function getSQLOperator($operator = "like") {
1250 switch ($operator) {
1283 return 'IS NOT NULL';
1291 function whereClause(&$field, $op,
1295 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1301 if (($min !== NULL && strlen($min) > 0) ||
1302 ($max !== NULL && strlen($max) > 0)
1304 $min = CRM_Utils_Type
::escape($min, $type);
1305 $max = CRM_Utils_Type
::escape($max, $type);
1309 $clauses[] = "( {$field['dbAlias']} >= $min )";
1312 $clauses[] = "( {$field['dbAlias']} < $min )";
1317 $clauses[] = "( {$field['dbAlias']} <= $max )";
1320 $clauses[] = "( {$field['dbAlias']} > $max )";
1324 if (!empty($clauses)) {
1326 $clause = implode(' AND ', $clauses);
1329 $clause = implode(' OR ', $clauses);
1337 if ($value !== NULL && strlen($value) > 0) {
1338 $value = CRM_Utils_Type
::escape($value, $type);
1339 if (strpos($value, '%') === FALSE) {
1340 $value = "'%{$value}%'";
1343 $value = "'{$value}'";
1345 $sqlOP = $this->getSQLOperator($op);
1346 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1352 if ($value !== NULL && is_array($value) && count($value) > 0) {
1353 $sqlOP = $this->getSQLOperator($op);
1354 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1355 //cycle through selections and esacape values
1356 foreach ($value as $key => $selection) {
1357 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1359 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1362 // for numerical values
1363 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1365 if ($op == 'notin') {
1366 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1369 $clause = "( " . $clause . " )";
1375 // mhas == multiple has
1376 if ($value !== NULL && count($value) > 0) {
1377 $sqlOP = $this->getSQLOperator($op);
1378 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1383 // mnot == multiple is not one of
1384 if ($value !== NULL && count($value) > 0) {
1385 $sqlOP = $this->getSQLOperator($op);
1386 $clause = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1392 if ($value !== NULL && strlen($value) > 0) {
1393 $value = CRM_Utils_Type
::escape($value, $type);
1394 if (strpos($value, '%') === FALSE) {
1396 $value = "'{$value}%'";
1399 $value = "'%{$value}'";
1403 $value = "'{$value}'";
1405 $sqlOP = $this->getSQLOperator($op);
1406 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1412 $sqlOP = $this->getSQLOperator($op);
1413 $clause = "( {$field['dbAlias']} $sqlOP )";
1417 if ($value !== NULL && strlen($value) > 0) {
1418 if (isset($field['clause'])) {
1419 // FIXME: we not doing escape here. Better solution is to use two
1420 // different types - data-type and filter-type
1421 $clause = $field['clause'];
1424 $value = CRM_Utils_Type
::escape($value, $type);
1425 $sqlOP = $this->getSQLOperator($op);
1426 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1427 $value = "'{$value}'";
1429 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1435 if (!empty($field['group']) && $clause) {
1436 $clause = $this->whereGroupClause($field, $value, $op);
1438 elseif (!empty($field['tag']) && $clause) {
1439 // not using left join in query because if any contact
1440 // belongs to more than one tag, results duplicate
1442 $clause = $this->whereTagClause($field, $value, $op);
1448 function dateClause($fieldName,
1449 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1452 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1453 $sqlOP = $this->getSQLOperator($relative);
1454 return "( {$fieldName} {$sqlOP} )";
1457 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1460 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1461 $clauses[] = "( {$fieldName} >= $from )";
1465 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1466 $clauses[] = "( {$fieldName} <= {$to} )";
1469 if (!empty($clauses)) {
1470 return implode(' AND ', $clauses);
1476 * @todo - could not find any instances where this is called
1477 * @param unknown_type $relative
1478 * @param String $from
1479 * @param String_type $to
1480 * @return string|NULL
1482 function dateDisplay($relative, $from, $to) {
1483 list($from, $to) = $this->getFromTo($relative, $from, $to);
1486 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1489 $clauses[] = 'Past';
1493 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1496 $clauses[] = 'Today';
1499 if (!empty($clauses)) {
1500 return implode(' - ', $clauses);
1506 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1507 if (empty($totime)) {
1510 //FIX ME not working for relative
1512 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1513 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1514 $from = substr($dateRange['from'], 0, 8);
1515 //Take only Date Part, Sometime Time part is also present in 'to'
1516 $to = substr($dateRange['to'], 0, 8);
1518 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1519 $to = CRM_Utils_Date
::processDate($to, $totime);
1520 return array($from, $to);
1523 function alterDisplay(&$rows) {
1524 // custom code to alter rows
1527 function alterCustomDataDisplay(&$rows) {
1528 // custom code to alter rows having custom values
1529 if (empty($this->_customGroupExtends
)) {
1533 $customFieldIds = array();
1534 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1535 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1536 $customFieldIds[$fieldAlias] = $fieldId;
1539 if (empty($customFieldIds)) {
1543 $customFields = $fieldValueMap = array();
1544 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1546 // skip for type date and ContactReference since date format is already handled
1548 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1549 FROM civicrm_custom_field cf
1550 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1551 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1552 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1553 cg.is_active = 1 AND
1554 cf.is_active = 1 AND
1555 cf.is_searchable = 1 AND
1556 cf.data_type NOT IN ('ContactReference', 'Date') AND
1557 cf.id IN (" . implode(",", $customFieldIds) . ")";
1559 $dao = CRM_Core_DAO
::executeQuery($query);
1560 while ($dao->fetch()) {
1561 foreach ($customFieldCols as $key) {
1562 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1564 if ($dao->option_group_id
) {
1565 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1570 $entryFound = FALSE;
1571 foreach ($rows as $rowNum => $row) {
1572 foreach ($row as $tableCol => $val) {
1573 if (array_key_exists($tableCol, $customFields)) {
1574 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1579 // skip looking further in rows, if first row itself doesn't
1580 // have the column we need
1587 function formatCustomValues($value, $customField, $fieldValueMap) {
1588 if (CRM_Utils_System
::isNull($value)) {
1592 $htmlType = $customField['html_type'];
1594 switch ($customField['data_type']) {
1596 if ($value == '1') {
1597 $retValue = ts('Yes');
1600 $retValue = ts('No');
1605 $retValue = CRM_Utils_System
::formatWikiURL($value);
1617 if ($htmlType == 'Text') {
1618 $retValue = (float)$value;
1622 if ($htmlType == 'Text') {
1632 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1637 if (in_array($htmlType, array(
1638 'Text', 'TextArea'))) {
1642 case 'StateProvince':
1645 switch ($htmlType) {
1646 case 'Multi-Select Country':
1647 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1648 $customData = array();
1649 foreach ($value as $val) {
1651 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1654 $retValue = implode(', ', $customData);
1657 case 'Select Country':
1658 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1661 case 'Select State/Province':
1662 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1665 case 'Multi-Select State/Province':
1666 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1667 $customData = array();
1668 foreach ($value as $val) {
1670 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1673 $retValue = implode(', ', $customData);
1678 case 'Autocomplete-Select':
1679 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1683 case 'AdvMulti-Select':
1684 case 'Multi-Select':
1685 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1686 $customData = array();
1687 foreach ($value as $val) {
1689 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1692 $retValue = implode(', ', $customData);
1707 function removeDuplicates(&$rows) {
1708 if (empty($this->_noRepeats
)) {
1711 $checkList = array();
1713 foreach ($rows as $key => $list) {
1714 foreach ($list as $colName => $colVal) {
1715 if (array_key_exists($colName, $checkList) &&
1716 $checkList[$colName] == $colVal) {
1717 $rows[$key][$colName] = "";
1719 if (in_array($colName, $this->_noRepeats
)) {
1720 $checkList[$colName] = $colVal;
1726 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1727 foreach ($row as $colName => $colVal) {
1728 if (in_array($colName, $fields)) {
1729 $row[$colName] = $row[$colName];
1731 elseif (isset($this->_columnHeaders
[$colName])) {
1733 $row[$colName] = "Subtotal";
1737 unset($row[$colName]);
1743 function grandTotal(&$rows) {
1744 if (!$this->_rollup ||
($this->_rollup
== '') ||
1745 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1749 $lastRow = array_pop($rows);
1751 foreach ($this->_columnHeaders
as $fld => $val) {
1752 if (!in_array($fld, $this->_statFields
)) {
1753 if (!$this->_grandFlag
) {
1754 $lastRow[$fld] = "Grand Total";
1755 $this->_grandFlag
= TRUE;
1758 $lastRow[$fld] = "";
1763 $this->assign('grandStat', $lastRow);
1767 function formatDisplay(&$rows, $pager = TRUE) {
1768 // set pager based on if any limit was applied in the query.
1773 // allow building charts if any
1774 if (!empty($this->_params
['charts']) && !empty($rows)) {
1775 $this->buildChart($rows);
1776 $this->assign('chartEnabled', TRUE);
1777 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1778 $this->assign('chartId', $this->_chartId
);
1781 // unset columns not to be displayed.
1782 foreach ($this->_columnHeaders
as $key => $value) {
1783 if (!empty($value['no_display'])) {
1784 unset($this->_columnHeaders
[$key]);
1788 // unset columns not to be displayed.
1789 if (!empty($rows)) {
1790 foreach ($this->_noDisplay
as $noDisplayField) {
1791 foreach ($rows as $rowNum => $row) {
1792 unset($this->_columnHeaders
[$noDisplayField]);
1797 // build array of section totals
1798 $this->sectionTotals();
1800 // process grand-total row
1801 $this->grandTotal($rows);
1803 // use this method for formatting rows for display purpose.
1804 $this->alterDisplay($rows);
1805 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1807 // use this method for formatting custom rows for display purpose.
1808 $this->alterCustomDataDisplay($rows);
1811 function buildChart(&$rows) {
1812 // override this method for building charts.
1815 // select() method below has been added recently (v3.3), and many of the report templates might
1816 // still be having their own select() method. We should fix them as and when encountered and move
1817 // towards generalizing the select() method below.
1819 $select = $this->_selectAliases
= array();
1821 foreach ($this->_columns
as $tableName => $table) {
1822 if (array_key_exists('fields', $table)) {
1823 foreach ($table['fields'] as $fieldName => $field) {
1824 if ($tableName == 'civicrm_address') {
1825 $this->_addressField
= TRUE;
1827 if ($tableName == 'civicrm_email') {
1828 $this->_emailField
= TRUE;
1830 if ($tableName == 'civicrm_phone') {
1831 $this->_phoneField
= TRUE;
1834 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
1836 // 1. In many cases we want select clause to be built in slightly different way
1837 // for a particular field of a particular type.
1838 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1840 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1841 if ($selectClause) {
1842 $select[] = $selectClause;
1846 // include statistics columns only if set
1847 if (!empty($field['statistics'])) {
1848 foreach ($field['statistics'] as $stat => $label) {
1849 $alias = "{$tableName}_{$fieldName}_{$stat}";
1850 switch (strtolower($stat)) {
1853 $select[] = "$stat({$field['dbAlias']}) as $alias";
1854 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1855 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1856 $this->_statFields
[$label] = $alias;
1857 $this->_selectAliases
[] = $alias;
1861 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1862 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1863 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1864 $this->_statFields
[$label] = $alias;
1865 $this->_selectAliases
[] = $alias;
1868 case 'count_distinct':
1869 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1870 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1871 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1872 $this->_statFields
[$label] = $alias;
1873 $this->_selectAliases
[] = $alias;
1877 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1878 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1879 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1880 $this->_statFields
[$label] = $alias;
1881 $this->_selectAliases
[] = $alias;
1887 $alias = "{$tableName}_{$fieldName}";
1888 $select[] = "{$field['dbAlias']} as $alias";
1889 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1890 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1891 $this->_selectAliases
[] = $alias;
1897 // select for group bys
1898 if (array_key_exists('group_bys', $table)) {
1899 foreach ($table['group_bys'] as $fieldName => $field) {
1901 if ($tableName == 'civicrm_address') {
1902 $this->_addressField
= TRUE;
1904 if ($tableName == 'civicrm_email') {
1905 $this->_emailField
= TRUE;
1907 if ($tableName == 'civicrm_phone') {
1908 $this->_phoneField
= TRUE;
1910 // 1. In many cases we want select clause to be built in slightly different way
1911 // for a particular field of a particular type.
1912 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1914 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1915 if ($selectClause) {
1916 $select[] = $selectClause;
1920 if (!empty($this->_params
['group_bys']) && !empty($this->_params
['group_bys'][$fieldName]) && !empty($this->_params
['group_bys_freq'])) {
1921 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1923 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1924 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1925 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1926 $field['title'] = 'Week';
1930 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1931 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1932 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1933 $field['title'] = 'Year';
1937 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1938 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1939 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1940 $field['title'] = 'Month';
1944 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1945 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1946 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1947 $field['title'] = 'Quarter';
1950 // for graphs and charts -
1951 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
1952 $this->_interval
= $field['title'];
1953 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1954 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1955 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1957 // just to make sure these values are transfered to rows.
1958 // since we 'll need them for calculation purpose,
1959 // e.g making subtotals look nicer or graphs
1960 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1961 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1968 $this->_selectClauses
= $select;
1969 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1972 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1977 $this->storeWhereHavingClauseArray();
1979 if (empty($this->_whereClauses
)) {
1980 $this->_where
= "WHERE ( 1 ) ";
1981 $this->_having
= "";
1984 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1987 if ($this->_aclWhere
) {
1988 $this->_where
.= " AND {$this->_aclWhere} ";
1991 if (!empty($this->_havingClauses
)) {
1992 // use this clause to construct group by clause.
1993 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1998 * Store Where clauses into an array - breaking out this step makes
1999 * over-riding more flexible as the clauses can be used in constructing a
2000 * temp table that may not be part of the final where clause or added
2001 * in other functions
2003 function storeWhereHavingClauseArray(){
2004 foreach ($this->_columns
as $tableName => $table) {
2005 if (array_key_exists('filters', $table)) {
2006 foreach ($table['filters'] as $fieldName => $field) {
2007 // respect pseudofield to filter spec so fields can be marked as
2008 // not to be handled here
2009 if(!empty($field['pseudofield'])){
2013 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2014 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2015 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2016 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2017 if (is_array($value) && !empty($value)) {
2018 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2022 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2023 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2024 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2025 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2026 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2027 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2031 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2033 $clause = $this->whereClause($field,
2035 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2036 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2037 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2042 if (!empty($clause)) {
2043 if (!empty($field['having'])) {
2044 $this->_havingClauses
[] = $clause;
2047 $this->_whereClauses
[] = $clause;
2055 function processReportMode() {
2056 $buttonName = $this->controller
->getButtonName();
2058 $output = CRM_Utils_Request
::retrieve(
2061 CRM_Core_DAO
::$_nullObject
2065 CRM_Utils_Request
::retrieve(
2068 CRM_Core_DAO
::$_nullObject
2071 $this->_absoluteUrl
= FALSE;
2073 $this->assign('printOnly', FALSE);
2075 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2076 $this->assign('printOnly', TRUE);
2078 $this->assign('outputMode', 'print');
2079 $this->_outputMode
= 'print';
2080 if ($this->_sendmail
) {
2081 $this->_absoluteUrl
= TRUE;
2084 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2085 $this->assign('printOnly', TRUE);
2087 $this->assign('outputMode', 'pdf');
2088 $this->_outputMode
= 'pdf';
2089 $this->_absoluteUrl
= TRUE;
2091 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2092 $this->assign('printOnly', TRUE);
2094 $this->assign('outputMode', 'csv');
2095 $this->_outputMode
= 'csv';
2096 $this->_absoluteUrl
= TRUE;
2098 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2099 $this->assign('outputMode', 'group');
2100 $this->_outputMode
= 'group';
2102 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2103 $this->assign('outputMode', 'create_report');
2104 $this->_outputMode
= 'create_report';
2107 $this->assign('outputMode', 'html');
2108 $this->_outputMode
= 'html';
2111 // Get today's date to include in printed reports
2113 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2114 $this->assign('reportDate', $reportDate);
2118 function beginPostProcess() {
2119 $this->setParams($this->controller
->exportValues($this->_name
));
2121 if (empty($this->_params
) &&
2124 $this->setParams($this->_formValues
);
2127 // hack to fix params when submitted from dashboard, CRM-8532
2128 // fields array is missing because form building etc is skipped
2129 // in dashboard mode for report
2130 //@todo - this could be done in the dashboard no we have a setter
2131 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2132 $this->setParams($this->_formValues
);
2135 $this->_formValues
= $this->_params
;
2136 if (CRM_Core_Permission
::check('administer Reports') &&
2137 isset($this->_id
) &&
2138 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2139 $this->_chartButtonName
== $this->controller
->getButtonName()
2142 $this->assign('updateReportButton', TRUE);
2144 $this->processReportMode();
2145 $this->beginPostProcessCommon();
2149 * beginPostProcess function run in both report mode and non-report mode (api)
2151 function beginPostProcessCommon() {
2155 function buildQuery($applyLimit = TRUE) {
2158 $this->customDataFrom();
2163 // order_by columns not selected for display need to be included in SELECT
2164 $unselectedSectionColumns = $this->unselectedSectionColumns();
2165 foreach ($unselectedSectionColumns as $alias => $section) {
2166 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2169 if ($applyLimit && empty($this->_params
['charts'])) {
2172 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2174 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2178 function groupBy() {
2179 $groupBys = array();
2180 if (!empty($this->_params
['group_bys']) &&
2181 is_array($this->_params
['group_bys']) &&
2182 !empty($this->_params
['group_bys'])
2184 foreach ($this->_columns
as $tableName => $table) {
2185 if (array_key_exists('group_bys', $table)) {
2186 foreach ($table['group_bys'] as $fieldName => $field) {
2187 if (!empty($this->_params
['group_bys'][$fieldName])) {
2188 $groupBys[] = $field['dbAlias'];
2195 if (!empty($groupBys)) {
2196 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2200 function orderBy() {
2201 $this->_orderBy
= "";
2202 $this->_sections
= array();
2203 $this->storeOrderByArray();
2204 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2205 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2207 $this->assign('sections', $this->_sections
);
2211 * In some cases other functions want to know which fields are selected for ordering by
2212 * Separating this into a separate function allows it to be called separately from constructing
2213 * the order by clause
2215 function storeOrderByArray() {
2216 $orderBys = array();
2218 if (!empty($this->_params
['order_bys']) &&
2219 is_array($this->_params
['order_bys']) &&
2220 !empty($this->_params
['order_bys'])
2223 // Proces order_bys in user-specified order
2224 foreach ($this->_params
['order_bys'] as $orderBy) {
2225 $orderByField = array();
2226 foreach ($this->_columns
as $tableName => $table) {
2227 if (array_key_exists('order_bys', $table)) {
2228 // For DAO columns defined in $this->_columns
2229 $fields = $table['order_bys'];
2231 elseif (array_key_exists('extends', $table)) {
2232 // For custom fields referenced in $this->_customGroupExtends
2233 $fields = CRM_Utils_Array
::value('fields', $table, array());
2235 if (!empty($fields) && is_array($fields)) {
2236 foreach ($fields as $fieldName => $field) {
2237 if ($fieldName == $orderBy['column']) {
2238 $orderByField = array_merge($field, $orderBy);
2239 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2246 if (!empty($orderByField)) {
2247 $this->_orderByFields
[] = $orderByField;
2248 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2250 // Record any section headers for assignment to the template
2251 if (!empty($orderBy['section'])) {
2252 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2253 $this->_sections
[$orderByField['tplField']] = $orderByField;
2259 $this->_orderByArray
= $orderBys;
2261 $this->assign('sections', $this->_sections
);
2264 function unselectedSectionColumns() {
2265 $selectColumns = array();
2266 foreach ($this->_columns
as $tableName => $table) {
2267 if (array_key_exists('fields', $table)) {
2268 foreach ($table['fields'] as $fieldName => $field) {
2269 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
2271 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2277 if (is_array($this->_sections
)) {
2278 return array_diff_key($this->_sections
, $selectColumns);
2285 function buildRows($sql, &$rows) {
2286 $dao = CRM_Core_DAO
::executeQuery($sql);
2287 if (!is_array($rows)) {
2291 // use this method to modify $this->_columnHeaders
2292 $this->modifyColumnHeaders();
2294 $unselectedSectionColumns = $this->unselectedSectionColumns();
2296 while ($dao->fetch()) {
2298 foreach ($this->_columnHeaders
as $key => $value) {
2299 if (property_exists($dao, $key)) {
2300 $row[$key] = $dao->$key;
2304 // section headers not selected for display need to be added to row
2305 foreach ($unselectedSectionColumns as $key => $values) {
2306 if (property_exists($dao, $key)) {
2307 $row[$key] = $dao->$key;
2316 * When "order by" fields are marked as sections, this assigns to the template
2317 * an array of total counts for each section. This data is used by the Smarty
2318 * plugin {sectionTotal}
2320 function sectionTotals() {
2322 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2323 if (empty($this->_selectAliases
)) {
2327 if (!empty($this->_sections
)) {
2328 // build the query with no LIMIT clause
2329 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2330 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2332 // pull section aliases out of $this->_sections
2333 $sectionAliases = array_keys($this->_sections
);
2336 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2337 $ifnulls[] = "ifnull($alias, '') as $alias";
2340 /* Group (un-limited) report by all aliases and get counts. This might
2341 * be done more efficiently when the contents of $sql are known, ie. by
2342 * overriding this method in the report class.
2346 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2348 // initialize array of total counts
2350 $dao = CRM_Core_DAO
::executeQuery($query);
2351 while ($dao->fetch()) {
2353 // let $this->_alterDisplay translate any integer ids to human-readable values.
2354 $rows[0] = $dao->toArray();
2355 $this->alterDisplay($rows);
2358 // add totals for all permutations of section values
2361 $aliasCount = count($sectionAliases);
2362 foreach ($sectionAliases as $alias) {
2363 $values[] = $row[$alias];
2364 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2365 if ($i == $aliasCount) {
2366 // the last alias is the lowest-level section header; use count as-is
2367 $totals[$key] = $dao->ct
;
2370 // other aliases are higher level; roll count into their total
2371 $totals[$key] +
= $dao->ct
;
2375 $this->assign('sectionTotals', $totals);
2379 function modifyColumnHeaders() {
2380 // use this method to modify $this->_columnHeaders
2383 function doTemplateAssignment(&$rows) {
2384 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2385 $this->assign_by_ref('rows', $rows);
2386 $this->assign('statistics', $this->statistics($rows));
2389 // override this method to build your own statistics
2390 function statistics(&$rows) {
2391 $statistics = array();
2393 $count = count($rows);
2395 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2399 $this->countStat($statistics, $count);
2401 $this->groupByStat($statistics);
2403 $this->filterStat($statistics);
2408 function countStat(&$statistics, $count) {
2409 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2413 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2414 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2415 'value' => $this->_rowsFound
,
2420 function groupByStat(&$statistics) {
2421 if (!empty($this->_params
['group_bys']) &&
2422 is_array($this->_params
['group_bys']) &&
2423 !empty($this->_params
['group_bys'])
2425 foreach ($this->_columns
as $tableName => $table) {
2426 if (array_key_exists('group_bys', $table)) {
2427 foreach ($table['group_bys'] as $fieldName => $field) {
2428 if (!empty($this->_params
['group_bys'][$fieldName])) {
2429 $combinations[] = $field['title'];
2434 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2435 'value' => implode(' & ', $combinations),
2440 function filterStat(&$statistics) {
2441 foreach ($this->_columns
as $tableName => $table) {
2442 if (array_key_exists('filters', $table)) {
2443 foreach ($table['filters'] as $fieldName => $field) {
2444 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2447 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2448 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2449 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2450 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2451 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2453 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2454 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2456 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2457 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2460 $statistics['filters'][] = array(
2461 'title' => $field['title'],
2462 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2465 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2466 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2468 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2469 $statistics['filters'][] = array(
2470 'title' => $field['title'],
2471 'value' => $pair[$rel],
2476 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2479 $pair = $this->getOperationPair(
2480 CRM_Utils_Array
::value('operatorType', $field),
2483 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2484 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2485 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2486 if (in_array($op, array(
2487 'bw', 'nbw')) && ($min ||
$max)) {
2488 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2490 elseif ($op == 'nll' ||
$op == 'nnll') {
2491 $value = $pair[$op];
2493 elseif (is_array($val) && (!empty($val))) {
2494 $options = CRM_Utils_Array
::value('options', $field, array());
2495 foreach ($val as $key => $valIds) {
2496 if (isset($options[$valIds])) {
2497 $val[$key] = $options[$valIds];
2500 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op == 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2501 $val = implode(', ', $val);
2502 $value = "{$pair[$op]} " . $val;
2504 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2505 is_array($field['options']) && !empty($field['options'])
2507 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2510 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2514 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2524 function endPostProcess(&$rows = NULL) {
2525 if ( $this->_storeResultSet
) {
2526 $this->_resultSet
= $rows;
2529 if ($this->_outputMode
== 'print' ||
2530 $this->_outputMode
== 'pdf' ||
2534 $content = $this->compileContent();
2535 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2539 if ($this->_sendmail
) {
2540 $config = CRM_Core_Config
::singleton();
2541 $attachments = array();
2543 if ($this->_outputMode
== 'csv') {
2544 $content = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') . ": {$url}</p>" . '<p>' . ts('The report is attached as a CSV file.') . '</p>' . $this->_formValues
['report_footer'];
2546 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2547 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2548 file_put_contents($csvFullFilename, $csvContent);
2549 $attachments[] = array(
2550 'fullPath' => $csvFullFilename,
2551 'mime_type' => 'text/csv',
2552 'cleanName' => 'CiviReport.csv',
2555 if ($this->_outputMode
== 'pdf') {
2556 // generate PDF content
2557 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2558 file_put_contents($pdfFullFilename,
2559 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2560 TRUE, array('orientation' => 'landscape')
2563 // generate Email Content
2564 $content = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') . ": {$url}</p>" . '<p>' . ts('The report is attached as a PDF file.') . '</p>' . $this->_formValues
['report_footer'];
2566 $attachments[] = array(
2567 'fullPath' => $pdfFullFilename,
2568 'mime_type' => 'application/pdf',
2569 'cleanName' => 'CiviReport.pdf',
2573 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2574 $this->_outputMode
, $attachments
2576 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2579 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2583 elseif ($this->_outputMode
== 'print') {
2587 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2588 $config = CRM_Core_Config
::singleton();
2589 //get chart image name
2590 $chartImg = $this->_chartId
. '.png';
2591 //get image url path
2592 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2593 $uploadUrl .= $chartImg;
2594 //get image doc path to overwrite
2595 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2597 $chart = imagecreatefrompng($uploadUrl);
2598 //convert it into formattd png
2599 header('Content-type: image/png');
2600 //overwrite with same image
2601 imagepng($chart, $uploadImg);
2603 imagedestroy($chart);
2605 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2607 CRM_Utils_System
::civiExit();
2609 elseif ($this->_outputMode
== 'csv') {
2610 CRM_Report_Utils_Report
::export2csv($this, $rows);
2612 elseif ($this->_outputMode
== 'group') {
2613 $group = $this->_params
['groups'];
2614 $this->add2group($group);
2616 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2617 CRM_Report_Form_Instance
::postProcess($this);
2619 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2620 $this->_outputMode
== 'create_report' ) {
2621 $this->_createNew
= TRUE;
2622 CRM_Report_Form_Instance
::postProcess($this);
2626 function storeResultSet() {
2627 $this->_storeResultSet
= TRUE;
2630 function getResultSet() {
2631 return $this->_resultSet
;
2635 * Get Template file name - use default form template if a specific one has not been set up for this report
2638 function getTemplateFileName(){
2639 $defaultTpl = parent
::getTemplateFileName();
2640 $template = CRM_Core_Smarty
::singleton();
2641 if (!$template->template_exists($defaultTpl)) {
2642 $defaultTpl = 'CRM/Report/Form.tpl';
2648 * Compile the report content
2650 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2652 function compileContent(){
2653 $templateFile = $this->getHookedTemplateFileName();
2654 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2658 function postProcess() {
2659 // get ready with post process params
2660 $this->beginPostProcess();
2663 $sql = $this->buildQuery();
2665 // build array of result based on column headers. This method also allows
2666 // modifying column headers before using it to build result set i.e $rows.
2668 $this->buildRows($sql, $rows);
2670 // format result set.
2671 $this->formatDisplay($rows);
2673 // assign variables to templates
2674 $this->doTemplateAssignment($rows);
2676 // do print / pdf / instance stuff if needed
2677 $this->endPostProcess($rows);
2680 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2681 // lets do the pager if in html mode
2682 $this->_limit
= NULL;
2683 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2684 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2686 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2688 if (!$pageId && !empty($_POST)) {
2689 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2690 $pageId = max((int)@$_POST['crmPID_B'], 1);
2692 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2693 $pageId = max((int)@$_POST['crmPID'], 1);
2695 unset($_POST['crmPID_B'], $_POST['crmPID']);
2698 $pageId = $pageId ?
$pageId : 1;
2699 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2700 $offset = ($pageId - 1) * $rowCount;
2702 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2703 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2705 $this->_limit
= " LIMIT $offset, $rowCount";
2706 return array($offset, $rowCount);
2708 if($this->_limitValue
) {
2709 if($this->_offsetValue
) {
2710 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2713 $this->_limit
= " LIMIT " . $this->_limitValue
;
2718 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2719 if ($this->_limit
&& ($this->_limit
!= '')) {
2720 $sql = "SELECT FOUND_ROWS();";
2721 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2723 'total' => $this->_rowsFound
,
2724 'rowCount' => $rowCount,
2725 'status' => ts('Records') . ' %%StatusMessage%%',
2726 'buttonBottom' => 'PagerBottomButton',
2727 'buttonTop' => 'PagerTopButton',
2728 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2731 $pager = new CRM_Utils_Pager($params);
2732 $this->assign_by_ref('pager', $pager);
2733 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2737 function whereGroupClause($field, $value, $op) {
2739 $smartGroupQuery = "";
2741 $group = new CRM_Contact_DAO_Group();
2742 $group->is_active
= 1;
2744 $smartGroups = array();
2745 while ($group->fetch()) {
2746 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2747 $smartGroups[] = $group->id
;
2751 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2753 $smartGroupQuery = '';
2754 if (!empty($smartGroups)) {
2755 $smartGroups = implode(',', $smartGroups);
2756 $smartGroupQuery = " UNION DISTINCT
2757 SELECT DISTINCT smartgroup_contact.contact_id
2758 FROM civicrm_group_contact_cache smartgroup_contact
2759 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2762 $sqlOp = $this->getSQLOperator($op);
2763 if (!is_array($value)) {
2764 $value = array($value);
2766 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2768 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2769 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2770 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2771 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2772 {$smartGroupQuery} ) ";
2775 function whereTagClause($field, $value, $op) {
2776 // not using left join in query because if any contact
2777 // belongs to more than one tag, results duplicate
2779 $sqlOp = $this->getSQLOperator($op);
2780 if (!is_array($value)) {
2781 $value = array($value);
2783 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2785 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2786 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2787 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2788 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2791 function buildACLClause($tableAlias = 'contact_a') {
2792 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2795 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2796 if (empty($this->_customGroupExtends
)) {
2799 if (!is_array($this->_customGroupExtends
)) {
2800 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2802 $customGroupWhere = '';
2803 if (!empty($permCustomGroupIds)) {
2804 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2807 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2808 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2809 FROM civicrm_custom_group cg
2810 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2811 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2813 cg.is_active = 1 AND
2814 cf.is_active = 1 AND
2815 cf.is_searchable = 1
2816 ORDER BY cg.weight, cf.weight";
2817 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2820 while ($customDAO->fetch()) {
2821 if ($customDAO->table_name
!= $curTable) {
2822 $curTable = $customDAO->table_name
;
2823 $curFields = $curFilters = array();
2826 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2827 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2828 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2829 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2832 'fields', 'filters', 'group_bys') as $colKey) {
2833 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2834 $this->_columns
[$curTable][$colKey] = array();
2838 $fieldName = 'custom_' . $customDAO->cf_id
;
2841 // this makes aliasing work in favor
2842 $curFields[$fieldName] = array(
2843 'name' => $customDAO->column_name
,
2844 'title' => $customDAO->label
,
2845 'dataType' => $customDAO->data_type
,
2846 'htmlType' => $customDAO->html_type
,
2849 if ($this->_customGroupFilters
) {
2850 // this makes aliasing work in favor
2851 $curFilters[$fieldName] = array(
2852 'name' => $customDAO->column_name
,
2853 'title' => $customDAO->label
,
2854 'dataType' => $customDAO->data_type
,
2855 'htmlType' => $customDAO->html_type
,
2859 switch ($customDAO->data_type
) {
2862 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2863 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2864 // CRM-6946, show time part for datetime date fields
2865 if ($customDAO->time_format
) {
2866 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2871 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2872 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2876 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2880 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2881 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2885 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2886 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2890 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2891 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2895 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2897 if (!empty($customDAO->option_group_id
)) {
2898 if (in_array($customDAO->html_type
, array(
2899 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2900 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2903 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2905 if ($this->_customGroupFilters
) {
2906 $curFilters[$fieldName]['options'] = array();
2907 $ogDAO = CRM_Core_DAO
::executeQuery("SELECT ov.value, ov.label FROM civicrm_option_value ov WHERE ov.option_group_id = %1 ORDER BY ov.weight", array(1 => array($customDAO->option_group_id
, 'Integer')));
2908 while ($ogDAO->fetch()) {
2909 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2915 case 'StateProvince':
2916 if (in_array($customDAO->html_type
, array(
2917 'Multi-Select State/Province'))) {
2918 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2921 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2923 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2927 if (in_array($customDAO->html_type
, array(
2928 'Multi-Select Country'))) {
2929 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2932 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2934 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2937 case 'ContactReference':
2938 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2939 $curFilters[$fieldName]['name'] = 'display_name';
2940 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2942 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2943 $curFields[$fieldName]['name'] = 'display_name';
2944 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2948 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2949 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2952 if (!array_key_exists('type', $curFields[$fieldName])) {
2953 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2957 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2959 if ($this->_customGroupFilters
) {
2960 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2962 if ($this->_customGroupGroupBy
) {
2963 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2968 function customDataFrom() {
2969 if (empty($this->_customGroupExtends
)) {
2972 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2974 foreach ($this->_columns
as $table => $prop) {
2975 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2976 $extendsTable = $mapper[$prop['extends']];
2978 // check field is in params
2979 if (!$this->isFieldSelected($prop)) {
2982 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
2984 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2986 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
2987 // handle for ContactReference
2988 if (array_key_exists('fields', $prop)) {
2989 foreach ($prop['fields'] as $fieldName => $field) {
2990 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2991 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2993 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3001 function isFieldSelected($prop) {
3006 if (!empty($this->_params
['fields'])) {
3007 foreach (array_keys($prop['fields']) as $fieldAlias) {
3008 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3009 if ($customFieldId) {
3010 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3014 //might be survey response field.
3015 if (!empty($this->_params
['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3022 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3023 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3024 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3030 if (!empty($this->_params
['order_bys'])) {
3031 foreach (array_keys($prop['fields']) as $fieldAlias) {
3032 foreach ($this->_params
['order_bys'] as $orderBy) {
3033 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3040 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3041 foreach ($prop['filters'] as $fieldAlias => $val) {
3043 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3044 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3045 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3046 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3052 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3053 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3064 * Check for empty order_by configurations and remove them; also set
3065 * template to hide them.
3067 function preProcessOrderBy(&$formValues) {
3068 // Object to show/hide form elements
3069 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3071 $_showHide->addShow('optionField_1');
3073 // Cycle through order_by options; skip any empty ones, and hide them as well
3076 if (!empty($formValues['order_bys'])) {
3077 foreach ($formValues['order_bys'] as $order_by) {
3078 if ($order_by['column'] && $order_by['column'] != '-') {
3079 $_showHide->addShow('optionField_' . $n);
3080 $orderBys[$n] = $order_by;
3085 for ($i = $n; $i <= 5; $i++
) {
3087 $_showHide->addHide('optionField_' . $i);
3091 // overwrite order_by options with modified values
3092 if (!empty($orderBys)) {
3093 $formValues['order_bys'] = $orderBys;
3096 $formValues['order_bys'] = array(1 => array('column' => '-'));
3099 // assign show/hide data to template
3100 $_showHide->addToTemplate();
3104 * Does table name have columns in SELECT clause?
3106 * @param string $tableName Name of table (index of $this->_columns array)
3110 function isTableSelected($tableName) {
3111 return in_array($tableName, $this->selectedTables());
3115 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3116 * (building the array if it's unset)
3118 * @return Array $this->_selectedTables
3120 function selectedTables() {
3121 if (!$this->_selectedTables
) {
3122 $orderByColumns = array();
3123 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3124 foreach ($this->_params
['order_bys'] as $orderBy) {
3125 $orderByColumns[] = $orderBy['column'];
3129 foreach ($this->_columns
as $tableName => $table) {
3130 if (array_key_exists('fields', $table)) {
3131 foreach ($table['fields'] as $fieldName => $field) {
3132 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
3133 $this->_selectedTables
[] = $tableName;
3138 if (array_key_exists('order_bys', $table)) {
3139 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3140 if (in_array($orderByName, $orderByColumns)) {
3141 $this->_selectedTables
[] = $tableName;
3146 if (array_key_exists('filters', $table)) {
3147 foreach ($table['filters'] as $filterName => $filter) {
3148 if (!empty($this->_params
["{$filterName}_value"]) ||
3149 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3150 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3152 $this->_selectedTables
[] = $tableName;
3159 return $this->_selectedTables
;
3163 * @deprecated - use getAddressColumns which is a more accurate description
3164 * and also accepts an array of options rather than a long list
3166 * function for adding address fields to construct function in reports
3167 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3168 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3169 * @return array address fields for construct clause
3171 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3172 'country_id' => TRUE)) {
3173 $addressFields = array(
3174 'civicrm_address' =>
3176 'dao' => 'CRM_Core_DAO_Address',
3180 array('title' => ts('Address Name'),
3181 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3184 array('title' => ts('Street Address'),
3185 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3187 'supplemental_address_1' =>
3188 array('title' => ts('Supplementary Address Field 1'),
3189 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3191 'supplemental_address_2' =>
3192 array('title' => ts('Supplementary Address Field 2'),
3193 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3197 'name' => 'street_number',
3198 'title' => ts('Street Number'),
3200 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3204 'name' => 'street_name',
3205 'title' => ts('Street Name'),
3207 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3211 'name' => 'street_unit',
3212 'title' => ts('Street Unit'),
3214 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3217 array('title' => ts('City'),
3218 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3221 array('title' => ts('Postal Code'),
3222 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3224 'postal_code_suffix' =>
3225 array('title' => ts('Postal Code Suffix'),
3226 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3229 array('title' => ts('County'),
3230 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3232 'state_province_id' =>
3233 array('title' => ts('State/Province'),
3234 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3237 array('title' => ts('Country'),
3238 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3241 'grouping' => 'location-fields',
3246 $addressFields['civicrm_address']['filters'] = array(
3247 'street_number' => array('title' => ts('Street Number'),
3249 'name' => 'street_number',
3251 'street_name' => array('title' => ts('Street Name'),
3252 'name' => 'street_name',
3253 'operator' => 'like',
3255 'postal_code' => array('title' => ts('Postal Code'),
3257 'name' => 'postal_code',
3259 'city' => array('title' => ts('City'),
3260 'operator' => 'like',
3263 'county_id' => array(
3264 'name' => 'county_id',
3265 'title' => ts('County'),
3266 'type' => CRM_Utils_Type
::T_INT
,
3268 CRM_Report_Form
::OP_MULTISELECT
,
3270 CRM_Core_PseudoConstant
::county(),
3272 'state_province_id' => array(
3273 'name' => 'state_province_id',
3274 'title' => ts('State/Province'),
3275 'type' => CRM_Utils_Type
::T_INT
,
3277 CRM_Report_Form
::OP_MULTISELECT
,
3279 CRM_Core_PseudoConstant
::stateProvince(),
3281 'country_id' => array(
3282 'name' => 'country_id',
3283 'title' => ts('Country'),
3284 'type' => CRM_Utils_Type
::T_INT
,
3286 CRM_Report_Form
::OP_MULTISELECT
,
3288 CRM_Core_PseudoConstant
::country(),
3294 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3295 'street_number' => array('title' => 'Odd / Even Street Number'),
3296 'street_address' => NULL,
3298 'postal_code' => NULL,
3303 $addressFields['civicrm_address']['group_bys'] = array(
3304 'street_address' => NULL,
3306 'postal_code' => NULL,
3307 'state_province_id' =>
3308 array('title' => ts('State/Province'),
3311 array('title' => ts('Country'),
3314 array('title' => ts('County'),
3318 return $addressFields;
3322 * Do AlterDisplay processing on Address Fields
3324 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3325 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3326 $entryFound = FALSE;
3328 if (array_key_exists('civicrm_address_country_id', $row)) {
3329 if ($value = $row['civicrm_address_country_id']) {
3330 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3331 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3332 "reset=1&force=1&{$criteriaQueryParams}&" .
3333 "country_id_op=in&country_id_value={$value}",
3334 $this->_absoluteUrl
, $this->_id
3336 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3337 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3344 if (array_key_exists('civicrm_address_county_id', $row)) {
3345 if ($value = $row['civicrm_address_county_id']) {
3346 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3347 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3348 "reset=1&force=1&{$criteriaQueryParams}&" .
3349 "county_id_op=in&county_id_value={$value}",
3350 $this->_absoluteUrl
, $this->_id
3352 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3353 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3359 // handle state province
3360 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3361 if ($value = $row['civicrm_address_state_province_id']) {
3362 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3364 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3365 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3366 $this->_absoluteUrl
, $this->_id
3368 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3369 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3380 * Adjusts dates passed in to YEAR() for fiscal year.
3382 function fiscalYearOffset($fieldName) {
3383 $config = CRM_Core_Config
::singleton();
3384 $fy = $config->fiscalYearStart
;
3385 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3386 return "YEAR( $fieldName )";
3388 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3392 * Add Address into From Table if required
3394 function addAddressFromClause() {
3395 // include address field if address column is to be included
3396 if ((isset($this->_addressField
) &&
3397 $this->_addressField
3399 $this->isTableSelected('civicrm_address')
3402 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3403 ON ({$this->_aliases['civicrm_contact']}.id =
3404 {$this->_aliases['civicrm_address']}.contact_id) AND
3405 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3410 * Add Phone into From Table if required
3412 function addPhoneFromClause() {
3413 // include address field if address column is to be included
3414 if ($this->isTableSelected('civicrm_phone')
3417 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3418 ON ({$this->_aliases['civicrm_contact']}.id =
3419 {$this->_aliases['civicrm_phone']}.contact_id) AND
3420 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3425 * Get phone columns to add to array
3426 * @param array $options
3427 * - prefix Prefix to add to table (in case of more than one instance of the table)
3428 * - prefix_label Label to give columns from this phone table instance
3429 * @return array phone columns definition
3431 function getPhoneColumns($options = array()){
3432 $defaultOptions = array(
3434 'prefix_label' => '',
3437 $options = array_merge($defaultOptions,$options);
3440 $options['prefix'] . 'civicrm_phone' => array(
3441 'dao' => 'CRM_Core_DAO_Phone',
3443 $options['prefix'] . 'phone' => array(
3444 'title' => ts($options['prefix_label'] . 'Phone'),
3454 * Get address columns to add to array
3455 * @param array $options
3456 * - prefix Prefix to add to table (in case of more than one instance of the table)
3457 * - prefix_label Label to give columns from this address table instance
3458 * @return array address columns definition
3460 function getAddressColumns($options = array()){
3461 $defaultOptions = array(
3463 'prefix_label' => '',
3467 'defaults' => array(
3470 $options = array_merge($defaultOptions,$options);
3471 return $this->addAddressFields(
3472 $options['group_by'],
3473 $options['order_by'],
3474 $options['filters'],
3475 $options['defaults']
3480 function add2group($groupID) {
3481 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3482 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3483 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3485 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3486 $dao = CRM_Core_DAO
::executeQuery($sql);
3488 $contact_ids = array();
3489 // Add resulting contacts to group
3490 while ($dao->fetch()) {
3491 if ($dao->addtogroup_contact_id
) {
3492 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3496 if ( !empty($contact_ids) ) {
3497 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3498 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3501 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3506 /* function used for showing charts on print screen */
3507 static function uploadChartImage() {
3508 // upload strictly for '.png' images
3509 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3510 if (preg_match('/\.png$/', $name)) {
3512 // POST data is usually string data, but we are passing a RAW .png
3513 // so PHP is a bit confused and $_POST is empty. But it has saved
3514 // the raw bits into $HTTP_RAW_POST_DATA
3516 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3518 // prepare the directory
3519 $config = CRM_Core_Config
::singleton();
3520 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3521 if (!file_exists($defaultPath)) {
3522 mkdir($defaultPath, 0777, TRUE);
3525 // full path to the saved image including filename
3526 $destination = $defaultPath . $name;
3529 $jfh = fopen($destination, 'w') or die("can't open file");
3530 fwrite($jfh, $httpRawPostData);
3532 CRM_Utils_System
::civiExit();