3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 CONST ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
53 * The id of the report instance
60 * The id of the report template
64 protected $_templateID;
72 protected $_noFields = FALSE;
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attribues as the value
80 protected $_columns = array();
83 * The set of filters in the report
87 protected $_filters = array();
90 * The set of optional columns in the report
94 protected $_options = array();
96 protected $_defaults = array();
99 * By default most reports hide contact id.
100 * Setting this to true makes it available
102 protected $_exposeContactID = TRUE;
105 * Set of statistic fields
109 protected $_statFields = array();
112 * Set of statistics data
116 protected $_statistics = array();
119 * List of fields not to be repeated during display
123 protected $_noRepeats = array();
126 * List of fields not to be displayed
130 protected $_noDisplay = array();
133 * Object type that a custom group extends
137 protected $_customGroupExtends = NULL;
138 protected $_customGroupExtendsJoin = array();
139 protected $_customGroupFilters = TRUE;
140 protected $_customGroupGroupBy = FALSE;
141 protected $_customGroupJoin = 'LEFT JOIN';
147 protected $_tagFilter = FALSE;
150 * build groups filter
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * An attribute for checkbox/radio form field layout
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
174 protected $_force = 1;
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_grandFlag = FALSE;
194 protected $_rowsFound = NULL;
195 protected $_selectAliases = array();
196 protected $_rollup = NULL;
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.");
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 ||
array_key_exists('enumValues', $this->_columns
[$tableName][$fieldGrp][$fieldName]))
580 // with multiple options operator-type is generally multi-select
581 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
582 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
584 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
595 // copy filters to a separate handy variable
596 if (array_key_exists('filters', $table)) {
597 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
600 if (array_key_exists('group_bys', $table)) {
601 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
604 if (array_key_exists('fields', $table)) {
605 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
610 $this->setDefaultValues(FALSE);
613 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
614 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
615 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
616 CRM_Report_Utils_Get
::processChart($this->_defaults
);
619 $this->_formValues
= $this->_defaults
;
620 $this->postProcess();
624 function setDefaultValues($freeze = TRUE) {
625 $freezeGroup = array();
627 // FIXME: generalizing form field naming conventions would reduce
628 // lots of lines below.
629 foreach ($this->_columns
as $tableName => $table) {
630 if (array_key_exists('fields', $table)) {
631 foreach ($table['fields'] as $fieldName => $field) {
632 if (empty($field['no_display'])) {
633 if (isset($field['required'])) {
635 $this->_defaults
['fields'][$fieldName] = 1;
638 // find element object, so that we could use quickform's freeze method
639 // for required elements
640 $obj = $this->getElementFromGroup("fields", $fieldName);
642 $freezeGroup[] = $obj;
646 elseif (isset($field['default'])) {
647 $this->_defaults
['fields'][$fieldName] = $field['default'];
653 if (array_key_exists('group_bys', $table)) {
654 foreach ($table['group_bys'] as $fieldName => $field) {
655 if (isset($field['default'])) {
656 if (!empty($field['frequency'])) {
657 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
659 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
663 if (array_key_exists('filters', $table)) {
664 foreach ($table['filters'] as $fieldName => $field) {
665 if (isset($field['default'])) {
666 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
667 if(is_array($field['default'])){
668 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
669 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
670 $this->_defaults
["{$fieldName}_relative"] = 0;
673 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
677 $this->_defaults
["{$fieldName}_value"] = $field['default'];
680 //assign default value as "in" for multiselect
681 //operator, To freeze the select element
682 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT
) {
683 $this->_defaults
["{$fieldName}_op"] = 'in';
685 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
) {
686 $this->_defaults
["{$fieldName}_op"] = 'mhas';
688 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
689 $this->_defaults
["{$fieldName}_op"] = $op;
695 array_key_exists('order_bys', $table) &&
696 is_array($table['order_bys'])
698 if (!array_key_exists('order_bys', $this->_defaults
)) {
699 $this->_defaults
['order_bys'] = array();
701 foreach ($table['order_bys'] as $fieldName => $field) {
702 if (!empty($field['default']) ||
703 CRM_Utils_Array
::value('default_order', $field) ||
704 CRM_Utils_Array
::value('default_is_section', $field) ||
705 CRM_Utils_Array
::value('default_weight', $field)
708 'column' => $fieldName,
709 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
710 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
713 if (!empty($field['default_weight'])) {
714 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
717 array_unshift($this->_defaults
['order_bys'], $order_by);
723 foreach ($this->_options
as $fieldName => $field) {
724 if (isset($field['default'])) {
725 $this->_defaults
['options'][$fieldName] = $field['default'];
730 if (!empty($this->_submitValues
)) {
731 $this->preProcessOrderBy($this->_submitValues
);
734 $this->preProcessOrderBy($this->_defaults
);
737 // lets finish freezing task here itself
738 if (!empty($freezeGroup)) {
739 foreach ($freezeGroup as $elem) {
744 if ($this->_formValues
) {
745 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
748 if ($this->_instanceValues
) {
749 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
752 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
754 return $this->_defaults
;
757 function getElementFromGroup($group, $grpFieldName) {
758 $eleObj = $this->getElement($group);
759 foreach ($eleObj->_elements
as $index => $obj) {
760 if ($grpFieldName == $obj->_attributes
['name']) {
768 * Setter for $_params
769 * @param array $params
771 function setParams($params) {
772 $this->_params
= $params;
779 function setID($instanceid) {
780 $this->_id
= $instanceid;
785 * @param boolean $force
787 function setForce($isForce) {
788 $this->_force
= $isForce;
792 * Setter for $_limitValue
793 * @param number $_limitValue
795 function setLimitValue($_limitValue) {
796 $this->_limitValue
= $_limitValue;
800 * Setter for $_offsetValue
801 * @param number $_offsetValue
803 function setOffsetValue($_offsetValue) {
804 $this->_offsetValue
= $_offsetValue;
808 * Getter for $_defaultValues
809 * @return array $_defaultValues
811 function getDefaultValues() {
812 return $this->_defaults
;
815 function addColumns() {
818 foreach ($this->_columns
as $tableName => $table) {
819 if (array_key_exists('fields', $table)) {
820 foreach ($table['fields'] as $fieldName => $field) {
822 if (empty($field['no_display'])) {
823 foreach ( array('table', 'field') as $var) {
824 if (!empty($
{$var}['grouping'])) {
825 if (!is_array($
{$var}['grouping'])) {
826 $tableName = $
{$var}['grouping'];
828 $tableName = array_keys($
{$var}['grouping']);
829 $tableName = $tableName[0];
830 $groupTitle = array_values($
{$var}['grouping']);
831 $groupTitle = $groupTitle[0];
836 if (!$groupTitle && isset($table['group_title'])) {
837 $groupTitle = $table['group_title'];
840 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
841 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
842 $colGroups[$tableName]['group_title'] = $groupTitle;
845 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
851 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
852 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
854 $this->assign('colGroups', $colGroups);
857 function addFilters() {
858 $options = $filters = array();
860 foreach ($this->_filters
as $table => $attributes) {
861 foreach ($attributes as $fieldName => $field) {
862 // get ready with option value pair
863 // @ 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
865 $operations = $this->getOperationPair(
866 CRM_Utils_Array
::value('operatorType', $field),
869 $filters[$table][$fieldName] = $field;
871 switch (CRM_Utils_Array
::value('operatorType', $field)) {
872 case CRM_Report_Form
::OP_MONTH
:
873 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
874 // If there's no option list for this filter, define one.
875 $field['options'] = array(
884 9 => ts('September'),
886 11 => ts('November'),
887 12 => ts('December'),
889 // Add this option list to this column _columns. This is
890 // required so that filter statistics show properly.
891 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
893 case CRM_Report_Form
::OP_MULTISELECT
:
894 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
895 // assume a multi-select field
896 if (!empty($field['options'])) {
897 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
898 if (count($operations) <= 1) {
901 $select = $this->addElement('select', "{$fieldName}_value", NULL,
902 $field['options'], array(
904 'style' => 'min-width:250px',
907 $select->setMultiple(TRUE);
911 case CRM_Report_Form
::OP_SELECT
:
912 // assume a select field
913 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
914 if (!empty($field['options']))
915 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
918 case CRM_Report_Form
::OP_DATE
:
919 // build datetime fields
920 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
924 case CRM_Report_Form
::OP_DATETIME
:
925 // build datetime fields
926 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
930 case CRM_Report_Form
::OP_INT
:
931 case CRM_Report_Form
::OP_FLOAT
:
932 // and a min value input box
933 $this->add('text', "{$fieldName}_min", ts('Min'));
934 // and a max value input box
935 $this->add('text', "{$fieldName}_max", ts('Max'));
937 // default type is string
938 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
939 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
941 // we need text box for value input
942 $this->add('text', "{$fieldName}_value", NULL);
947 $this->assign('filters', $filters);
950 function addOptions() {
951 if (!empty($this->_options
)) {
952 // FIXME: For now lets build all elements as checkboxes.
953 // Once we clear with the format we can build elements based on type
956 foreach ($this->_options
as $fieldName => $field) {
957 if ($field['type'] == 'select') {
958 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
960 else if ($field['type'] == 'checkbox') {
961 $options[$field['title']] = $fieldName;
962 $this->addCheckBox($fieldName, NULL,
964 NULL, NULL, NULL, $this->_fourColumnAttribute
969 $this->assign('otherOptions', $this->_options
);
972 function addChartOptions() {
973 if (!empty($this->_charts
)) {
974 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
975 $this->assign('charts', $this->_charts
);
976 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
980 function addGroupBys() {
981 $options = $freqElements = array();
983 foreach ($this->_columns
as $tableName => $table) {
984 if (array_key_exists('group_bys', $table)) {
985 foreach ($table['group_bys'] as $fieldName => $field) {
986 if (!empty($field)) {
987 $options[$field['title']] = $fieldName;
988 if (!empty($field['frequency'])) {
989 $freqElements[$field['title']] = $fieldName;
995 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
996 NULL, NULL, NULL, $this->_fourColumnAttribute
998 $this->assign('groupByElements', $options);
1000 foreach ($freqElements as $name) {
1001 $this->addElement('select', "group_bys_freq[$name]",
1002 ts('Frequency'), $this->_groupByDateFreq
1007 function addOrderBys() {
1009 foreach ($this->_columns
as $tableName => $table) {
1011 // Report developer may define any column to order by; include these as order-by options
1012 if (array_key_exists('order_bys', $table)) {
1013 foreach ($table['order_bys'] as $fieldName => $field) {
1014 if (!empty($field)) {
1015 $options[$fieldName] = $field['title'];
1020 /* Add searchable custom fields as order-by options, if so requested
1021 * (These are already indexed, so allowing to order on them is cheap.)
1025 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
1026 foreach ($table['fields'] as $fieldName => $field) {
1027 if (empty($field['no_display'])) {
1028 $options[$fieldName] = $field['title'];
1036 $this->assign('orderByOptions', $options);
1038 if (!empty($options)) {
1040 '-' => ' - none - ') +
$options;
1041 for ($i = 1; $i <= 5; $i++
) {
1042 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1043 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1044 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1045 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1050 function buildInstanceAndButtons() {
1051 CRM_Report_Form_Instance
::buildForm($this);
1053 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1055 $this->addElement('submit', $this->_instanceButtonName
, $label);
1056 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1057 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1060 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
1062 if ($this->_instanceForm
) {
1063 $this->assign('instanceForm', TRUE);
1066 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1067 $this->addElement('submit', $this->_printButtonName
, $label);
1069 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1070 $this->addElement('submit', $this->_pdfButtonName
, $label);
1072 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1074 if ($this->_csvSupported
) {
1075 $this->addElement('submit', $this->_csvButtonName
, $label);
1078 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
1079 $this->addElement('select', 'groups', ts('Group'),
1080 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
1082 $this->assign('group', TRUE);
1085 $label = ts('Add These Contacts to Group');
1086 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
1088 $this->addChartOptions();
1089 $this->addButtons(array(
1092 'name' => ts('Preview Report'),
1093 'isDefault' => TRUE,
1099 function buildQuickForm() {
1100 $this->addColumns();
1102 $this->addFilters();
1104 $this->addOptions();
1106 $this->addGroupBys();
1108 $this->addOrderBys();
1110 $this->buildInstanceAndButtons();
1112 //add form rule for report
1113 if (is_callable(array(
1114 $this, 'formRule'))) {
1115 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1119 // a formrule function to ensure that fields selected in group_by
1120 // (if any) should only be the ones present in display/select fields criteria;
1121 // note: works if and only if any custom field selected in group_by.
1122 function customDataFormRule($fields, $ignoreFields = array( )) {
1124 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1125 foreach ($this->_columns
as $tableName => $table) {
1126 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1127 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1128 if (array_key_exists($fieldName, $fields['group_bys']) &&
1129 !array_key_exists($fieldName, $fields['fields'])
1131 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1133 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1134 foreach ($fields['fields'] as $fld => $val) {
1135 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1136 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1147 // Note: $fieldName param allows inheriting class to build operationPairs
1148 // specific to a field.
1149 function getOperationPair($type = "string", $fieldName = NULL) {
1150 // FIXME: At some point we should move these key-val pairs
1151 // to option_group and option_value table.
1153 case CRM_Report_Form
::OP_INT
:
1154 case CRM_Report_Form
::OP_FLOAT
:
1156 'lte' => ts('Is less than or equal to'),
1157 'gte' => ts('Is greater than or equal to'),
1158 'bw' => ts('Is between'),
1159 'eq' => ts('Is equal to'),
1160 'lt' => ts('Is less than'),
1161 'gt' => ts('Is greater than'),
1162 'neq' => ts('Is not equal to'),
1163 'nbw' => ts('Is not between'),
1164 'nll' => ts('Is empty (Null)'),
1165 'nnll' => ts('Is not empty (Null)'),
1169 case CRM_Report_Form
::OP_SELECT
:
1171 'eq' => ts('Is equal to'),
1174 case CRM_Report_Form
::OP_MONTH
:
1175 case CRM_Report_Form
::OP_MULTISELECT
:
1177 'in' => ts('Is one of'),
1178 'notin' => ts('Is not one of'),
1182 case CRM_Report_Form
::OP_DATE
:
1184 'nll' => ts('Is empty (Null)'),
1185 'nnll' => ts('Is not empty (Null)'),
1189 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1190 // use this operator for the values, concatenated with separator. For e.g if
1191 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1193 'mhas' => ts('Is one of'),
1199 'has' => ts('Contains'),
1200 'sw' => ts('Starts with'),
1201 'ew' => ts('Ends with'),
1202 'nhas' => ts('Does not contain'),
1203 'eq' => ts('Is equal to'),
1204 'neq' => ts('Is not equal to'),
1205 'nll' => ts('Is empty (Null)'),
1206 'nnll' => ts('Is not empty (Null)'),
1211 function buildTagFilter() {
1212 $contactTags = CRM_Core_BAO_Tag
::getTags();
1213 if (!empty($contactTags)) {
1214 $this->_columns
['civicrm_tag'] = array(
1215 'dao' => 'CRM_Core_DAO_Tag',
1221 'title' => ts('Tag'),
1223 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1224 'options' => $contactTags,
1232 * Adds group filters to _columns (called from _Constuct
1234 function buildGroupFilter() {
1235 $this->_columns
['civicrm_group']['filters'] = array(
1238 'name' => 'group_id',
1239 'title' => ts('Group'),
1240 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1242 'options' => CRM_Core_PseudoConstant
::group(),
1245 if (empty($this->_columns
['civicrm_group']['dao'])) {
1246 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1248 if (empty($this->_columns
['civicrm_group']['alias'])) {
1249 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1253 function getSQLOperator($operator = "like") {
1254 switch ($operator) {
1287 return 'IS NOT NULL';
1295 function whereClause(&$field, $op,
1299 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1305 if (($min !== NULL && strlen($min) > 0) ||
1306 ($max !== NULL && strlen($max) > 0)
1308 $min = CRM_Utils_Type
::escape($min, $type);
1309 $max = CRM_Utils_Type
::escape($max, $type);
1313 $clauses[] = "( {$field['dbAlias']} >= $min )";
1316 $clauses[] = "( {$field['dbAlias']} < $min )";
1321 $clauses[] = "( {$field['dbAlias']} <= $max )";
1324 $clauses[] = "( {$field['dbAlias']} > $max )";
1328 if (!empty($clauses)) {
1330 $clause = implode(' AND ', $clauses);
1333 $clause = implode(' OR ', $clauses);
1341 if ($value !== NULL && strlen($value) > 0) {
1342 $value = CRM_Utils_Type
::escape($value, $type);
1343 if (strpos($value, '%') === FALSE) {
1344 $value = "'%{$value}%'";
1347 $value = "'{$value}'";
1349 $sqlOP = $this->getSQLOperator($op);
1350 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1356 if ($value !== NULL && is_array($value) && count($value) > 0) {
1357 $sqlOP = $this->getSQLOperator($op);
1358 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1359 //cycle through selections and esacape values
1360 foreach ($value as $key => $selection) {
1361 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1363 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1366 // for numerical values
1367 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1369 if ($op == 'notin') {
1370 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1373 $clause = "( " . $clause . " )";
1379 // mhas == multiple has
1380 if ($value !== NULL && count($value) > 0) {
1381 $sqlOP = $this->getSQLOperator($op);
1382 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1388 if ($value !== NULL && strlen($value) > 0) {
1389 $value = CRM_Utils_Type
::escape($value, $type);
1390 if (strpos($value, '%') === FALSE) {
1392 $value = "'{$value}%'";
1395 $value = "'%{$value}'";
1399 $value = "'{$value}'";
1401 $sqlOP = $this->getSQLOperator($op);
1402 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1408 $sqlOP = $this->getSQLOperator($op);
1409 $clause = "( {$field['dbAlias']} $sqlOP )";
1413 if ($value !== NULL && strlen($value) > 0) {
1414 if (isset($field['clause'])) {
1415 // FIXME: we not doing escape here. Better solution is to use two
1416 // different types - data-type and filter-type
1417 $clause = $field['clause'];
1420 $value = CRM_Utils_Type
::escape($value, $type);
1421 $sqlOP = $this->getSQLOperator($op);
1422 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1423 $value = "'{$value}'";
1425 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1431 if (!empty($field['group']) && $clause) {
1432 $clause = $this->whereGroupClause($field, $value, $op);
1434 elseif (!empty($field['tag']) && $clause) {
1435 // not using left join in query because if any contact
1436 // belongs to more than one tag, results duplicate
1438 $clause = $this->whereTagClause($field, $value, $op);
1444 function dateClause($fieldName,
1445 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1448 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1449 $sqlOP = $this->getSQLOperator($relative);
1450 return "( {$fieldName} {$sqlOP} )";
1453 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1456 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1457 $clauses[] = "( {$fieldName} >= $from )";
1461 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1462 $clauses[] = "( {$fieldName} <= {$to} )";
1465 if (!empty($clauses)) {
1466 return implode(' AND ', $clauses);
1472 * @todo - could not find any instances where this is called
1473 * @param unknown_type $relative
1474 * @param String $from
1475 * @param String_type $to
1476 * @return string|NULL
1478 function dateDisplay($relative, $from, $to) {
1479 list($from, $to) = $this->getFromTo($relative, $from, $to);
1482 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1485 $clauses[] = 'Past';
1489 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1492 $clauses[] = 'Today';
1495 if (!empty($clauses)) {
1496 return implode(' - ', $clauses);
1502 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1503 if (empty($totime)) {
1506 //FIX ME not working for relative
1508 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1509 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1510 $from = substr($dateRange['from'], 0, 8);
1511 //Take only Date Part, Sometime Time part is also present in 'to'
1512 $to = substr($dateRange['to'], 0, 8);
1514 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1515 $to = CRM_Utils_Date
::processDate($to, $totime);
1516 return array($from, $to);
1519 function alterDisplay(&$rows) {
1520 // custom code to alter rows
1523 function alterCustomDataDisplay(&$rows) {
1524 // custom code to alter rows having custom values
1525 if (empty($this->_customGroupExtends
)) {
1529 $customFieldIds = array();
1530 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1531 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1532 $customFieldIds[$fieldAlias] = $fieldId;
1535 if (empty($customFieldIds)) {
1539 $customFields = $fieldValueMap = array();
1540 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1542 // skip for type date and ContactReference since date format is already handled
1544 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1545 FROM civicrm_custom_field cf
1546 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1547 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1548 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1549 cg.is_active = 1 AND
1550 cf.is_active = 1 AND
1551 cf.is_searchable = 1 AND
1552 cf.data_type NOT IN ('ContactReference', 'Date') AND
1553 cf.id IN (" . implode(",", $customFieldIds) . ")";
1555 $dao = CRM_Core_DAO
::executeQuery($query);
1556 while ($dao->fetch()) {
1557 foreach ($customFieldCols as $key) {
1558 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1560 if ($dao->option_group_id
) {
1561 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1566 $entryFound = FALSE;
1567 foreach ($rows as $rowNum => $row) {
1568 foreach ($row as $tableCol => $val) {
1569 if (array_key_exists($tableCol, $customFields)) {
1570 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1575 // skip looking further in rows, if first row itself doesn't
1576 // have the column we need
1583 function formatCustomValues($value, $customField, $fieldValueMap) {
1584 if (CRM_Utils_System
::isNull($value)) {
1588 $htmlType = $customField['html_type'];
1590 switch ($customField['data_type']) {
1592 if ($value == '1') {
1593 $retValue = ts('Yes');
1596 $retValue = ts('No');
1601 $retValue = CRM_Utils_System
::formatWikiURL($value);
1613 if ($htmlType == 'Text') {
1614 $retValue = (float)$value;
1618 if ($htmlType == 'Text') {
1628 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1633 if (in_array($htmlType, array(
1634 'Text', 'TextArea'))) {
1638 case 'StateProvince':
1641 switch ($htmlType) {
1642 case 'Multi-Select Country':
1643 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1644 $customData = array();
1645 foreach ($value as $val) {
1647 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1650 $retValue = implode(', ', $customData);
1653 case 'Select Country':
1654 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1657 case 'Select State/Province':
1658 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1661 case 'Multi-Select State/Province':
1662 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1663 $customData = array();
1664 foreach ($value as $val) {
1666 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1669 $retValue = implode(', ', $customData);
1674 case 'Autocomplete-Select':
1675 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1679 case 'AdvMulti-Select':
1680 case 'Multi-Select':
1681 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1682 $customData = array();
1683 foreach ($value as $val) {
1685 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1688 $retValue = implode(', ', $customData);
1703 function removeDuplicates(&$rows) {
1704 if (empty($this->_noRepeats
)) {
1707 $checkList = array();
1709 foreach ($rows as $key => $list) {
1710 foreach ($list as $colName => $colVal) {
1711 if (array_key_exists($colName, $checkList) &&
1712 $checkList[$colName] == $colVal) {
1713 $rows[$key][$colName] = "";
1715 if (in_array($colName, $this->_noRepeats
)) {
1716 $checkList[$colName] = $colVal;
1722 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1723 foreach ($row as $colName => $colVal) {
1724 if (in_array($colName, $fields)) {
1725 $row[$colName] = $row[$colName];
1727 elseif (isset($this->_columnHeaders
[$colName])) {
1729 $row[$colName] = "Subtotal";
1733 unset($row[$colName]);
1739 function grandTotal(&$rows) {
1740 if (!$this->_rollup ||
($this->_rollup
== '') ||
1741 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1745 $lastRow = array_pop($rows);
1747 foreach ($this->_columnHeaders
as $fld => $val) {
1748 if (!in_array($fld, $this->_statFields
)) {
1749 if (!$this->_grandFlag
) {
1750 $lastRow[$fld] = "Grand Total";
1751 $this->_grandFlag
= TRUE;
1754 $lastRow[$fld] = "";
1759 $this->assign('grandStat', $lastRow);
1763 function formatDisplay(&$rows, $pager = TRUE) {
1764 // set pager based on if any limit was applied in the query.
1769 // allow building charts if any
1770 if (!empty($this->_params
['charts']) && !empty($rows)) {
1771 $this->buildChart($rows);
1772 $this->assign('chartEnabled', TRUE);
1773 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1774 $this->assign('chartId', $this->_chartId
);
1777 // unset columns not to be displayed.
1778 foreach ($this->_columnHeaders
as $key => $value) {
1779 if (!empty($value['no_display'])) {
1780 unset($this->_columnHeaders
[$key]);
1784 // unset columns not to be displayed.
1785 if (!empty($rows)) {
1786 foreach ($this->_noDisplay
as $noDisplayField) {
1787 foreach ($rows as $rowNum => $row) {
1788 unset($this->_columnHeaders
[$noDisplayField]);
1793 // build array of section totals
1794 $this->sectionTotals();
1796 // process grand-total row
1797 $this->grandTotal($rows);
1799 // use this method for formatting rows for display purpose.
1800 $this->alterDisplay($rows);
1801 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1803 // use this method for formatting custom rows for display purpose.
1804 $this->alterCustomDataDisplay($rows);
1807 function buildChart(&$rows) {
1808 // override this method for building charts.
1811 // select() method below has been added recently (v3.3), and many of the report templates might
1812 // still be having their own select() method. We should fix them as and when encountered and move
1813 // towards generalizing the select() method below.
1815 $select = $this->_selectAliases
= array();
1817 foreach ($this->_columns
as $tableName => $table) {
1818 if (array_key_exists('fields', $table)) {
1819 foreach ($table['fields'] as $fieldName => $field) {
1820 if ($tableName == 'civicrm_address') {
1821 $this->_addressField
= TRUE;
1823 if ($tableName == 'civicrm_email') {
1824 $this->_emailField
= TRUE;
1826 if ($tableName == 'civicrm_phone') {
1827 $this->_phoneField
= TRUE;
1830 if (!empty($field['required']) ||
1831 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1834 // 1. In many cases we want select clause to be built in slightly different way
1835 // for a particular field of a particular type.
1836 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1838 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1839 if ($selectClause) {
1840 $select[] = $selectClause;
1844 // include statistics columns only if set
1845 if (!empty($field['statistics'])) {
1846 foreach ($field['statistics'] as $stat => $label) {
1847 $alias = "{$tableName}_{$fieldName}_{$stat}";
1848 switch (strtolower($stat)) {
1851 $select[] = "$stat({$field['dbAlias']}) as $alias";
1852 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1853 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1854 $this->_statFields
[$label] = $alias;
1855 $this->_selectAliases
[] = $alias;
1859 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1860 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1861 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1862 $this->_statFields
[$label] = $alias;
1863 $this->_selectAliases
[] = $alias;
1866 case 'count_distinct':
1867 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1868 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1869 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1870 $this->_statFields
[$label] = $alias;
1871 $this->_selectAliases
[] = $alias;
1875 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1876 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1877 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1878 $this->_statFields
[$label] = $alias;
1879 $this->_selectAliases
[] = $alias;
1885 $alias = "{$tableName}_{$fieldName}";
1886 $select[] = "{$field['dbAlias']} as $alias";
1887 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1888 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1889 $this->_selectAliases
[] = $alias;
1895 // select for group bys
1896 if (array_key_exists('group_bys', $table)) {
1897 foreach ($table['group_bys'] as $fieldName => $field) {
1899 if ($tableName == 'civicrm_address') {
1900 $this->_addressField
= TRUE;
1902 if ($tableName == 'civicrm_email') {
1903 $this->_emailField
= TRUE;
1905 if ($tableName == 'civicrm_phone') {
1906 $this->_phoneField
= TRUE;
1908 // 1. In many cases we want select clause to be built in slightly different way
1909 // for a particular field of a particular type.
1910 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1912 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1913 if ($selectClause) {
1914 $select[] = $selectClause;
1918 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1919 && !empty($this->_params
['group_bys_freq'])) {
1920 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1922 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1923 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1924 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1925 $field['title'] = 'Week';
1929 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1930 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1931 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1932 $field['title'] = 'Year';
1936 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1937 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1938 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1939 $field['title'] = 'Month';
1943 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1944 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1945 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1946 $field['title'] = 'Quarter';
1949 // for graphs and charts -
1950 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
1951 $this->_interval
= $field['title'];
1952 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1953 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1954 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1956 // just to make sure these values are transfered to rows.
1957 // since we 'll need them for calculation purpose,
1958 // e.g making subtotals look nicer or graphs
1959 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1960 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1967 $this->_selectClauses
= $select;
1968 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1971 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1976 $this->storeWhereHavingClauseArray();
1978 if (empty($this->_whereClauses
)) {
1979 $this->_where
= "WHERE ( 1 ) ";
1980 $this->_having
= "";
1983 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1986 if ($this->_aclWhere
) {
1987 $this->_where
.= " AND {$this->_aclWhere} ";
1990 if (!empty($this->_havingClauses
)) {
1991 // use this clause to construct group by clause.
1992 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1997 * Store Where clauses into an array - breaking out this step makes
1998 * over-riding more flexible as the clauses can be used in constructing a
1999 * temp table that may not be part of the final where clause or added
2000 * in other functions
2002 function storeWhereHavingClauseArray(){
2003 foreach ($this->_columns
as $tableName => $table) {
2004 if (array_key_exists('filters', $table)) {
2005 foreach ($table['filters'] as $fieldName => $field) {
2006 // respect pseudofield to filter spec so fields can be marked as
2007 // not to be handled here
2008 if(!empty($field['pseudofield'])){
2012 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2013 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
2014 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2015 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2016 if (is_array($value) && !empty($value)) {
2017 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2021 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2022 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2023 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2024 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2025 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2026 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2030 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2032 $clause = $this->whereClause($field,
2034 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2035 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2036 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2041 if (!empty($clause)) {
2042 if (!empty($field['having'])) {
2043 $this->_havingClauses
[] = $clause;
2046 $this->_whereClauses
[] = $clause;
2054 function processReportMode() {
2055 $buttonName = $this->controller
->getButtonName();
2057 $output = CRM_Utils_Request
::retrieve(
2060 CRM_Core_DAO
::$_nullObject
2064 CRM_Utils_Request
::retrieve(
2067 CRM_Core_DAO
::$_nullObject
2070 $this->_absoluteUrl
= FALSE;
2072 $this->assign('printOnly', FALSE);
2074 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
2075 $this->assign('printOnly', TRUE);
2077 $this->assign('outputMode', 'print');
2078 $this->_outputMode
= 'print';
2079 if ($this->_sendmail
) {
2080 $this->_absoluteUrl
= TRUE;
2083 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2084 $this->assign('printOnly', TRUE);
2086 $this->assign('outputMode', 'pdf');
2087 $this->_outputMode
= 'pdf';
2088 $this->_absoluteUrl
= TRUE;
2090 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2091 $this->assign('printOnly', TRUE);
2093 $this->assign('outputMode', 'csv');
2094 $this->_outputMode
= 'csv';
2095 $this->_absoluteUrl
= TRUE;
2097 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2098 $this->assign('outputMode', 'group');
2099 $this->_outputMode
= 'group';
2101 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2102 $this->assign('outputMode', 'create_report');
2103 $this->_outputMode
= 'create_report';
2106 $this->assign('outputMode', 'html');
2107 $this->_outputMode
= 'html';
2110 // Get today's date to include in printed reports
2112 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2113 $this->assign('reportDate', $reportDate);
2117 function beginPostProcess() {
2118 $this->setParams($this->controller
->exportValues($this->_name
));
2120 if (empty($this->_params
) &&
2123 $this->setParams($this->_formValues
);
2126 // hack to fix params when submitted from dashboard, CRM-8532
2127 // fields array is missing because form building etc is skipped
2128 // in dashboard mode for report
2129 //@todo - this could be done in the dashboard no we have a setter
2130 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2131 $this->setParams($this->_formValues
);
2134 $this->_formValues
= $this->_params
;
2135 if (CRM_Core_Permission
::check('administer Reports') &&
2136 isset($this->_id
) &&
2137 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2138 $this->_chartButtonName
== $this->controller
->getButtonName()
2141 $this->assign('updateReportButton', TRUE);
2143 $this->processReportMode();
2144 $this->beginPostProcessCommon();
2148 * beginPostProcess function run in both report mode and non-report mode (api)
2150 function beginPostProcessCommon() {
2154 function buildQuery($applyLimit = TRUE) {
2157 $this->customDataFrom();
2162 // order_by columns not selected for display need to be included in SELECT
2163 $unselectedSectionColumns = $this->unselectedSectionColumns();
2164 foreach ($unselectedSectionColumns as $alias => $section) {
2165 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2168 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2171 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2173 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2177 function groupBy() {
2178 $groupBys = array();
2179 if (!empty($this->_params
['group_bys']) &&
2180 is_array($this->_params
['group_bys']) &&
2181 !empty($this->_params
['group_bys'])
2183 foreach ($this->_columns
as $tableName => $table) {
2184 if (array_key_exists('group_bys', $table)) {
2185 foreach ($table['group_bys'] as $fieldName => $field) {
2186 if (!empty($this->_params
['group_bys'][$fieldName])) {
2187 $groupBys[] = $field['dbAlias'];
2194 if (!empty($groupBys)) {
2195 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2199 function orderBy() {
2200 $this->_orderBy
= "";
2201 $this->_sections
= array();
2202 $this->storeOrderByArray();
2203 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2204 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2206 $this->assign('sections', $this->_sections
);
2210 * In some cases other functions want to know which fields are selected for ordering by
2211 * Separating this into a separate function allows it to be called separately from constructing
2212 * the order by clause
2214 function storeOrderByArray() {
2215 $orderBys = array();
2217 if (!empty($this->_params
['order_bys']) &&
2218 is_array($this->_params
['order_bys']) &&
2219 !empty($this->_params
['order_bys'])
2222 // Proces order_bys in user-specified order
2223 foreach ($this->_params
['order_bys'] as $orderBy) {
2224 $orderByField = array();
2225 foreach ($this->_columns
as $tableName => $table) {
2226 if (array_key_exists('order_bys', $table)) {
2227 // For DAO columns defined in $this->_columns
2228 $fields = $table['order_bys'];
2230 elseif (array_key_exists('extends', $table)) {
2231 // For custom fields referenced in $this->_customGroupExtends
2232 $fields = $table['fields'];
2234 if (!empty($fields) && is_array($fields)) {
2235 foreach ($fields as $fieldName => $field) {
2236 if ($fieldName == $orderBy['column']) {
2237 $orderByField = array_merge($field, $orderBy);
2238 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2245 if (!empty($orderByField)) {
2246 $this->_orderByFields
[] = $orderByField;
2247 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2249 // Record any section headers for assignment to the template
2250 if (!empty($orderBy['section'])) {
2251 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2252 $this->_sections
[$orderByField['tplField']] = $orderByField;
2258 $this->_orderByArray
= $orderBys;
2260 $this->assign('sections', $this->_sections
);
2263 function unselectedSectionColumns() {
2264 $selectColumns = array();
2265 foreach ($this->_columns
as $tableName => $table) {
2266 if (array_key_exists('fields', $table)) {
2267 foreach ($table['fields'] as $fieldName => $field) {
2268 if (!empty($field['required']) ||
2269 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2272 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2278 if (is_array($this->_sections
)) {
2279 return array_diff_key($this->_sections
, $selectColumns);
2286 function buildRows($sql, &$rows) {
2287 $dao = CRM_Core_DAO
::executeQuery($sql);
2288 if (!is_array($rows)) {
2292 // use this method to modify $this->_columnHeaders
2293 $this->modifyColumnHeaders();
2295 $unselectedSectionColumns = $this->unselectedSectionColumns();
2297 while ($dao->fetch()) {
2299 foreach ($this->_columnHeaders
as $key => $value) {
2300 if (property_exists($dao, $key)) {
2301 $row[$key] = $dao->$key;
2305 // section headers not selected for display need to be added to row
2306 foreach ($unselectedSectionColumns as $key => $values) {
2307 if (property_exists($dao, $key)) {
2308 $row[$key] = $dao->$key;
2317 * When "order by" fields are marked as sections, this assigns to the template
2318 * an array of total counts for each section. This data is used by the Smarty
2319 * plugin {sectionTotal}
2321 function sectionTotals() {
2323 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2324 if (empty($this->_selectAliases
)) {
2328 if (!empty($this->_sections
)) {
2329 // build the query with no LIMIT clause
2330 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2331 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2333 // pull section aliases out of $this->_sections
2334 $sectionAliases = array_keys($this->_sections
);
2337 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2338 $ifnulls[] = "ifnull($alias, '') as $alias";
2341 /* Group (un-limited) report by all aliases and get counts. This might
2342 * be done more efficiently when the contents of $sql are known, ie. by
2343 * overriding this method in the report class.
2347 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2349 // initialize array of total counts
2351 $dao = CRM_Core_DAO
::executeQuery($query);
2352 while ($dao->fetch()) {
2354 // let $this->_alterDisplay translate any integer ids to human-readable values.
2355 $rows[0] = $dao->toArray();
2356 $this->alterDisplay($rows);
2359 // add totals for all permutations of section values
2362 $aliasCount = count($sectionAliases);
2363 foreach ($sectionAliases as $alias) {
2364 $values[] = $row[$alias];
2365 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2366 if ($i == $aliasCount) {
2367 // the last alias is the lowest-level section header; use count as-is
2368 $totals[$key] = $dao->ct
;
2371 // other aliases are higher level; roll count into their total
2372 $totals[$key] +
= $dao->ct
;
2376 $this->assign('sectionTotals', $totals);
2380 function modifyColumnHeaders() {
2381 // use this method to modify $this->_columnHeaders
2384 function doTemplateAssignment(&$rows) {
2385 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2386 $this->assign_by_ref('rows', $rows);
2387 $this->assign('statistics', $this->statistics($rows));
2390 // override this method to build your own statistics
2391 function statistics(&$rows) {
2392 $statistics = array();
2394 $count = count($rows);
2396 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2400 $this->countStat($statistics, $count);
2402 $this->groupByStat($statistics);
2404 $this->filterStat($statistics);
2409 function countStat(&$statistics, $count) {
2410 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2414 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2415 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2416 'value' => $this->_rowsFound
,
2421 function groupByStat(&$statistics) {
2422 if (!empty($this->_params
['group_bys']) &&
2423 is_array($this->_params
['group_bys']) &&
2424 !empty($this->_params
['group_bys'])
2426 foreach ($this->_columns
as $tableName => $table) {
2427 if (array_key_exists('group_bys', $table)) {
2428 foreach ($table['group_bys'] as $fieldName => $field) {
2429 if (!empty($this->_params
['group_bys'][$fieldName])) {
2430 $combinations[] = $field['title'];
2435 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2436 'value' => implode(' & ', $combinations),
2441 function filterStat(&$statistics) {
2442 foreach ($this->_columns
as $tableName => $table) {
2443 if (array_key_exists('filters', $table)) {
2444 foreach ($table['filters'] as $fieldName => $field) {
2445 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2448 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2449 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2450 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2451 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2452 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2454 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2455 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2457 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2458 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2461 $statistics['filters'][] = array(
2462 'title' => $field['title'],
2463 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2466 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2467 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2469 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2470 $statistics['filters'][] = array(
2471 'title' => $field['title'],
2472 'value' => $pair[$rel],
2477 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2480 $pair = $this->getOperationPair(
2481 CRM_Utils_Array
::value('operatorType', $field),
2484 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2485 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2486 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2487 if (in_array($op, array(
2488 'bw', 'nbw')) && ($min ||
$max)) {
2489 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2491 elseif ($op == 'nll' ||
$op == 'nnll') {
2492 $value = $pair[$op];
2494 elseif (is_array($val) && (!empty($val))) {
2495 $options = CRM_Utils_Array
::value('options', $field, array());
2496 foreach ($val as $key => $valIds) {
2497 if (isset($options[$valIds])) {
2498 $val[$key] = $options[$valIds];
2501 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2502 $val = implode(', ', $val);
2503 $value = "{$pair[$op]} " . $val;
2505 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2506 is_array($field['options']) && !empty($field['options'])
2508 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2511 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2515 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2525 function endPostProcess(&$rows = NULL) {
2526 if ( $this->_storeResultSet
) {
2527 $this->_resultSet
= $rows;
2530 if ($this->_outputMode
== 'print' ||
2531 $this->_outputMode
== 'pdf' ||
2535 $content = $this->compileContent();
2536 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2540 if ($this->_sendmail
) {
2541 $config = CRM_Core_Config
::singleton();
2542 $attachments = array();
2544 if ($this->_outputMode
== 'csv') {
2545 $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'];
2547 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2548 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2549 file_put_contents($csvFullFilename, $csvContent);
2550 $attachments[] = array(
2551 'fullPath' => $csvFullFilename,
2552 'mime_type' => 'text/csv',
2553 'cleanName' => 'CiviReport.csv',
2556 if ($this->_outputMode
== 'pdf') {
2557 // generate PDF content
2558 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2559 file_put_contents($pdfFullFilename,
2560 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2561 TRUE, array('orientation' => 'landscape')
2564 // generate Email Content
2565 $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'];
2567 $attachments[] = array(
2568 'fullPath' => $pdfFullFilename,
2569 'mime_type' => 'application/pdf',
2570 'cleanName' => 'CiviReport.pdf',
2574 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2575 $this->_outputMode
, $attachments
2577 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2580 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2583 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2585 elseif ($this->_outputMode
== 'print') {
2589 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2590 $config = CRM_Core_Config
::singleton();
2591 //get chart image name
2592 $chartImg = $this->_chartId
. '.png';
2593 //get image url path
2594 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2595 $uploadUrl .= $chartImg;
2596 //get image doc path to overwrite
2597 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2599 $chart = imagecreatefrompng($uploadUrl);
2600 //convert it into formattd png
2601 header('Content-type: image/png');
2602 //overwrite with same image
2603 imagepng($chart, $uploadImg);
2605 imagedestroy($chart);
2607 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2609 CRM_Utils_System
::civiExit();
2611 elseif ($this->_outputMode
== 'csv') {
2612 CRM_Report_Utils_Report
::export2csv($this, $rows);
2614 elseif ($this->_outputMode
== 'group') {
2615 $group = $this->_params
['groups'];
2616 $this->add2group($group);
2618 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2619 CRM_Report_Form_Instance
::postProcess($this);
2621 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2622 $this->_outputMode
== 'create_report' ) {
2623 $this->_createNew
= TRUE;
2624 CRM_Report_Form_Instance
::postProcess($this);
2628 function storeResultSet() {
2629 $this->_storeResultSet
= TRUE;
2632 function getResultSet() {
2633 return $this->_resultSet
;
2637 * Get Template file name - use default form template if a specific one has not been set up for this report
2640 function getTemplateFileName(){
2641 $defaultTpl = parent
::getTemplateFileName();
2642 $template = CRM_Core_Smarty
::singleton();
2643 if (!$template->template_exists($defaultTpl)) {
2644 $defaultTpl = 'CRM/Report/Form.tpl';
2650 * Compile the report content
2652 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2654 function compileContent(){
2655 $templateFile = $this->getHookedTemplateFileName();
2656 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2660 function postProcess() {
2661 // get ready with post process params
2662 $this->beginPostProcess();
2665 $sql = $this->buildQuery();
2667 // build array of result based on column headers. This method also allows
2668 // modifying column headers before using it to build result set i.e $rows.
2670 $this->buildRows($sql, $rows);
2672 // format result set.
2673 $this->formatDisplay($rows);
2675 // assign variables to templates
2676 $this->doTemplateAssignment($rows);
2678 // do print / pdf / instance stuff if needed
2679 $this->endPostProcess($rows);
2682 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2683 // lets do the pager if in html mode
2684 $this->_limit
= NULL;
2685 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2686 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2688 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2690 if (!$pageId && !empty($_POST)) {
2691 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2692 $pageId = max((int)@$_POST['crmPID_B'], 1);
2694 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2695 $pageId = max((int)@$_POST['crmPID'], 1);
2697 unset($_POST['crmPID_B'], $_POST['crmPID']);
2700 $pageId = $pageId ?
$pageId : 1;
2701 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2702 $offset = ($pageId - 1) * $rowCount;
2704 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2705 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2707 $this->_limit
= " LIMIT $offset, $rowCount";
2708 return array($offset, $rowCount);
2710 if($this->_limitValue
) {
2711 if($this->_offsetValue
) {
2712 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2715 $this->_limit
= " LIMIT " . $this->_limitValue
;
2720 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2721 if ($this->_limit
&& ($this->_limit
!= '')) {
2722 $sql = "SELECT FOUND_ROWS();";
2723 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2725 'total' => $this->_rowsFound
,
2726 'rowCount' => $rowCount,
2727 'status' => ts('Records') . ' %%StatusMessage%%',
2728 'buttonBottom' => 'PagerBottomButton',
2729 'buttonTop' => 'PagerTopButton',
2730 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2733 $pager = new CRM_Utils_Pager($params);
2734 $this->assign_by_ref('pager', $pager);
2735 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
2739 function whereGroupClause($field, $value, $op) {
2741 $smartGroupQuery = "";
2743 $group = new CRM_Contact_DAO_Group();
2744 $group->is_active
= 1;
2746 $smartGroups = array();
2747 while ($group->fetch()) {
2748 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2749 $smartGroups[] = $group->id
;
2753 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2755 $smartGroupQuery = '';
2756 if (!empty($smartGroups)) {
2757 $smartGroups = implode(',', $smartGroups);
2758 $smartGroupQuery = " UNION DISTINCT
2759 SELECT DISTINCT smartgroup_contact.contact_id
2760 FROM civicrm_group_contact_cache smartgroup_contact
2761 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2764 $sqlOp = $this->getSQLOperator($op);
2765 if (!is_array($value)) {
2766 $value = array($value);
2768 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2770 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2771 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2772 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2773 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2774 {$smartGroupQuery} ) ";
2777 function whereTagClause($field, $value, $op) {
2778 // not using left join in query because if any contact
2779 // belongs to more than one tag, results duplicate
2781 $sqlOp = $this->getSQLOperator($op);
2782 if (!is_array($value)) {
2783 $value = array($value);
2785 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2787 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2788 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2789 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2790 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2793 function buildACLClause($tableAlias = 'contact_a') {
2794 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2797 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2798 if (empty($this->_customGroupExtends
)) {
2801 if (!is_array($this->_customGroupExtends
)) {
2802 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2804 $customGroupWhere = '';
2805 if (!empty($permCustomGroupIds)) {
2806 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2809 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2810 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2811 FROM civicrm_custom_group cg
2812 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2813 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2815 cg.is_active = 1 AND
2816 cf.is_active = 1 AND
2817 cf.is_searchable = 1
2818 ORDER BY cg.weight, cf.weight";
2819 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2822 while ($customDAO->fetch()) {
2823 if ($customDAO->table_name
!= $curTable) {
2824 $curTable = $customDAO->table_name
;
2825 $curFields = $curFilters = array();
2828 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2829 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2830 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2831 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2834 'fields', 'filters', 'group_bys') as $colKey) {
2835 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2836 $this->_columns
[$curTable][$colKey] = array();
2840 $fieldName = 'custom_' . $customDAO->cf_id
;
2843 // this makes aliasing work in favor
2844 $curFields[$fieldName] = array(
2845 'name' => $customDAO->column_name
,
2846 'title' => $customDAO->label
,
2847 'dataType' => $customDAO->data_type
,
2848 'htmlType' => $customDAO->html_type
,
2851 if ($this->_customGroupFilters
) {
2852 // this makes aliasing work in favor
2853 $curFilters[$fieldName] = array(
2854 'name' => $customDAO->column_name
,
2855 'title' => $customDAO->label
,
2856 'dataType' => $customDAO->data_type
,
2857 'htmlType' => $customDAO->html_type
,
2861 switch ($customDAO->data_type
) {
2864 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2865 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2866 // CRM-6946, show time part for datetime date fields
2867 if ($customDAO->time_format
) {
2868 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2873 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2874 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2878 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2882 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2883 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2887 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2888 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2892 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2893 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2897 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2899 if (!empty($customDAO->option_group_id
)) {
2900 if (in_array($customDAO->html_type
, array(
2901 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2902 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2905 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2907 if ($this->_customGroupFilters
) {
2908 $curFilters[$fieldName]['options'] = array();
2909 $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')));
2910 while ($ogDAO->fetch()) {
2911 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2917 case 'StateProvince':
2918 if (in_array($customDAO->html_type
, array(
2919 'Multi-Select State/Province'))) {
2920 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2923 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2925 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2929 if (in_array($customDAO->html_type
, array(
2930 'Multi-Select Country'))) {
2931 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2934 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2936 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2939 case 'ContactReference':
2940 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2941 $curFilters[$fieldName]['name'] = 'display_name';
2942 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2944 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2945 $curFields[$fieldName]['name'] = 'display_name';
2946 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2950 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2951 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2954 if (!array_key_exists('type', $curFields[$fieldName])) {
2955 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2959 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2961 if ($this->_customGroupFilters
) {
2962 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2964 if ($this->_customGroupGroupBy
) {
2965 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2970 function customDataFrom() {
2971 if (empty($this->_customGroupExtends
)) {
2974 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2976 foreach ($this->_columns
as $table => $prop) {
2977 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2978 $extendsTable = $mapper[$prop['extends']];
2980 // check field is in params
2981 if (!$this->isFieldSelected($prop)) {
2984 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
2986 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2988 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
2989 // handle for ContactReference
2990 if (array_key_exists('fields', $prop)) {
2991 foreach ($prop['fields'] as $fieldName => $field) {
2992 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2993 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2995 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3003 function isFieldSelected($prop) {
3008 if (!empty($this->_params
['fields'])) {
3009 foreach (array_keys($prop['fields']) as $fieldAlias) {
3010 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3011 if ($customFieldId) {
3012 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3016 //might be survey response field.
3017 if (!empty($this->_params
['fields']['survey_response']) &&
3018 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
3026 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3027 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3028 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3034 if (!empty($this->_params
['order_bys'])) {
3035 foreach (array_keys($prop['fields']) as $fieldAlias) {
3036 foreach ($this->_params
['order_bys'] as $orderBy) {
3037 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
3044 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3045 foreach ($prop['filters'] as $fieldAlias => $val) {
3047 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3048 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3049 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3050 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
3056 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3057 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3068 * Check for empty order_by configurations and remove them; also set
3069 * template to hide them.
3071 function preProcessOrderBy(&$formValues) {
3072 // Object to show/hide form elements
3073 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3075 $_showHide->addShow('optionField_1');
3077 // Cycle through order_by options; skip any empty ones, and hide them as well
3080 if (!empty($formValues['order_bys'])) {
3081 foreach ($formValues['order_bys'] as $order_by) {
3082 if ($order_by['column'] && $order_by['column'] != '-') {
3083 $_showHide->addShow('optionField_' . $n);
3084 $orderBys[$n] = $order_by;
3089 for ($i = $n; $i <= 5; $i++
) {
3091 $_showHide->addHide('optionField_' . $i);
3095 // overwrite order_by options with modified values
3096 if (!empty($orderBys)) {
3097 $formValues['order_bys'] = $orderBys;
3100 $formValues['order_bys'] = array(1 => array('column' => '-'));
3103 // assign show/hide data to template
3104 $_showHide->addToTemplate();
3108 * Does table name have columns in SELECT clause?
3110 * @param string $tableName Name of table (index of $this->_columns array)
3114 function isTableSelected($tableName) {
3115 return in_array($tableName, $this->selectedTables());
3119 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3120 * (building the array if it's unset)
3122 * @return Array $this->_selectedTables
3124 function selectedTables() {
3125 if (!$this->_selectedTables
) {
3126 $orderByColumns = array();
3127 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3128 foreach ($this->_params
['order_bys'] as $orderBy) {
3129 $orderByColumns[] = $orderBy['column'];
3133 foreach ($this->_columns
as $tableName => $table) {
3134 if (array_key_exists('fields', $table)) {
3135 foreach ($table['fields'] as $fieldName => $field) {
3136 if (!empty($field['required']) ||
3137 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3139 $this->_selectedTables
[] = $tableName;
3144 if (array_key_exists('order_bys', $table)) {
3145 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3146 if (in_array($orderByName, $orderByColumns)) {
3147 $this->_selectedTables
[] = $tableName;
3152 if (array_key_exists('filters', $table)) {
3153 foreach ($table['filters'] as $filterName => $filter) {
3154 if (!empty($this->_params
["{$filterName}_value"]) ||
3155 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3156 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3158 $this->_selectedTables
[] = $tableName;
3165 return $this->_selectedTables
;
3169 * @deprecated - use getAddressColumns which is a more accurate description
3170 * and also accepts an array of options rather than a long list
3172 * function for adding address fields to construct function in reports
3173 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3174 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3175 * @return array address fields for construct clause
3177 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3178 'country_id' => TRUE)) {
3179 $addressFields = array(
3180 'civicrm_address' =>
3182 'dao' => 'CRM_Core_DAO_Address',
3186 array('title' => ts('Address Name'),
3187 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3190 array('title' => ts('Street Address'),
3191 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3193 'supplemental_address_1' =>
3194 array('title' => ts('Supplementary Address Field 1'),
3195 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3197 'supplemental_address_2' =>
3198 array('title' => ts('Supplementary Address Field 2'),
3199 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3203 'name' => 'street_number',
3204 'title' => ts('Street Number'),
3206 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3210 'name' => 'street_name',
3211 'title' => ts('Street Name'),
3213 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3217 'name' => 'street_unit',
3218 'title' => ts('Street Unit'),
3220 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3223 array('title' => ts('City'),
3224 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3227 array('title' => ts('Postal Code'),
3228 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3230 'postal_code_suffix' =>
3231 array('title' => ts('Postal Code Suffix'),
3232 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3235 array('title' => ts('County'),
3236 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3238 'state_province_id' =>
3239 array('title' => ts('State/Province'),
3240 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3243 array('title' => ts('Country'),
3244 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3247 'grouping' => 'location-fields',
3252 $addressFields['civicrm_address']['filters'] = array(
3253 'street_number' => array('title' => ts('Street Number'),
3255 'name' => 'street_number',
3257 'street_name' => array('title' => ts('Street Name'),
3258 'name' => 'street_name',
3259 'operator' => 'like',
3261 'postal_code' => array('title' => ts('Postal Code'),
3263 'name' => 'postal_code',
3265 'city' => array('title' => ts('City'),
3266 'operator' => 'like',
3269 'county_id' => array(
3270 'name' => 'county_id',
3271 'title' => ts('County'),
3272 'type' => CRM_Utils_Type
::T_INT
,
3274 CRM_Report_Form
::OP_MULTISELECT
,
3276 CRM_Core_PseudoConstant
::county(),
3278 'state_province_id' => array(
3279 'name' => 'state_province_id',
3280 'title' => ts('State/Province'),
3281 'type' => CRM_Utils_Type
::T_INT
,
3283 CRM_Report_Form
::OP_MULTISELECT
,
3285 CRM_Core_PseudoConstant
::stateProvince(),
3287 'country_id' => array(
3288 'name' => 'country_id',
3289 'title' => ts('Country'),
3290 'type' => CRM_Utils_Type
::T_INT
,
3292 CRM_Report_Form
::OP_MULTISELECT
,
3294 CRM_Core_PseudoConstant
::country(),
3300 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3301 'street_number' => array('title' => 'Odd / Even Street Number'),
3302 'street_address' => NULL,
3304 'postal_code' => NULL,
3309 $addressFields['civicrm_address']['group_bys'] = array(
3310 'street_address' => NULL,
3312 'postal_code' => NULL,
3313 'state_province_id' =>
3314 array('title' => ts('State/Province'),
3317 array('title' => ts('Country'),
3320 array('title' => ts('County'),
3324 return $addressFields;
3328 * Do AlterDisplay processing on Address Fields
3330 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3331 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3332 $entryFound = FALSE;
3334 if (array_key_exists('civicrm_address_country_id', $row)) {
3335 if ($value = $row['civicrm_address_country_id']) {
3336 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3337 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3338 "reset=1&force=1&{$criteriaQueryParams}&" .
3339 "country_id_op=in&country_id_value={$value}",
3340 $this->_absoluteUrl
, $this->_id
3342 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3343 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3350 if (array_key_exists('civicrm_address_county_id', $row)) {
3351 if ($value = $row['civicrm_address_county_id']) {
3352 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3353 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3354 "reset=1&force=1&{$criteriaQueryParams}&" .
3355 "county_id_op=in&county_id_value={$value}",
3356 $this->_absoluteUrl
, $this->_id
3358 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3359 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3365 // handle state province
3366 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3367 if ($value = $row['civicrm_address_state_province_id']) {
3368 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3370 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3371 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3372 $this->_absoluteUrl
, $this->_id
3374 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3375 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3386 * Adjusts dates passed in to YEAR() for fiscal year.
3388 function fiscalYearOffset($fieldName) {
3389 $config = CRM_Core_Config
::singleton();
3390 $fy = $config->fiscalYearStart
;
3391 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3392 return "YEAR( $fieldName )";
3394 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3398 * Add Address into From Table if required
3400 function addAddressFromClause() {
3401 // include address field if address column is to be included
3402 if ((isset($this->_addressField
) &&
3403 $this->_addressField
3405 $this->isTableSelected('civicrm_address')
3408 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3409 ON ({$this->_aliases['civicrm_contact']}.id =
3410 {$this->_aliases['civicrm_address']}.contact_id) AND
3411 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3416 * Add Phone into From Table if required
3418 function addPhoneFromClause() {
3419 // include address field if address column is to be included
3420 if ($this->isTableSelected('civicrm_phone')
3423 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3424 ON ({$this->_aliases['civicrm_contact']}.id =
3425 {$this->_aliases['civicrm_phone']}.contact_id) AND
3426 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3431 * Get phone columns to add to array
3432 * @param array $options
3433 * - prefix Prefix to add to table (in case of more than one instance of the table)
3434 * - prefix_label Label to give columns from this phone table instance
3435 * @return array phone columns definition
3437 function getPhoneColumns($options = array()){
3438 $defaultOptions = array(
3440 'prefix_label' => '',
3443 $options = array_merge($defaultOptions,$options);
3446 $options['prefix'] . 'civicrm_phone' => array(
3447 'dao' => 'CRM_Core_DAO_Phone',
3449 $options['prefix'] . 'phone' => array(
3450 'title' => ts($options['prefix_label'] . 'Phone'),
3460 * Get address columns to add to array
3461 * @param array $options
3462 * - prefix Prefix to add to table (in case of more than one instance of the table)
3463 * - prefix_label Label to give columns from this address table instance
3464 * @return array address columns definition
3466 function getAddressColumns($options = array()){
3467 $defaultOptions = array(
3469 'prefix_label' => '',
3473 'defaults' => array(
3476 $options = array_merge($defaultOptions,$options);
3477 return $this->addAddressFields(
3478 $options['group_by'],
3479 $options['order_by'],
3480 $options['filters'],
3481 $options['defaults']
3486 function add2group($groupID) {
3487 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3488 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3489 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3491 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3492 $dao = CRM_Core_DAO
::executeQuery($sql);
3494 $contact_ids = array();
3495 // Add resulting contacts to group
3496 while ($dao->fetch()) {
3497 if ($dao->addtogroup_contact_id
) {
3498 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3502 if ( !empty($contact_ids) ) {
3503 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3504 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3507 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3512 /* function used for showing charts on print screen */
3513 static function uploadChartImage() {
3514 // upload strictly for '.png' images
3515 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3516 if (preg_match('/\.png$/', $name)) {
3518 // POST data is usually string data, but we are passing a RAW .png
3519 // so PHP is a bit confused and $_POST is empty. But it has saved
3520 // the raw bits into $HTTP_RAW_POST_DATA
3522 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3524 // prepare the directory
3525 $config = CRM_Core_Config
::singleton();
3526 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3527 if (!file_exists($defaultPath)) {
3528 mkdir($defaultPath, 0777, TRUE);
3531 // full path to the saved image including filename
3532 $destination = $defaultPath . $name;
3535 $jfh = fopen($destination, 'w') or die("can't open file");
3536 fwrite($jfh, $httpRawPostData);
3538 CRM_Utils_System
::civiExit();