3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 protected $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * Array of tabs to display on report.
167 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
169 * $this->tabs['OrderBy'] = array(
170 * 'title' => ts('Sorting'),
171 * 'tpl' => 'OrderBy',
172 * 'div_label' => 'order-by',
177 protected $tabs = array();
180 * Should we add paging.
184 protected $addPaging = TRUE;
187 * An attribute for checkbox/radio form field layout
191 protected $_fourColumnAttribute = array(
192 '</td><td width="25%">',
193 '</td><td width="25%">',
194 '</td><td width="25%">',
198 protected $_force = 1;
200 protected $_params = NULL;
201 protected $_formValues = NULL;
202 protected $_instanceValues = NULL;
204 protected $_instanceForm = FALSE;
205 protected $_criteriaForm = FALSE;
207 protected $_instanceButtonName = NULL;
208 protected $_createNewButtonName = NULL;
209 protected $_printButtonName = NULL;
210 protected $_pdfButtonName = NULL;
211 protected $_csvButtonName = NULL;
212 protected $_groupButtonName = NULL;
213 protected $_chartButtonName = NULL;
214 protected $_csvSupported = TRUE;
215 protected $_add2groupSupported = TRUE;
216 protected $_groups = NULL;
217 protected $_grandFlag = FALSE;
218 protected $_rowsFound = NULL;
219 protected $_selectAliases = array();
220 protected $_rollup = NULL;
225 protected $_aliases = array();
241 protected $_limit = NULL;
244 * This can be set to specify a limit to the number of rows
245 * Since it is currently envisaged as part of the api usage it is only being applied
246 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
247 * of the code (see limit() fn.
251 protected $_limitValue = NULL;
254 * This can be set to specify row offset
255 * See notes on _limitValue
258 protected $_offsetValue = NULL;
262 protected $_sections = NULL;
263 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
264 protected $_absoluteUrl = FALSE;
267 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
271 protected $_storeResultSet = FALSE;
274 * When _storeResultSet Flag is set use this var to store result set in form of array
278 protected $_resultSet = array();
281 * To what frequency group-by a date column
285 protected $_groupByDateFreq = array(
287 'YEARWEEK' => 'Week',
288 'QUARTER' => 'Quarter',
293 * Variables to hold the acl inner join and where clause
295 protected $_aclFrom = NULL;
296 protected $_aclWhere = NULL;
299 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
301 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
305 protected $_selectedTables;
308 * Array of DAO tables having columns included in WHERE or HAVING clause
312 protected $filteredTables;
315 * Output mode e.g 'print', 'csv', 'pdf'.
319 protected $_outputMode;
322 * Format of any chart in use.
324 * (it's unclear if this could be merged with outputMode at this stage)
330 public $_having = NULL;
331 public $_select = NULL;
332 public $_selectClauses = array();
333 public $_columnHeaders = array();
334 public $_orderBy = NULL;
335 public $_orderByFields = array();
336 public $_orderByArray = array();
337 public $_groupBy = NULL;
338 public $_whereClauses = array();
339 public $_havingClauses = array();
342 * DashBoardRowCount Dashboard row count
345 public $_dashBoardRowCount;
348 * Is this being called without a form controller (ie. the report is being render outside the normal form
349 * - e.g the api is retrieving the rows
352 public $noController = FALSE;
355 * Variable to hold the currency alias
357 protected $_currencyColumn = NULL;
362 protected $_interval;
367 protected $_sendmail;
380 * @var string Report description.
382 public $_description;
385 * @var bool Is an address field selected.
386 * This was intended to determine if the address table should be joined in
387 * The isTableSelected function is now preferred for this purpose
389 protected $_addressField;
392 * @var bool Is an email field selected.
393 * This was intended to determine if the email table should be joined in
394 * The isTableSelected function is now preferred for this purpose
396 protected $_emailField;
399 * @var bool Is a phone field selected.
400 * This was intended to determine if the phone table should be joined in
401 * The isTableSelected function is now preferred for this purpose
403 protected $_phoneField;
406 * @var bool Create new report instance? (or update existing) on save.
408 protected $_createNew;
411 * When a grand total row has calculated the status we pop it off to here.
413 * This allows us to access it from the stats function and avoid recalculating.
415 protected $rollupRow = array();
418 * SQL being run in this report.
420 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
428 * SQL being run in this report as an array.
430 * The sql in the report is stored in this variable in order to be returned to api & test calls.
439 public function __construct() {
440 parent
::__construct();
442 $this->addClass('crm-report-form');
444 if ($this->_tagFilter
) {
445 $this->buildTagFilter();
447 if ($this->_exposeContactID
) {
448 if (array_key_exists('civicrm_contact', $this->_columns
)) {
449 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
451 'title' => 'Contact ID',
457 if ($this->_groupFilter
) {
458 $this->buildGroupFilter();
461 // Get all custom groups
462 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
464 // Get the custom groupIds for which the user has VIEW permission
465 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
466 // and addCustomDataToColumns() will allow access to all custom groups.
467 $permCustomGroupIds = array();
468 if (!CRM_Core_Permission
::check('access all custom data')) {
469 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
470 // do not allow custom data for reports if user doesn't have
471 // permission to access custom data.
472 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
473 $this->_customGroupExtends
= array();
477 // merge custom data columns to _columns list, if any
478 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
480 // add / modify display columns, filters ..etc
481 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
483 //assign currencyColumn variable to tpl
484 $this->assign('currencyColumn', $this->_currencyColumn
);
488 * Shared pre-process function.
490 * If overriding preProcess function this should still be called.
494 public function preProcessCommon() {
496 = CRM_Utils_Request
::retrieve(
499 CRM_Core_DAO
::$_nullObject
502 $this->_dashBoardRowCount
503 = CRM_Utils_Request
::retrieve(
506 CRM_Core_DAO
::$_nullObject
509 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
511 $this->assign('section', $this->_section
);
512 CRM_Core_Region
::instance('page-header')->add(array(
513 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
515 if (!$this->noController
) {
516 $this->setID($this->get('instanceId'));
519 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
521 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
525 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
526 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
527 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
531 $this->assign('instanceId', $this->_id
);
532 $params = array('id' => $this->_id
);
533 $this->_instanceValues
= array();
534 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
536 $this->_instanceValues
538 if (empty($this->_instanceValues
)) {
539 CRM_Core_Error
::fatal("Report could not be loaded.");
541 $this->_title
= $this->_instanceValues
['title'];
542 if (!empty($this->_instanceValues
['permission']) &&
543 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
544 CRM_Core_Permission
::check('administer Reports')
547 CRM_Utils_System
::permissionDenied();
548 CRM_Utils_System
::civiExit();
551 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
553 $this->_formValues
= unserialize($formValues);
556 $this->_formValues
= NULL;
559 $this->setOutputMode();
561 if ($this->_outputMode
== 'copy') {
562 $this->_createNew
= TRUE;
563 $this->_params
= $this->_formValues
;
564 $this->_params
['view_mode'] = 'criteria';
565 $this->_params
['title'] = ts('(copy)') . $this->getTitle();
566 // Do not pass go. Do not collect another chance to re-run the same query.
567 CRM_Report_Form_Instance
::postProcess($this);
570 // lets always do a force if reset is found in the url.
571 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
572 // in the comment line above these 2.
573 if (!empty($_REQUEST['reset'])
574 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
579 $this->assign('mode', 'instance');
581 elseif (!$this->noController
) {
582 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
583 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
584 if (($instanceCount > 0) && $optionValueID) {
585 $this->assign('instanceUrl',
586 CRM_Utils_System
::url('civicrm/report/list',
587 "reset=1&ovid=$optionValueID"
591 if ($optionValueID) {
592 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
596 $this->assign('mode', 'template');
599 // lets display the Report Settings section
600 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
602 // Do not display Report Settings section if administer Reports permission is absent OR
603 // if report instance is reserved and administer reserved reports absent
604 if (!CRM_Core_Permission
::check('administer Reports') ||
605 ($this->_instanceValues
['is_reserved'] &&
606 !CRM_Core_Permission
::check('administer reserved reports'))
608 $this->_instanceForm
= FALSE;
611 $this->assign('criteriaForm', FALSE);
612 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
613 if (CRM_Core_Permission
::check('administer Reports') ||
614 CRM_Core_Permission
::check('access Report Criteria')
616 if (!$this->_instanceValues
['is_reserved'] ||
617 CRM_Core_Permission
::check('administer reserved reports')
619 $this->assign('criteriaForm', TRUE);
620 $this->_criteriaForm
= TRUE;
624 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
625 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
626 $this->_printButtonName
= $this->getButtonName('submit', 'print');
627 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
628 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
629 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
630 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
636 public function addBreadCrumb() {
640 'title' => ts('Report Templates'),
641 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
645 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
649 * Pre process function.
651 * Called prior to build form.
653 public function preProcess() {
654 $this->preProcessCommon();
657 $this->addBreadCrumb();
660 foreach ($this->_columns
as $tableName => $table) {
662 if (!isset($table['alias'])) {
663 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
667 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
670 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
672 $daoOrBaoName = NULL;
673 // higher preference to bao object
674 if (array_key_exists('bao', $table)) {
675 $daoOrBaoName = $table['bao'];
676 $expFields = $daoOrBaoName::exportableFields();
678 elseif (array_key_exists('dao', $table)) {
679 $daoOrBaoName = $table['dao'];
680 $expFields = $daoOrBaoName::export();
683 $expFields = array();
686 $doNotCopy = array('required');
688 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
689 foreach ($fieldGroups as $fieldGrp) {
690 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
691 foreach ($table[$fieldGrp] as $fieldName => $field) {
692 // $name is the field name used to reference the BAO/DAO export fields array
693 $name = isset($field['name']) ?
$field['name'] : $fieldName;
695 // Sometimes the field name key in the BAO/DAO export fields array is
696 // different from the actual database field name.
697 // Unset $field['name'] so that actual database field name can be obtained
698 // from the BAO/DAO export fields array.
699 unset($field['name']);
701 if (array_key_exists($name, $expFields)) {
702 foreach ($doNotCopy as $dnc) {
703 // unset the values we don't want to be copied.
704 unset($expFields[$name][$dnc]);
707 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
710 foreach ($expFields[$name] as $property => $val) {
711 if (!array_key_exists($property, $field)) {
712 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
719 if (!empty($field['no_repeat'])) {
720 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
722 if (!empty($field['no_display'])) {
723 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
726 // set alias = table-name, unless already set
727 $alias = isset($field['alias']) ?
$field['alias'] : (
728 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
730 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
732 // set name = fieldName, unless already set
733 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
734 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
737 // set dbAlias = alias.name, unless already set
738 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
739 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
741 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
744 // a few auto fills for filters
745 if ($fieldGrp == 'filters') {
746 // fill operator types
747 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
748 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
749 case CRM_Utils_Type
::T_MONEY
:
750 case CRM_Utils_Type
::T_FLOAT
:
751 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
754 case CRM_Utils_Type
::T_INT
:
755 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
758 case CRM_Utils_Type
::T_DATE
:
759 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
762 case CRM_Utils_Type
::T_BOOLEAN
:
763 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
764 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
765 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
776 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
778 // with multiple options operator-type is generally multi-select
779 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
780 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
782 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
793 // copy filters to a separate handy variable
794 if (array_key_exists('filters', $table)) {
795 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
798 if (array_key_exists('group_bys', $table)) {
799 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
802 if (array_key_exists('fields', $table)) {
803 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
808 $this->setDefaultValues(FALSE);
811 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
812 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
813 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
814 CRM_Report_Utils_Get
::processChart($this->_defaults
);
817 $this->_formValues
= $this->_defaults
;
818 $this->postProcess();
823 * Set default values.
825 * @param bool $freeze
829 public function setDefaultValues($freeze = TRUE) {
830 $freezeGroup = array();
832 // FIXME: generalizing form field naming conventions would reduce
833 // Lots of lines below.
834 foreach ($this->_columns
as $tableName => $table) {
835 if (array_key_exists('fields', $table)) {
836 foreach ($table['fields'] as $fieldName => $field) {
837 if (empty($field['no_display'])) {
838 if (isset($field['required'])) {
840 $this->_defaults
['fields'][$fieldName] = 1;
843 // find element object, so that we could use quickform's freeze method
844 // for required elements
845 $obj = $this->getElementFromGroup("fields", $fieldName);
847 $freezeGroup[] = $obj;
851 elseif (isset($field['default'])) {
852 $this->_defaults
['fields'][$fieldName] = $field['default'];
858 if (array_key_exists('group_bys', $table)) {
859 foreach ($table['group_bys'] as $fieldName => $field) {
860 if (isset($field['default'])) {
861 if (!empty($field['frequency'])) {
862 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
864 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
868 if (array_key_exists('filters', $table)) {
869 foreach ($table['filters'] as $fieldName => $field) {
870 if (isset($field['default'])) {
871 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
873 if (is_array($field['default'])) {
874 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
875 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
876 $this->_defaults
["{$fieldName}_relative"] = 0;
879 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
883 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
884 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
885 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
887 $this->_defaults
["{$fieldName}_value"] = $field['default'];
890 //assign default value as "in" for multiselect
891 //operator, To freeze the select element
892 if (CRM_Utils_Array
::value('operatorType', $field) ==
893 CRM_Report_Form
::OP_MULTISELECT
895 $this->_defaults
["{$fieldName}_op"] = 'in';
897 if (CRM_Utils_Array
::value('operatorType', $field) ==
898 CRM_Report_Form
::OP_ENTITYREF
900 $this->_defaults
["{$fieldName}_op"] = 'in';
902 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
903 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
905 $this->_defaults
["{$fieldName}_op"] = 'mhas';
907 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
908 $this->_defaults
["{$fieldName}_op"] = $op;
914 empty($this->_formValues
['order_bys']) &&
915 (array_key_exists('order_bys', $table) &&
916 is_array($table['order_bys']))
918 if (!array_key_exists('order_bys', $this->_defaults
)) {
919 $this->_defaults
['order_bys'] = array();
921 foreach ($table['order_bys'] as $fieldName => $field) {
922 if (!empty($field['default']) ||
!empty($field['default_order']) ||
923 CRM_Utils_Array
::value('default_is_section', $field) ||
924 !empty($field['default_weight'])
927 'column' => $fieldName,
928 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
929 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
932 if (!empty($field['default_weight'])) {
933 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
936 array_unshift($this->_defaults
['order_bys'], $order_by);
942 foreach ($this->_options
as $fieldName => $field) {
943 if (isset($field['default'])) {
944 $this->_defaults
['options'][$fieldName] = $field['default'];
949 if (!empty($this->_submitValues
)) {
950 $this->preProcessOrderBy($this->_submitValues
);
953 $this->preProcessOrderBy($this->_defaults
);
956 // lets finish freezing task here itself
957 if (!empty($freezeGroup)) {
958 foreach ($freezeGroup as $elem) {
963 if ($this->_formValues
) {
964 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
967 if ($this->_instanceValues
) {
968 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
971 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
973 return $this->_defaults
;
977 * Get element from group.
979 * @param string $group
980 * @param string $grpFieldName
984 public function getElementFromGroup($group, $grpFieldName) {
985 $eleObj = $this->getElement($group);
986 foreach ($eleObj->_elements
as $index => $obj) {
987 if ($grpFieldName == $obj->_attributes
['name']) {
995 * Setter for $_params.
997 * @param array $params
999 public function setParams($params) {
1000 $this->_params
= $params;
1006 * @param int $instanceID
1008 public function setID($instanceID) {
1009 $this->_id
= $instanceID;
1013 * Setter for $_force.
1015 * @param bool $isForce
1017 public function setForce($isForce) {
1018 $this->_force
= $isForce;
1022 * Setter for $_limitValue.
1024 * @param int $_limitValue
1026 public function setLimitValue($_limitValue) {
1027 $this->_limitValue
= $_limitValue;
1031 * Setter for $_offsetValue.
1033 * @param int $_offsetValue
1035 public function setOffsetValue($_offsetValue) {
1036 $this->_offsetValue
= $_offsetValue;
1040 * Setter for $addPaging.
1042 * @param bool $value
1044 public function setAddPaging($value) {
1045 $this->addPaging
= $value;
1049 * Getter for $_defaultValues.
1053 public function getDefaultValues() {
1054 return $this->_defaults
;
1058 * Add columns to report.
1060 public function addColumns() {
1063 foreach ($this->_columns
as $tableName => $table) {
1064 if (array_key_exists('fields', $table)) {
1065 foreach ($table['fields'] as $fieldName => $field) {
1067 if (empty($field['no_display'])) {
1068 foreach (array('table', 'field') as $var) {
1069 if (!empty($
{$var}['grouping'])) {
1070 if (!is_array($
{$var}['grouping'])) {
1071 $tableName = $
{$var}['grouping'];
1074 $tableName = array_keys($
{$var}['grouping']);
1075 $tableName = $tableName[0];
1076 $groupTitle = array_values($
{$var}['grouping']);
1077 $groupTitle = $groupTitle[0];
1082 if (!$groupTitle && isset($table['group_title'])) {
1083 $groupTitle = $table['group_title'];
1084 // Having a group_title is secret code for being a custom group
1085 // which cryptically translates to needing an accordion.
1086 // here we make that explicit.
1087 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1090 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1091 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1092 $colGroups[$tableName]['group_title'] = $groupTitle;
1094 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1100 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1101 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1103 if (!empty($colGroups)) {
1104 $this->tabs
['FieldSelection'] = array(
1105 'title' => ts('Columns'),
1106 'tpl' => 'FieldSelection',
1107 'div_label' => 'col-groups',
1110 // Note this assignment is only really required in buildForm. It is being 'over-called'
1111 // to reduce risk of being missed due to overridden functions.
1112 $this->assign('tabs', $this->tabs
);
1115 $this->assign('colGroups', $colGroups);
1119 * Add filters to report.
1121 public function addFilters() {
1122 $filters = $filterGroups = array();
1125 foreach ($this->_filters
as $table => $attributes) {
1126 if (isset($this->_columns
[$table]['group_title'])) {
1127 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1128 // which magically means to 'display in an accordian'
1129 // here we make this explicit.
1130 $filterGroups[$table] = array(
1131 'group_title' => $this->_columns
[$table]['group_title'],
1132 'use_accordian_for_field_selection' => TRUE,
1136 foreach ($attributes as $fieldName => $field) {
1137 // get ready with option value pair
1138 // @ 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
1140 $operations = $this->getOperationPair(
1141 CRM_Utils_Array
::value('operatorType', $field),
1144 $filters[$table][$fieldName] = $field;
1146 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1147 case CRM_Report_Form
::OP_MONTH
:
1148 if (!array_key_exists('options', $field) ||
1149 !is_array($field['options']) ||
empty($field['options'])
1151 // If there's no option list for this filter, define one.
1152 $field['options'] = array(
1154 2 => ts('February'),
1161 9 => ts('September'),
1162 10 => ts('October'),
1163 11 => ts('November'),
1164 12 => ts('December'),
1166 // Add this option list to this column _columns. This is
1167 // required so that filter statistics show properly.
1168 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1170 case CRM_Report_Form
::OP_MULTISELECT
:
1171 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1172 // assume a multi-select field
1173 if (!empty($field['options']) ||
1174 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1176 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1177 if (count($operations) <= 1) {
1180 if ($fieldName == 'state_province_id' ||
1181 $fieldName == 'county_id'
1183 $this->addChainSelect($fieldName . '_value', array(
1190 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1191 'style' => 'min-width:250px',
1192 'class' => 'crm-select2 huge',
1194 'placeholder' => ts('- select -'),
1200 case CRM_Report_Form
::OP_SELECT
:
1201 // assume a select field
1202 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1203 if (!empty($field['options'])) {
1204 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1208 case CRM_Report_Form
::OP_ENTITYREF
:
1209 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1210 $this->setEntityRefDefaults($field, $table);
1211 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1214 case CRM_Report_Form
::OP_DATE
:
1215 // build datetime fields
1216 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1220 case CRM_Report_Form
::OP_DATETIME
:
1221 // build datetime fields
1222 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1226 case CRM_Report_Form
::OP_INT
:
1227 case CRM_Report_Form
::OP_FLOAT
:
1228 // and a min value input box
1229 $this->add('text', "{$fieldName}_min", ts('Min'));
1230 // and a max value input box
1231 $this->add('text', "{$fieldName}_max", ts('Max'));
1233 // default type is string
1234 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1235 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1237 // we need text box for value input
1238 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1243 if (!empty($filters)) {
1244 $this->tabs
['Filters'] = array(
1245 'title' => ts('Filters'),
1247 'div_label' => 'set-filters',
1250 $this->assign('filters', $filters);
1251 $this->assign('filterGroups', $filterGroups);
1255 * Function to assign the tabs to the template in the correct order.
1257 * We want the tabs to wind up in this order (if not overridden).
1265 protected function assignTabs() {
1273 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1274 $order = array_merge($order, $this->tabs
);
1275 $this->assign('tabs', $order);
1279 * The intent is to add a tab for developers to view the sql.
1281 * Currently using dpm.
1283 * @param string $sql
1285 protected function addToDeveloperTab($sql) {
1286 if (!CRM_Core_Permission
::check('view report sql')) {
1289 $this->tabs
['Developer'] = array(
1290 'title' => ts('Developer'),
1291 'tpl' => 'Developer',
1292 'div_label' => 'set-developer',
1295 $this->assignTabs();
1296 $this->sqlArray
[] = $sql;
1297 foreach (array('LEFT JOIN') as $term) {
1298 $sql = str_replace($term, '<br>  ' . $term, $sql);
1300 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1301 $sql = str_replace($term, '<br><br>' . $term, $sql);
1303 $this->sql
.= $sql . "<br>";
1305 $this->assign('sql', $this->sql
);
1309 * Add options defined in $this->_options to the report.
1311 public function addOptions() {
1312 if (!empty($this->_options
)) {
1313 // FIXME: For now lets build all elements as checkboxes.
1314 // Once we clear with the format we can build elements based on type
1316 foreach ($this->_options
as $fieldName => $field) {
1319 if ($field['type'] == 'select') {
1320 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1322 elseif ($field['type'] == 'checkbox') {
1323 $options[$field['title']] = $fieldName;
1324 $this->addCheckBox($fieldName, NULL,
1326 NULL, NULL, NULL, $this->_fourColumnAttribute
1331 if (!empty($this->_options
)) {
1332 $this->tabs
['ReportOptions'] = array(
1333 'title' => ts('Display Options'),
1334 'tpl' => 'ReportOptions',
1335 'div_label' => 'other-options',
1338 $this->assign('otherOptions', $this->_options
);
1342 * Add chart options to the report.
1344 public function addChartOptions() {
1345 if (!empty($this->_charts
)) {
1346 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1347 $this->assign('charts', $this->_charts
);
1348 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1353 * Add group by options to the report.
1355 public function addGroupBys() {
1356 $options = $freqElements = array();
1358 foreach ($this->_columns
as $tableName => $table) {
1359 if (array_key_exists('group_bys', $table)) {
1360 foreach ($table['group_bys'] as $fieldName => $field) {
1361 if (!empty($field)) {
1362 $options[$field['title']] = $fieldName;
1363 if (!empty($field['frequency'])) {
1364 $freqElements[$field['title']] = $fieldName;
1370 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1371 NULL, NULL, NULL, $this->_fourColumnAttribute
1373 $this->assign('groupByElements', $options);
1374 if (!empty($options)) {
1375 $this->tabs
['GroupBy'] = array(
1376 'title' => ts('Grouping'),
1378 'div_label' => 'group-by-elements',
1382 foreach ($freqElements as $name) {
1383 $this->addElement('select', "group_bys_freq[$name]",
1384 ts('Frequency'), $this->_groupByDateFreq
1390 * Add data for order by tab.
1392 public function addOrderBys() {
1394 foreach ($this->_columns
as $tableName => $table) {
1396 // Report developer may define any column to order by; include these as order-by options.
1397 if (array_key_exists('order_bys', $table)) {
1398 foreach ($table['order_bys'] as $fieldName => $field) {
1399 if (!empty($field)) {
1400 $options[$fieldName] = $field['title'];
1405 // Add searchable custom fields as order-by options, if so requested
1406 // (These are already indexed, so allowing to order on them is cheap.)
1408 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1409 array_key_exists('extends', $table) && !empty($table['extends'])
1411 foreach ($table['fields'] as $fieldName => $field) {
1412 if (empty($field['no_display'])) {
1413 $options[$fieldName] = $field['title'];
1421 $this->assign('orderByOptions', $options);
1422 if (!empty($options)) {
1423 $this->tabs
['OrderBy'] = array(
1424 'title' => ts('Sorting'),
1426 'div_label' => 'order-by-elements',
1430 if (!empty($options)) {
1432 '-' => ' - none - ',
1434 for ($i = 1; $i <= 5; $i++
) {
1435 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1436 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1437 'ASC' => 'Ascending',
1438 'DESC' => 'Descending',
1440 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1441 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1447 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1449 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1450 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1453 public function buildInstanceAndButtons() {
1454 CRM_Report_Form_Instance
::buildForm($this);
1456 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1458 $this->addElement('submit', $this->_instanceButtonName
, $label);
1459 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1460 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1463 $this->addElement('submit', $this->_createNewButtonName
,
1464 ts('Save a Copy') . '...');
1466 $this->assign('instanceForm', $this->_instanceForm
);
1468 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1469 $this->addElement('submit', $this->_printButtonName
, $label);
1471 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1472 $this->addElement('submit', $this->_pdfButtonName
, $label);
1474 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1476 if ($this->_csvSupported
) {
1477 $this->addElement('submit', $this->_csvButtonName
, $label);
1480 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1481 $permission = CRM_Core_Permission
::getPermission();
1482 if ($permission == CRM_Core_Permission
::EDIT
&&
1483 $this->_add2groupSupported
1485 $this->addElement('select', 'groups', ts('Group'),
1486 array('' => ts('Add Contacts to Group')) +
1487 CRM_Core_PseudoConstant
::nestedGroup(),
1488 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1490 $this->assign('group', TRUE);
1493 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1495 $this->addChartOptions();
1496 $this->addButtons(array(
1499 'name' => ts('Preview Report'),
1500 'isDefault' => TRUE,
1507 * Main build form function.
1509 public function buildQuickForm() {
1510 $this->addColumns();
1512 $this->addFilters();
1514 $this->addOptions();
1516 $this->addGroupBys();
1518 $this->addOrderBys();
1520 $this->buildInstanceAndButtons();
1522 // Add form rule for report.
1523 if (is_callable(array(
1527 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1529 $this->assignTabs();
1533 * A form rule function for custom data.
1535 * The rule ensures that fields selected in group_by if any) should only be the ones
1536 * present in display/select fields criteria;
1537 * note: works if and only if any custom field selected in group_by.
1539 * @param array $fields
1540 * @param array $ignoreFields
1544 public function customDataFormRule($fields, $ignoreFields = array()) {
1546 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1547 !empty($fields['group_bys'])
1549 foreach ($this->_columns
as $tableName => $table) {
1550 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1551 substr($tableName, 0, 12) == 'custom_value') &&
1552 !empty($this->_columns
[$tableName]['fields'])
1554 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1555 if (array_key_exists($fieldName, $fields['group_bys']) &&
1556 !array_key_exists($fieldName, $fields['fields'])
1558 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1560 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1561 foreach ($fields['fields'] as $fld => $val) {
1562 if (!array_key_exists($fld, $fields['group_bys']) &&
1563 !in_array($fld, $ignoreFields)
1565 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1577 * Get operators to display on form.
1579 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1581 * @param string $type
1582 * @param string $fieldName
1586 public function getOperationPair($type = "string", $fieldName = NULL) {
1587 // FIXME: At some point we should move these key-val pairs
1588 // to option_group and option_value table.
1590 case CRM_Report_Form
::OP_INT
:
1591 case CRM_Report_Form
::OP_FLOAT
:
1594 'lte' => ts('Is less than or equal to'),
1595 'gte' => ts('Is greater than or equal to'),
1596 'bw' => ts('Is between'),
1597 'eq' => ts('Is equal to'),
1598 'lt' => ts('Is less than'),
1599 'gt' => ts('Is greater than'),
1600 'neq' => ts('Is not equal to'),
1601 'nbw' => ts('Is not between'),
1602 'nll' => ts('Is empty (Null)'),
1603 'nnll' => ts('Is not empty (Null)'),
1607 case CRM_Report_Form
::OP_SELECT
:
1609 'eq' => ts('Is equal to'),
1613 case CRM_Report_Form
::OP_MONTH
:
1614 case CRM_Report_Form
::OP_MULTISELECT
:
1615 case CRM_Report_Form
::OP_ENTITYREF
:
1618 'in' => ts('Is one of'),
1619 'notin' => ts('Is not one of'),
1623 case CRM_Report_Form
::OP_DATE
:
1626 'nll' => ts('Is empty (Null)'),
1627 'nnll' => ts('Is not empty (Null)'),
1631 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1632 // use this operator for the values, concatenated with separator. For e.g if
1633 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1635 'mhas' => ts('Is one of'),
1636 'mnot' => ts('Is not one of'),
1643 'has' => ts('Contains'),
1644 'sw' => ts('Starts with'),
1645 'ew' => ts('Ends with'),
1646 'nhas' => ts('Does not contain'),
1647 'eq' => ts('Is equal to'),
1648 'neq' => ts('Is not equal to'),
1649 'nll' => ts('Is empty (Null)'),
1650 'nnll' => ts('Is not empty (Null)'),
1657 * Build the tag filter field to display on the filters tab.
1659 public function buildTagFilter() {
1660 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1661 if (!empty($contactTags)) {
1662 $this->_columns
['civicrm_tag'] = array(
1663 'dao' => 'CRM_Core_DAO_Tag',
1667 'title' => ts('Tag'),
1668 'type' => CRM_Utils_Type
::T_INT
,
1670 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1671 'options' => $contactTags,
1679 * Adds group filters to _columns (called from _Construct).
1681 public function buildGroupFilter() {
1682 $this->_columns
['civicrm_group']['filters'] = array(
1684 'name' => 'group_id',
1685 'title' => ts('Group'),
1686 'type' => CRM_Utils_Type
::T_INT
,
1687 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1689 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1692 if (empty($this->_columns
['civicrm_group']['dao'])) {
1693 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1695 if (empty($this->_columns
['civicrm_group']['alias'])) {
1696 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1701 * Get SQL operator from form text version.
1703 * @param string $operator
1707 public function getSQLOperator($operator = "like") {
1708 switch ($operator) {
1741 return 'IS NOT NULL';
1750 * Generate where clause.
1752 * This can be overridden in reports for special treatment of a field
1754 * @param array $field Field specifications
1755 * @param string $op Query operator (not an exact match to sql)
1756 * @param mixed $value
1760 * @return null|string
1762 public function whereClause(&$field, $op, $value, $min, $max) {
1764 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1766 // CRM-18010: Ensure type of each report filters
1768 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1775 if (($min !== NULL && strlen($min) > 0) ||
1776 ($max !== NULL && strlen($max) > 0)
1778 $min = CRM_Utils_Type
::escape($min, $type);
1779 $max = CRM_Utils_Type
::escape($max, $type);
1783 $clauses[] = "( {$field['dbAlias']} >= $min )";
1786 $clauses[] = "( {$field['dbAlias']} < $min )";
1791 $clauses[] = "( {$field['dbAlias']} <= $max )";
1794 $clauses[] = "( {$field['dbAlias']} > $max )";
1798 if (!empty($clauses)) {
1800 $clause = implode(' AND ', $clauses);
1803 $clause = implode(' OR ', $clauses);
1811 if ($value !== NULL && strlen($value) > 0) {
1812 $value = CRM_Utils_Type
::escape($value, $type);
1813 if (strpos($value, '%') === FALSE) {
1814 $value = "'%{$value}%'";
1817 $value = "'{$value}'";
1819 $sqlOP = $this->getSQLOperator($op);
1820 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1826 if (is_string($value) && strlen($value)) {
1827 $value = explode(',', $value);
1829 if ($value !== NULL && is_array($value) && count($value) > 0) {
1830 $sqlOP = $this->getSQLOperator($op);
1831 if (CRM_Utils_Array
::value('type', $field) ==
1832 CRM_Utils_Type
::T_STRING
1834 //cycle through selections and escape values
1835 foreach ($value as $key => $selection) {
1836 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1839 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1843 // for numerical values
1844 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1847 if ($op == 'notin') {
1848 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1851 $clause = "( " . $clause . " )";
1858 // multiple has or multiple not
1859 if ($value !== NULL && count($value) > 0) {
1860 $value = CRM_Utils_Type
::escapeAll($value, $type);
1861 $operator = $op == 'mnot' ?
'NOT' : '';
1862 $regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', (array) $value) . "[[:cntrl:]]*";
1863 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1869 if ($value !== NULL && strlen($value) > 0) {
1870 $value = CRM_Utils_Type
::escape($value, $type);
1871 if (strpos($value, '%') === FALSE) {
1873 $value = "'{$value}%'";
1876 $value = "'%{$value}'";
1880 $value = "'{$value}'";
1882 $sqlOP = $this->getSQLOperator($op);
1883 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1889 $sqlOP = $this->getSQLOperator($op);
1890 $clause = "( {$field['dbAlias']} $sqlOP )";
1894 if ($value !== NULL && strlen($value) > 0) {
1895 if (isset($field['clause'])) {
1896 // FIXME: we not doing escape here. Better solution is to use two
1897 // different types - data-type and filter-type
1898 $clause = $field['clause'];
1901 $value = CRM_Utils_Type
::escape($value, $type);
1902 $sqlOP = $this->getSQLOperator($op);
1903 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1904 $value = "'{$value}'";
1906 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1912 if (!empty($field['group']) && $clause) {
1913 $clause = $this->whereGroupClause($field, $value, $op);
1915 elseif (!empty($field['tag']) && $clause) {
1916 // not using left join in query because if any contact
1917 // belongs to more than one tag, results duplicate
1919 $clause = $this->whereTagClause($field, $value, $op);
1921 elseif (!empty($field['membership_org']) && $clause) {
1922 $clause = $this->whereMembershipOrgClause($value, $op);
1924 elseif (!empty($field['membership_type']) && $clause) {
1925 $clause = $this->whereMembershipTypeClause($value, $op);
1931 * Get SQL where clause for a date field.
1933 * @param string $fieldName
1934 * @param string $relative
1935 * @param string $from
1937 * @param string $type
1938 * @param string $fromTime
1939 * @param string $toTime
1941 * @return null|string
1943 public function dateClause(
1945 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1948 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1949 $sqlOP = $this->getSQLOperator($relative);
1950 return "( {$fieldName} {$sqlOP} )";
1953 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1956 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1957 $clauses[] = "( {$fieldName} >= $from )";
1961 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1962 $clauses[] = "( {$fieldName} <= {$to} )";
1965 if (!empty($clauses)) {
1966 return implode(' AND ', $clauses);
1973 * Possibly unused function.
1975 * @todo - could not find any instances where this is called
1977 * @param bool $relative
1978 * @param string $from
1981 * @return string|NULL
1983 public function dateDisplay($relative, $from, $to) {
1984 list($from, $to) = $this->getFromTo($relative, $from, $to);
1987 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1990 $clauses[] = 'Past';
1994 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1997 $clauses[] = 'Today';
2000 if (!empty($clauses)) {
2001 return implode(' - ', $clauses);
2008 * Get values for from and to for date ranges.
2010 * @param bool $relative
2011 * @param string $from
2013 * @param string $fromTime
2014 * @param string $toTime
2018 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2019 if (empty($toTime)) {
2022 //FIX ME not working for relative
2024 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2025 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2026 $from = substr($dateRange['from'], 0, 8);
2027 //Take only Date Part, Sometime Time part is also present in 'to'
2028 $to = substr($dateRange['to'], 0, 8);
2030 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2031 $to = CRM_Utils_Date
::processDate($to, $toTime);
2032 return array($from, $to);
2036 * Alter display of rows.
2038 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2039 * such as rendering contacts as links.
2041 * @param array $rows
2042 * Rows generated by SQL, with an array for each row.
2044 public function alterDisplay(&$rows) {
2048 * Alter the way in which custom data fields are displayed.
2050 * @param array $rows
2052 public function alterCustomDataDisplay(&$rows) {
2053 // custom code to alter rows having custom values
2054 if (empty($this->_customGroupExtends
)) {
2058 $customFieldIds = array();
2059 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2060 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2061 $customFieldIds[$fieldAlias] = $fieldId;
2064 if (empty($customFieldIds)) {
2068 // skip for type date and ContactReference since date format is already handled
2070 SELECT cg.table_name, cf.id
2071 FROM civicrm_custom_field cf
2072 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2073 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2074 cg.is_active = 1 AND
2075 cf.is_active = 1 AND
2076 cf.is_searchable = 1 AND
2077 cf.data_type NOT IN ('ContactReference', 'Date') AND
2078 cf.id IN (" . implode(",", $customFieldIds) . ")";
2080 $dao = CRM_Core_DAO
::executeQuery($query);
2081 while ($dao->fetch()) {
2082 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2086 $entryFound = FALSE;
2087 foreach ($rows as $rowNum => $row) {
2088 foreach ($row as $tableCol => $val) {
2089 if (array_key_exists($tableCol, $customFields)) {
2090 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2095 // skip looking further in rows, if first row itself doesn't
2096 // have the column we need
2104 * Remove duplicate rows.
2106 * @param array $rows
2108 public function removeDuplicates(&$rows) {
2109 if (empty($this->_noRepeats
)) {
2112 $checkList = array();
2114 foreach ($rows as $key => $list) {
2115 foreach ($list as $colName => $colVal) {
2116 if (array_key_exists($colName, $checkList) &&
2117 $checkList[$colName] == $colVal
2119 $rows[$key][$colName] = "";
2121 if (in_array($colName, $this->_noRepeats
)) {
2122 $checkList[$colName] = $colVal;
2129 * Fix subtotal display.
2132 * @param array $fields
2133 * @param bool $subtotal
2135 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2136 foreach ($row as $colName => $colVal) {
2137 if (in_array($colName, $fields)) {
2139 elseif (isset($this->_columnHeaders
[$colName])) {
2141 $row[$colName] = "Subtotal";
2145 unset($row[$colName]);
2152 * Calculate grant total.
2154 * @param array $rows
2158 public function grandTotal(&$rows) {
2159 if (!$this->_rollup ||
count($rows) == 1) {
2163 $this->moveSummaryColumnsToTheRightHandSide();
2165 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2169 $this->rollupRow
= array_pop($rows);
2171 foreach ($this->_columnHeaders
as $fld => $val) {
2172 if (!in_array($fld, $this->_statFields
)) {
2173 if (!$this->_grandFlag
) {
2174 $this->rollupRow
[$fld] = ts('Grand Total');
2175 $this->_grandFlag
= TRUE;
2178 $this->rollupRow
[$fld] = "";
2183 $this->assign('grandStat', $this->rollupRow
);
2188 * Format display output.
2190 * @param array $rows
2191 * @param bool $pager
2193 public function formatDisplay(&$rows, $pager = TRUE) {
2194 // set pager based on if any limit was applied in the query.
2199 // allow building charts if any
2200 if (!empty($this->_params
['charts']) && !empty($rows)) {
2201 $this->buildChart($rows);
2202 $this->assign('chartEnabled', TRUE);
2203 $this->_chartId
= "{$this->_params['charts']}_" .
2204 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2206 $this->assign('chartId', $this->_chartId
);
2209 // unset columns not to be displayed.
2210 foreach ($this->_columnHeaders
as $key => $value) {
2211 if (!empty($value['no_display'])) {
2212 unset($this->_columnHeaders
[$key]);
2216 // unset columns not to be displayed.
2217 if (!empty($rows)) {
2218 foreach ($this->_noDisplay
as $noDisplayField) {
2219 foreach ($rows as $rowNum => $row) {
2220 unset($this->_columnHeaders
[$noDisplayField]);
2225 // build array of section totals
2226 $this->sectionTotals();
2228 // process grand-total row
2229 $this->grandTotal($rows);
2231 // use this method for formatting rows for display purpose.
2232 $this->alterDisplay($rows);
2233 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2235 // use this method for formatting custom rows for display purpose.
2236 $this->alterCustomDataDisplay($rows);
2242 * @param array $rows
2244 public function buildChart(&$rows) {
2245 // override this method for building charts.
2248 // select() method below has been added recently (v3.3), and many of the report templates might
2249 // still be having their own select() method. We should fix them as and when encountered and move
2250 // towards generalizing the select() method below.
2253 * Generate the SELECT clause and set class variable $_select.
2255 public function select() {
2256 $select = $this->_selectAliases
= array();
2258 foreach ($this->_columns
as $tableName => $table) {
2259 if (array_key_exists('fields', $table)) {
2260 foreach ($table['fields'] as $fieldName => $field) {
2261 if ($tableName == 'civicrm_address') {
2262 $this->_addressField
= TRUE;
2264 if ($tableName == 'civicrm_email') {
2265 $this->_emailField
= TRUE;
2267 if ($tableName == 'civicrm_phone') {
2268 $this->_phoneField
= TRUE;
2271 if (!empty($field['required']) ||
2272 !empty($this->_params
['fields'][$fieldName])
2275 // 1. In many cases we want select clause to be built in slightly different way
2276 // for a particular field of a particular type.
2277 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2279 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2280 if ($selectClause) {
2281 $select[] = $selectClause;
2285 // include statistics columns only if set
2286 if (!empty($field['statistics'])) {
2287 foreach ($field['statistics'] as $stat => $label) {
2288 $alias = "{$tableName}_{$fieldName}_{$stat}";
2289 switch (strtolower($stat)) {
2292 $select[] = "$stat({$field['dbAlias']}) as $alias";
2293 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2294 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2295 $this->_statFields
[$label] = $alias;
2296 $this->_selectAliases
[] = $alias;
2300 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2301 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2302 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2303 $this->_statFields
[$label] = $alias;
2304 $this->_selectAliases
[] = $alias;
2307 case 'count_distinct':
2308 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2309 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2310 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2311 $this->_statFields
[$label] = $alias;
2312 $this->_selectAliases
[] = $alias;
2316 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2317 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2318 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2319 $this->_statFields
[$label] = $alias;
2320 $this->_selectAliases
[] = $alias;
2326 $alias = "{$tableName}_{$fieldName}";
2327 $select[] = "{$field['dbAlias']} as $alias";
2328 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2329 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2330 $this->_selectAliases
[] = $alias;
2336 // select for group bys
2337 if (array_key_exists('group_bys', $table)) {
2338 foreach ($table['group_bys'] as $fieldName => $field) {
2340 if ($tableName == 'civicrm_address') {
2341 $this->_addressField
= TRUE;
2343 if ($tableName == 'civicrm_email') {
2344 $this->_emailField
= TRUE;
2346 if ($tableName == 'civicrm_phone') {
2347 $this->_phoneField
= TRUE;
2349 // 1. In many cases we want select clause to be built in slightly different way
2350 // for a particular field of a particular type.
2351 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2353 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2354 if ($selectClause) {
2355 $select[] = $selectClause;
2359 if (!empty($this->_params
['group_bys']) &&
2360 !empty($this->_params
['group_bys'][$fieldName]) &&
2361 !empty($this->_params
['group_bys_freq'])
2363 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2365 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2366 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2367 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2368 $field['title'] = 'Week';
2372 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2373 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2374 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2375 $field['title'] = 'Year';
2379 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2380 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2381 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2382 $field['title'] = 'Month';
2386 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2387 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2388 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2389 $field['title'] = 'Quarter';
2392 // for graphs and charts -
2393 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2394 $this->_interval
= $field['title'];
2395 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2396 = $field['title'] . ' Beginning';
2397 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2398 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2400 // just to make sure these values are transferred to rows.
2401 // since we 'll need them for calculation purpose,
2402 // e.g making subtotals look nicer or graphs
2403 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2404 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2411 $this->_selectClauses
= $select;
2412 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2416 * Build select clause for a single field.
2418 * @param string $tableName
2419 * @param string $tableKey
2420 * @param string $fieldName
2421 * @param string $field
2425 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2430 * Build where clause.
2432 public function where() {
2433 $this->storeWhereHavingClauseArray();
2435 if (empty($this->_whereClauses
)) {
2436 $this->_where
= "WHERE ( 1 ) ";
2437 $this->_having
= "";
2440 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2443 if ($this->_aclWhere
) {
2444 $this->_where
.= " AND {$this->_aclWhere} ";
2447 if (!empty($this->_havingClauses
)) {
2448 // use this clause to construct group by clause.
2449 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2454 * Store Where clauses into an array.
2456 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2457 * temp table that may not be part of the final where clause or added
2458 * in other functions
2460 public function storeWhereHavingClauseArray() {
2461 foreach ($this->_columns
as $tableName => $table) {
2462 if (array_key_exists('filters', $table)) {
2463 foreach ($table['filters'] as $fieldName => $field) {
2464 // respect pseudofield to filter spec so fields can be marked as
2465 // not to be handled here
2466 if (!empty($field['pseudofield'])) {
2470 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2471 if (CRM_Utils_Array
::value('operatorType', $field) ==
2472 CRM_Report_Form
::OP_MONTH
2474 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2475 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2476 if (is_array($value) && !empty($value)) {
2478 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2483 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2484 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2485 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2486 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2487 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2488 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2492 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2494 $clause = $this->whereClause($field,
2496 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2497 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2498 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2503 if (!empty($clause)) {
2504 if (!empty($field['having'])) {
2505 $this->_havingClauses
[] = $clause;
2508 $this->_whereClauses
[] = $clause;
2520 public function processReportMode() {
2521 $this->setOutputMode();
2524 = CRM_Utils_Request
::retrieve(
2527 CRM_Core_DAO
::$_nullObject
2530 $this->_absoluteUrl
= FALSE;
2532 $this->assign('printOnly', FALSE);
2534 if ($this->_outputMode
== 'print' ||
2535 ($this->_sendmail
&& !$this->_outputMode
)
2537 $this->assign('printOnly', TRUE);
2539 $this->addPaging
= FALSE;
2540 $this->assign('outputMode', 'print');
2541 $this->_outputMode
= 'print';
2542 if ($this->_sendmail
) {
2543 $this->_absoluteUrl
= TRUE;
2546 elseif ($this->_outputMode
== 'pdf') {
2548 $this->addPaging
= FALSE;
2549 $this->_absoluteUrl
= TRUE;
2551 elseif ($this->_outputMode
== 'csv') {
2553 $this->_absoluteUrl
= TRUE;
2554 $this->addPaging
= FALSE;
2556 elseif ($this->_outputMode
== 'group') {
2557 $this->assign('outputMode', 'group');
2559 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2560 $this->assign('outputMode', 'create_report');
2562 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2563 $this->_createNew
= TRUE;
2566 $this->assign('outputMode', $this->_outputMode
);
2567 $this->assign('printOnly', $printOnly);
2568 // Get today's date to include in printed reports
2570 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2571 $this->assign('reportDate', $reportDate);
2576 * Post Processing function for Form.
2578 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2579 * This function is not accessed when the api calls the report.
2581 public function beginPostProcess() {
2582 $this->setParams($this->controller
->exportValues($this->_name
));
2583 if (empty($this->_params
) &&
2586 $this->setParams($this->_formValues
);
2589 // hack to fix params when submitted from dashboard, CRM-8532
2590 // fields array is missing because form building etc is skipped
2591 // in dashboard mode for report
2592 //@todo - this could be done in the dashboard no we have a setter
2593 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2594 $this->setParams($this->_formValues
);
2597 $this->_formValues
= $this->_params
;
2598 if (CRM_Core_Permission
::check('administer Reports') &&
2599 isset($this->_id
) &&
2600 ($this->_instanceButtonName
==
2601 $this->controller
->getButtonName() . '_save' ||
2602 $this->_chartButtonName
== $this->controller
->getButtonName()
2605 $this->assign('updateReportButton', TRUE);
2608 $this->processReportMode();
2610 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2611 $this->_createNew
= ($this->_outputMode
== 'copy');
2612 // Do not pass go. Do not collect another chance to re-run the same query.
2613 // This will be called from the button - there is an earlier response to the url
2614 // perhaps they can still be consolidated more.
2615 CRM_Report_Form_Instance
::postProcess($this);
2617 $this->beginPostProcessCommon();
2621 * BeginPostProcess function run in both report mode and non-report mode (api).
2623 public function beginPostProcessCommon() {}
2626 * Build the report query.
2628 * @param bool $applyLimit
2632 public function buildQuery($applyLimit = TRUE) {
2635 $this->customDataFrom();
2640 // order_by columns not selected for display need to be included in SELECT
2641 $unselectedSectionColumns = $this->unselectedSectionColumns();
2642 foreach ($unselectedSectionColumns as $alias => $section) {
2643 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2646 if ($applyLimit && empty($this->_params
['charts'])) {
2649 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2651 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2652 $this->addToDeveloperTab($sql);
2657 * Build group by clause.
2659 public function groupBy() {
2660 $groupBys = array();
2661 if (!empty($this->_params
['group_bys']) &&
2662 is_array($this->_params
['group_bys'])
2664 foreach ($this->_columns
as $tableName => $table) {
2665 if (array_key_exists('group_bys', $table)) {
2666 foreach ($table['group_bys'] as $fieldName => $field) {
2667 if (!empty($this->_params
['group_bys'][$fieldName])) {
2668 $groupBys[] = $field['dbAlias'];
2675 if (!empty($groupBys)) {
2676 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2681 * Build order by clause.
2683 public function orderBy() {
2684 $this->_orderBy
= "";
2685 $this->_sections
= array();
2686 $this->storeOrderByArray();
2687 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2688 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2690 $this->assign('sections', $this->_sections
);
2694 * Extract order by fields and store as an array.
2696 * In some cases other functions want to know which fields are selected for ordering by
2697 * Separating this into a separate function allows it to be called separately from constructing
2698 * the order by clause
2700 public function storeOrderByArray() {
2701 $orderBys = array();
2703 if (!empty($this->_params
['order_bys']) &&
2704 is_array($this->_params
['order_bys']) &&
2705 !empty($this->_params
['order_bys'])
2708 // Process order_bys in user-specified order
2709 foreach ($this->_params
['order_bys'] as $orderBy) {
2710 $orderByField = array();
2711 foreach ($this->_columns
as $tableName => $table) {
2712 if (array_key_exists('order_bys', $table)) {
2713 // For DAO columns defined in $this->_columns
2714 $fields = $table['order_bys'];
2716 elseif (array_key_exists('extends', $table)) {
2717 // For custom fields referenced in $this->_customGroupExtends
2718 $fields = CRM_Utils_Array
::value('fields', $table, array());
2723 if (!empty($fields) && is_array($fields)) {
2724 foreach ($fields as $fieldName => $field) {
2725 if ($fieldName == $orderBy['column']) {
2726 $orderByField = array_merge($field, $orderBy);
2727 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2734 if (!empty($orderByField)) {
2735 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2736 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2738 // Record any section headers for assignment to the template
2739 if (!empty($orderBy['section'])) {
2740 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2741 $this->_sections
[$orderByField['tplField']] = $orderByField;
2747 $this->_orderByArray
= $orderBys;
2749 $this->assign('sections', $this->_sections
);
2753 * Determine unselected columns.
2757 public function unselectedSectionColumns() {
2758 if (is_array($this->_sections
)) {
2759 return array_diff_key($this->_sections
, $this->getSelectColumns());
2767 * Build output rows.
2769 * @param string $sql
2770 * @param array $rows
2772 public function buildRows($sql, &$rows) {
2773 $dao = CRM_Core_DAO
::executeQuery($sql);
2774 if (!is_array($rows)) {
2778 // use this method to modify $this->_columnHeaders
2779 $this->modifyColumnHeaders();
2781 $unselectedSectionColumns = $this->unselectedSectionColumns();
2783 while ($dao->fetch()) {
2785 foreach ($this->_columnHeaders
as $key => $value) {
2786 if (property_exists($dao, $key)) {
2787 $row[$key] = $dao->$key;
2791 // section headers not selected for display need to be added to row
2792 foreach ($unselectedSectionColumns as $key => $values) {
2793 if (property_exists($dao, $key)) {
2794 $row[$key] = $dao->$key;
2803 * Calculate section totals.
2805 * When "order by" fields are marked as sections, this assigns to the template
2806 * an array of total counts for each section. This data is used by the Smarty
2807 * plugin {sectionTotal}.
2809 public function sectionTotals() {
2811 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2812 if (empty($this->_selectAliases
)) {
2816 if (!empty($this->_sections
)) {
2817 // build the query with no LIMIT clause
2818 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2819 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2821 // pull section aliases out of $this->_sections
2822 $sectionAliases = array_keys($this->_sections
);
2825 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2826 $ifnulls[] = "ifnull($alias, '') as $alias";
2829 // Group (un-limited) report by all aliases and get counts. This might
2830 // be done more efficiently when the contents of $sql are known, ie. by
2831 // overriding this method in the report class.
2833 $query = "select " . implode(", ", $ifnulls) .
2834 ", count(*) as ct from ($sql) as subquery group by " .
2835 implode(", ", $sectionAliases);
2837 // initialize array of total counts
2839 $dao = CRM_Core_DAO
::executeQuery($query);
2840 while ($dao->fetch()) {
2842 // let $this->_alterDisplay translate any integer ids to human-readable values.
2843 $rows[0] = $dao->toArray();
2844 $this->alterDisplay($rows);
2847 // add totals for all permutations of section values
2850 $aliasCount = count($sectionAliases);
2851 foreach ($sectionAliases as $alias) {
2852 $values[] = $row[$alias];
2853 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2854 if ($i == $aliasCount) {
2855 // the last alias is the lowest-level section header; use count as-is
2856 $totals[$key] = $dao->ct
;
2859 // other aliases are higher level; roll count into their total
2860 $totals[$key] +
= $dao->ct
;
2864 $this->assign('sectionTotals', $totals);
2869 * Modify column headers.
2871 public function modifyColumnHeaders() {
2872 // use this method to modify $this->_columnHeaders
2876 * Move totals columns to the right edge of the table.
2878 * It seems like a more logical layout to have any totals columns on the far right regardless of
2879 * the location of the rest of their table.
2881 public function moveSummaryColumnsToTheRightHandSide() {
2882 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2883 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2887 * Assign rows to the template.
2889 * @param array $rows
2891 public function doTemplateAssignment(&$rows) {
2892 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2893 $this->assign_by_ref('rows', $rows);
2894 $this->assign('statistics', $this->statistics($rows));
2898 * Build report statistics.
2900 * Override this method to build your own statistics.
2902 * @param array $rows
2906 public function statistics(&$rows) {
2907 $statistics = array();
2909 $count = count($rows);
2910 // Why do we increment the count for rollup seems to artificially inflate the count.
2911 // It seems perhaps intentional to include the summary row in the count of results - although
2912 // this just seems odd.
2913 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2917 $this->countStat($statistics, $count);
2919 $this->groupByStat($statistics);
2921 $this->filterStat($statistics);
2927 * Add count statistics.
2929 * @param array $statistics
2932 public function countStat(&$statistics, $count) {
2933 $statistics['counts']['rowCount'] = array(
2934 'title' => ts('Row(s) Listed'),
2938 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2939 $statistics['counts']['rowsFound'] = array(
2940 'title' => ts('Total Row(s)'),
2941 'value' => $this->_rowsFound
,
2947 * Add group by statistics.
2949 * @param array $statistics
2951 public function groupByStat(&$statistics) {
2952 if (!empty($this->_params
['group_bys']) &&
2953 is_array($this->_params
['group_bys']) &&
2954 !empty($this->_params
['group_bys'])
2956 foreach ($this->_columns
as $tableName => $table) {
2957 if (array_key_exists('group_bys', $table)) {
2958 foreach ($table['group_bys'] as $fieldName => $field) {
2959 if (!empty($this->_params
['group_bys'][$fieldName])) {
2960 $combinations[] = $field['title'];
2965 $statistics['groups'][] = array(
2966 'title' => ts('Grouping(s)'),
2967 'value' => implode(' & ', $combinations),
2973 * Filter statistics.
2975 * @param array $statistics
2977 public function filterStat(&$statistics) {
2978 foreach ($this->_columns
as $tableName => $table) {
2979 if (array_key_exists('filters', $table)) {
2980 foreach ($table['filters'] as $fieldName => $field) {
2981 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2982 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2983 CRM_Utils_Array
::value('operatorType', $field) !=
2984 CRM_Report_Form
::OP_MONTH
2988 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2989 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2990 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2991 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2992 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2994 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2995 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2997 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2998 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3001 $statistics['filters'][] = array(
3002 'title' => $field['title'],
3003 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3006 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3007 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3009 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3010 $statistics['filters'][] = array(
3011 'title' => $field['title'],
3012 'value' => $pair[$rel],
3017 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3020 $pair = $this->getOperationPair(
3021 CRM_Utils_Array
::value('operatorType', $field),
3024 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3025 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3026 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3027 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3028 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3030 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3031 $this->setEntityRefDefaults($field, $tableName);
3032 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3033 array('id' => $val) +
3034 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3036 foreach ($result['values'] as $v) {
3037 $values[] = $v['label'];
3039 $value = "{$pair[$op]} " . implode(', ', $values);
3041 elseif ($op == 'nll' ||
$op == 'nnll') {
3042 $value = $pair[$op];
3044 elseif (is_array($val) && (!empty($val))) {
3045 $options = CRM_Utils_Array
::value('options', $field, array());
3046 foreach ($val as $key => $valIds) {
3047 if (isset($options[$valIds])) {
3048 $val[$key] = $options[$valIds];
3051 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3052 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3053 $val = implode(', ', $val);
3054 $value = "{$pair[$op]} " . $val;
3056 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3057 isset($field['options']) &&
3058 is_array($field['options']) && !empty($field['options'])
3060 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3061 CRM_Utils_Array
::value($val, $field['options'], $val);
3064 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3068 $statistics['filters'][] = array(
3069 'title' => CRM_Utils_Array
::value('title', $field),
3080 * End post processing.
3082 * @param array|null $rows
3084 public function endPostProcess(&$rows = NULL) {
3085 if ($this->_storeResultSet
) {
3086 $this->_resultSet
= $rows;
3089 if ($this->_outputMode
== 'print' ||
3090 $this->_outputMode
== 'pdf' ||
3094 $content = $this->compileContent();
3095 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3099 if ($this->_sendmail
) {
3100 $config = CRM_Core_Config
::singleton();
3101 $attachments = array();
3103 if ($this->_outputMode
== 'csv') {
3105 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3106 ": {$url}</p>" . '<p>' .
3107 ts('The report is attached as a CSV file.') . '</p>' .
3108 $this->_formValues
['report_footer'];
3110 $csvFullFilename = $config->templateCompileDir
.
3111 CRM_Utils_File
::makeFileName('CiviReport.csv');
3112 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3113 file_put_contents($csvFullFilename, $csvContent);
3114 $attachments[] = array(
3115 'fullPath' => $csvFullFilename,
3116 'mime_type' => 'text/csv',
3117 'cleanName' => 'CiviReport.csv',
3120 if ($this->_outputMode
== 'pdf') {
3121 // generate PDF content
3122 $pdfFullFilename = $config->templateCompileDir
.
3123 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3124 file_put_contents($pdfFullFilename,
3125 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3126 TRUE, array('orientation' => 'landscape')
3129 // generate Email Content
3131 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3132 ": {$url}</p>" . '<p>' .
3133 ts('The report is attached as a PDF file.') . '</p>' .
3134 $this->_formValues
['report_footer'];
3136 $attachments[] = array(
3137 'fullPath' => $pdfFullFilename,
3138 'mime_type' => 'application/pdf',
3139 'cleanName' => 'CiviReport.pdf',
3143 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3144 $this->_outputMode
, $attachments
3147 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3150 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3154 elseif ($this->_outputMode
== 'print') {
3158 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3159 $config = CRM_Core_Config
::singleton();
3160 //get chart image name
3161 $chartImg = $this->_chartId
. '.png';
3162 //get image url path
3164 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3166 $uploadUrl .= $chartImg;
3167 //get image doc path to overwrite
3169 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3170 'openFlashChart/' . $chartImg;
3172 $chart = imagecreatefrompng($uploadUrl);
3173 //convert it into formatted png
3174 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3175 //overwrite with same image
3176 imagepng($chart, $uploadImg);
3178 imagedestroy($chart);
3180 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3182 CRM_Utils_System
::civiExit();
3184 elseif ($this->_outputMode
== 'csv') {
3185 CRM_Report_Utils_Report
::export2csv($this, $rows);
3187 elseif ($this->_outputMode
== 'group') {
3188 $group = $this->_params
['groups'];
3189 $this->add2group($group);
3194 * Set store result set indicator to TRUE.
3196 * @todo explain what this does
3198 public function storeResultSet() {
3199 $this->_storeResultSet
= TRUE;
3207 public function getResultSet() {
3208 return $this->_resultSet
;
3212 * Get the sql used to generate the report.
3216 public function getReportSql() {
3217 return $this->sqlArray
;
3221 * Use the form name to create the tpl file name.
3225 public function getTemplateFileName() {
3226 $defaultTpl = parent
::getTemplateFileName();
3227 $template = CRM_Core_Smarty
::singleton();
3228 if (!$template->template_exists($defaultTpl)) {
3229 $defaultTpl = 'CRM/Report/Form.tpl';
3235 * Compile the report content.
3237 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3241 public function compileContent() {
3242 $templateFile = $this->getHookedTemplateFileName();
3243 return $this->_formValues
['report_header'] .
3244 CRM_Core_Form
::$_template->fetch($templateFile) .
3245 $this->_formValues
['report_footer'];
3250 * Post process function.
3252 public function postProcess() {
3253 // get ready with post process params
3254 $this->beginPostProcess();
3257 $sql = $this->buildQuery();
3259 // build array of result based on column headers. This method also allows
3260 // modifying column headers before using it to build result set i.e $rows.
3262 $this->buildRows($sql, $rows);
3264 // format result set.
3265 $this->formatDisplay($rows);
3267 // assign variables to templates
3268 $this->doTemplateAssignment($rows);
3270 // do print / pdf / instance stuff if needed
3271 $this->endPostProcess($rows);
3277 * @param int $rowCount
3281 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3282 // lets do the pager if in html mode
3283 $this->_limit
= NULL;
3285 // CRM-14115, over-ride row count if rowCount is specified in URL
3286 if ($this->_dashBoardRowCount
) {
3287 $rowCount = $this->_dashBoardRowCount
;
3289 if ($this->addPaging
) {
3290 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3292 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3294 // @todo all http vars should be extracted in the preProcess
3295 // - not randomly in the class
3296 if (!$pageId && !empty($_POST)) {
3297 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3298 $pageId = max((int) $_POST['crmPID_B'], 1);
3300 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3301 $pageId = max((int) $_POST['crmPID'], 1);
3303 unset($_POST['crmPID_B'], $_POST['crmPID']);
3306 $pageId = $pageId ?
$pageId : 1;
3307 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3308 $offset = ($pageId - 1) * $rowCount;
3310 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3311 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3313 $this->_limit
= " LIMIT $offset, $rowCount";
3314 return array($offset, $rowCount);
3316 if ($this->_limitValue
) {
3317 if ($this->_offsetValue
) {
3318 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3321 $this->_limit
= " LIMIT " . $this->_limitValue
;
3329 * @param int $rowCount
3331 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3332 // CRM-14115, over-ride row count if rowCount is specified in URL
3333 if ($this->_dashBoardRowCount
) {
3334 $rowCount = $this->_dashBoardRowCount
;
3337 if ($this->_limit
&& ($this->_limit
!= '')) {
3338 if (!$this->_rowsFound
) {
3339 $sql = "SELECT FOUND_ROWS();";
3340 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3343 'total' => $this->_rowsFound
,
3344 'rowCount' => $rowCount,
3345 'status' => ts('Records') . ' %%StatusMessage%%',
3346 'buttonBottom' => 'PagerBottomButton',
3347 'buttonTop' => 'PagerTopButton',
3349 if (!empty($this->controller
)) {
3350 // This happens when being called from the api Really we want the api to be able to
3351 // pass paging parameters, but at this stage just preventing test crashes.
3352 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3355 $pager = new CRM_Utils_Pager($params);
3356 $this->assign_by_ref('pager', $pager);
3357 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3362 * Build where clause for groups.
3364 * @param string $field
3365 * @param mixed $value
3370 public function whereGroupClause($field, $value, $op) {
3372 $smartGroupQuery = "";
3374 $group = new CRM_Contact_DAO_Group();
3375 $group->is_active
= 1;
3377 $smartGroups = array();
3378 while ($group->fetch()) {
3379 if (in_array($group->id
, $this->_params
['gid_value']) &&
3380 $group->saved_search_id
3382 $smartGroups[] = $group->id
;
3386 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3388 $smartGroupQuery = '';
3389 if (!empty($smartGroups)) {
3390 $smartGroups = implode(',', $smartGroups);
3391 $smartGroupQuery = " UNION DISTINCT
3392 SELECT DISTINCT smartgroup_contact.contact_id
3393 FROM civicrm_group_contact_cache smartgroup_contact
3394 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3397 $sqlOp = $this->getSQLOperator($op);
3398 if (!is_array($value)) {
3399 $value = array($value);
3401 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3403 $contactAlias = $this->_aliases
['civicrm_contact'];
3404 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3405 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3407 return " {$contactAlias}.id {$sqlOp} (
3408 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3409 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3410 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3411 {$smartGroupQuery} ) ";
3415 * Build where clause for tags.
3417 * @param string $field
3418 * @param mixed $value
3423 public function whereTagClause($field, $value, $op) {
3424 // not using left join in query because if any contact
3425 // belongs to more than one tag, results duplicate
3427 $sqlOp = $this->getSQLOperator($op);
3428 if (!is_array($value)) {
3429 $value = array($value);
3431 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3432 $entity_table = $this->_tagFilterTable
;
3433 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3434 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3435 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3436 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3440 * Generate membership organization clause.
3442 * @param mixed $value
3443 * @param string $op SQL Operator
3447 public function whereMembershipOrgClause($value, $op) {
3448 $sqlOp = $this->getSQLOperator($op);
3449 if (!is_array($value)) {
3450 $value = array($value);
3453 $tmp_membership_org_sql_list = implode(', ', $value);
3454 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3455 SELECT DISTINCT mem.contact_id
3456 FROM civicrm_membership mem
3457 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3458 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3459 WHERE mt.member_of_contact_id IN (" .
3460 $tmp_membership_org_sql_list . ")
3461 AND mt.is_active = '1'
3462 AND mem_status.is_current_member = '1'
3463 AND mem_status.is_active = '1' ) ";
3467 * Generate Membership Type SQL Clause.
3469 * @param mixed $value
3475 public function whereMembershipTypeClause($value, $op) {
3476 $sqlOp = $this->getSQLOperator($op);
3477 if (!is_array($value)) {
3478 $value = array($value);
3481 $tmp_membership_sql_list = implode(', ', $value);
3482 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3483 SELECT DISTINCT mem.contact_id
3484 FROM civicrm_membership mem
3485 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3486 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3487 WHERE mem.membership_type_id IN (" .
3488 $tmp_membership_sql_list . ")
3489 AND mt.is_active = '1'
3490 AND mem_status.is_current_member = '1'
3491 AND mem_status.is_active = '1' ) ";
3495 * Build acl clauses.
3497 * @param string $tableAlias
3499 public function buildACLClause($tableAlias = 'contact_a') {
3500 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3504 * Add custom data to the columns.
3506 * @param bool $addFields
3507 * @param array $permCustomGroupIds
3509 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3510 if (empty($this->_customGroupExtends
)) {
3513 if (!is_array($this->_customGroupExtends
)) {
3514 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3516 $customGroupWhere = '';
3517 if (!empty($permCustomGroupIds)) {
3518 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3522 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3523 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3524 FROM civicrm_custom_group cg
3525 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3526 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3528 cg.is_active = 1 AND
3529 cf.is_active = 1 AND
3530 cf.is_searchable = 1
3531 ORDER BY cg.weight, cf.weight";
3532 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3535 while ($customDAO->fetch()) {
3536 if ($customDAO->table_name
!= $curTable) {
3537 $curTable = $customDAO->table_name
;
3538 $curFields = $curFilters = array();
3541 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3542 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3543 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3544 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3546 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3547 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3548 $this->_columns
[$curTable][$colKey] = array();
3552 $fieldName = 'custom_' . $customDAO->cf_id
;
3555 // this makes aliasing work in favor
3556 $curFields[$fieldName] = array(
3557 'name' => $customDAO->column_name
,
3558 'title' => $customDAO->label
,
3559 'dataType' => $customDAO->data_type
,
3560 'htmlType' => $customDAO->html_type
,
3563 if ($this->_customGroupFilters
) {
3564 // this makes aliasing work in favor
3565 $curFilters[$fieldName] = array(
3566 'name' => $customDAO->column_name
,
3567 'title' => $customDAO->label
,
3568 'dataType' => $customDAO->data_type
,
3569 'htmlType' => $customDAO->html_type
,
3573 switch ($customDAO->data_type
) {
3576 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3577 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3578 // CRM-6946, show time part for datetime date fields
3579 if ($customDAO->time_format
) {
3580 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3585 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3586 $curFilters[$fieldName]['options'] = array('' => ts('- select -'))
3587 + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3588 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3592 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3593 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3597 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3598 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3599 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3603 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3604 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3608 case 'StateProvince':
3610 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3612 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3613 if ($options !== FALSE) {
3614 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3615 $curFilters[$fieldName]['options'] = $options;
3619 case 'ContactReference':
3620 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3621 $curFilters[$fieldName]['name'] = 'display_name';
3622 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3624 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3625 $curFields[$fieldName]['name'] = 'display_name';
3626 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3630 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3631 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3634 if (!array_key_exists('type', $curFields[$fieldName])) {
3635 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3639 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3641 if ($this->_customGroupFilters
) {
3642 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3644 if ($this->_customGroupGroupBy
) {
3645 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3651 * Build custom data from clause.
3653 * @param bool $joinsForFiltersOnly
3654 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3656 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3657 if (empty($this->_customGroupExtends
)) {
3660 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3661 $customTables = explode(',', CRM_Core_DAO
::singleValueQuery("SELECT GROUP_CONCAT(table_name) FROM civicrm_custom_group"));
3663 foreach ($this->_columns
as $table => $prop) {
3664 if (in_array($table, $customTables)) {
3665 $extendsTable = $mapper[$prop['extends']];
3666 // Check field is required for rendering the report.
3667 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3670 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3672 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3674 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3675 // handle for ContactReference
3676 if (array_key_exists('fields', $prop)) {
3677 foreach ($prop['fields'] as $fieldName => $field) {
3678 if (CRM_Utils_Array
::value('dataType', $field) ==
3681 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3683 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3692 * Check if the field is selected.
3694 * @param string $prop
3698 public function isFieldSelected($prop) {
3703 if (!empty($this->_params
['fields'])) {
3704 foreach (array_keys($prop['fields']) as $fieldAlias) {
3705 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3706 if ($customFieldId) {
3707 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3711 //might be survey response field.
3712 if (!empty($this->_params
['fields']['survey_response']) &&
3713 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3721 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3722 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3723 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3724 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3731 if (!empty($this->_params
['order_bys'])) {
3732 foreach (array_keys($prop['fields']) as $fieldAlias) {
3733 foreach ($this->_params
['order_bys'] as $orderBy) {
3734 if ($fieldAlias == $orderBy['column'] &&
3735 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3742 return $this->isFieldFiltered($prop);
3747 * Check if the field is used as a filter.
3749 * @param string $prop
3753 protected function isFieldFiltered($prop) {
3754 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3755 foreach ($prop['filters'] as $fieldAlias => $val) {
3764 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3765 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3766 ||
($attach != 'relative' &&
3767 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3773 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3774 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3785 * Check for empty order_by configurations and remove them.
3787 * Also set template to hide them.
3789 * @param array $formValues
3791 public function preProcessOrderBy(&$formValues) {
3792 // Object to show/hide form elements
3793 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3795 $_showHide->addShow('optionField_1');
3797 // Cycle through order_by options; skip any empty ones, and hide them as well
3800 if (!empty($formValues['order_bys'])) {
3801 foreach ($formValues['order_bys'] as $order_by) {
3802 if ($order_by['column'] && $order_by['column'] != '-') {
3803 $_showHide->addShow('optionField_' . $n);
3804 $orderBys[$n] = $order_by;
3809 for ($i = $n; $i <= 5; $i++
) {
3811 $_showHide->addHide('optionField_' . $i);
3815 // overwrite order_by options with modified values
3816 if (!empty($orderBys)) {
3817 $formValues['order_bys'] = $orderBys;
3820 $formValues['order_bys'] = array(1 => array('column' => '-'));
3823 // assign show/hide data to template
3824 $_showHide->addToTemplate();
3828 * Check if table name has columns in SELECT clause.
3830 * @param string $tableName
3831 * Name of table (index of $this->_columns array).
3835 public function isTableSelected($tableName) {
3836 return in_array($tableName, $this->selectedTables());
3840 * Check if table name has columns in WHERE or HAVING clause.
3842 * @param string $tableName
3843 * Name of table (index of $this->_columns array).
3847 public function isTableFiltered($tableName) {
3848 // Cause the array to be generated if not previously done.
3849 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3850 $this->selectedTables();
3852 return in_array($tableName, $this->filteredTables
);
3856 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3858 * If the array is unset it will be built.
3863 public function selectedTables() {
3864 if (!$this->_selectedTables
) {
3865 $orderByColumns = array();
3866 if (array_key_exists('order_bys', $this->_params
) &&
3867 is_array($this->_params
['order_bys'])
3869 foreach ($this->_params
['order_bys'] as $orderBy) {
3870 $orderByColumns[] = $orderBy['column'];
3874 foreach ($this->_columns
as $tableName => $table) {
3875 if (array_key_exists('fields', $table)) {
3876 foreach ($table['fields'] as $fieldName => $field) {
3877 if (!empty($field['required']) ||
3878 !empty($this->_params
['fields'][$fieldName])
3880 $this->_selectedTables
[] = $tableName;
3885 if (array_key_exists('order_bys', $table)) {
3886 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3887 if (in_array($orderByName, $orderByColumns)) {
3888 $this->_selectedTables
[] = $tableName;
3893 if (array_key_exists('filters', $table)) {
3894 foreach ($table['filters'] as $filterName => $filter) {
3895 if (!empty($this->_params
["{$filterName}_value"]) ||
3896 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3898 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3901 $this->_selectedTables
[] = $tableName;
3902 $this->filteredTables
[] = $tableName;
3909 return $this->_selectedTables
;
3913 * Add address fields.
3915 * @deprecated - use getAddressColumns which is a more accurate description
3916 * and also accepts an array of options rather than a long list
3918 * adding address fields to construct function in reports
3920 * @param bool $groupBy
3921 * Add GroupBy? Not appropriate for detail report.
3922 * @param bool $orderBy
3923 * Add GroupBy? Not appropriate for detail report.
3924 * @param bool $filters
3925 * @param array $defaults
3928 * address fields for construct clause
3930 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3931 $addressFields = array(
3932 'civicrm_address' => array(
3933 'dao' => 'CRM_Core_DAO_Address',
3935 'address_name' => array(
3936 'title' => ts('Address Name'),
3937 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3940 'street_address' => array(
3941 'title' => ts('Street Address'),
3942 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3944 'supplemental_address_1' => array(
3945 'title' => ts('Supplementary Address Field 1'),
3946 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3948 'supplemental_address_2' => array(
3949 'title' => ts('Supplementary Address Field 2'),
3950 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3952 'street_number' => array(
3953 'name' => 'street_number',
3954 'title' => ts('Street Number'),
3956 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3958 'street_name' => array(
3959 'name' => 'street_name',
3960 'title' => ts('Street Name'),
3962 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3964 'street_unit' => array(
3965 'name' => 'street_unit',
3966 'title' => ts('Street Unit'),
3968 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3971 'title' => ts('City'),
3972 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3974 'postal_code' => array(
3975 'title' => ts('Postal Code'),
3976 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3978 'postal_code_suffix' => array(
3979 'title' => ts('Postal Code Suffix'),
3980 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3982 'country_id' => array(
3983 'title' => ts('Country'),
3984 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3986 'state_province_id' => array(
3987 'title' => ts('State/Province'),
3988 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3990 'county_id' => array(
3991 'title' => ts('County'),
3992 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3995 'grouping' => 'location-fields',
4000 $addressFields['civicrm_address']['filters'] = array(
4001 'street_number' => array(
4002 'title' => ts('Street Number'),
4004 'name' => 'street_number',
4006 'street_name' => array(
4007 'title' => ts('Street Name'),
4008 'name' => 'street_name',
4009 'operator' => 'like',
4011 'postal_code' => array(
4012 'title' => ts('Postal Code'),
4014 'name' => 'postal_code',
4017 'title' => ts('City'),
4018 'operator' => 'like',
4021 'country_id' => array(
4022 'name' => 'country_id',
4023 'title' => ts('Country'),
4024 'type' => CRM_Utils_Type
::T_INT
,
4025 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4026 'options' => CRM_Core_PseudoConstant
::country(),
4028 'state_province_id' => array(
4029 'name' => 'state_province_id',
4030 'title' => ts('State/Province'),
4031 'type' => CRM_Utils_Type
::T_INT
,
4032 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4033 'options' => array(),
4035 'county_id' => array(
4036 'name' => 'county_id',
4037 'title' => ts('County'),
4038 'type' => CRM_Utils_Type
::T_INT
,
4039 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4040 'options' => array(),
4046 $addressFields['civicrm_address']['order_bys'] = array(
4047 'street_name' => array('title' => ts('Street Name')),
4048 'street_number' => array('title' => 'Odd / Even Street Number'),
4049 'street_address' => NULL,
4051 'postal_code' => NULL,
4056 $addressFields['civicrm_address']['group_bys'] = array(
4057 'street_address' => NULL,
4059 'postal_code' => NULL,
4060 'state_province_id' => array(
4061 'title' => ts('State/Province'),
4063 'country_id' => array(
4064 'title' => ts('Country'),
4066 'county_id' => array(
4067 'title' => ts('County'),
4071 return $addressFields;
4075 * Do AlterDisplay processing on Address Fields.
4078 * @param array $rows
4079 * @param int $rowNum
4080 * @param string $baseUrl
4081 * @param string $linkText
4085 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4086 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4087 $entryFound = FALSE;
4089 if (array_key_exists('civicrm_address_country_id', $row)) {
4090 if ($value = $row['civicrm_address_country_id']) {
4091 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4093 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4094 "reset=1&force=1&{$criteriaQueryParams}&" .
4095 "country_id_op=in&country_id_value={$value}",
4096 $this->_absoluteUrl
, $this->_id
4098 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4099 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4100 array(1 => $linkText)
4107 if (array_key_exists('civicrm_address_county_id', $row)) {
4108 if ($value = $row['civicrm_address_county_id']) {
4109 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4111 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4112 "reset=1&force=1&{$criteriaQueryParams}&" .
4113 "county_id_op=in&county_id_value={$value}",
4114 $this->_absoluteUrl
, $this->_id
4116 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4117 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4118 array(1 => $linkText)
4124 // handle state province
4125 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4126 if ($value = $row['civicrm_address_state_province_id']) {
4127 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4129 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4130 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4131 $this->_absoluteUrl
, $this->_id
4133 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4134 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4135 array(1 => $linkText)
4146 * Do AlterDisplay processing on Address Fields.
4149 * @param array $rows
4150 * @param int $rowNum
4151 * @param string $baseUrl
4152 * @param string $linkText
4156 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4157 $entryFound = FALSE;
4158 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4159 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4160 $addLinks = array('gender_id' => 'Gender');
4161 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4162 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4163 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4164 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4165 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4166 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4172 $yesNoFields = array(
4173 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4175 foreach ($yesNoFields as $fieldName) {
4176 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4177 // Since these are essentially 'negative fields' it feels like it
4178 // makes sense to only highlight the exceptions hence no 'No'.
4179 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4187 * Adjusts dates passed in to YEAR() for fiscal year.
4189 * @param string $fieldName
4193 public function fiscalYearOffset($fieldName) {
4194 $config = CRM_Core_Config
::singleton();
4195 $fy = $config->fiscalYearStart
;
4196 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4197 ($fy['d'] == 1 && $fy['M'] == 1)
4199 return "YEAR( $fieldName )";
4201 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4202 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4206 * Add Address into From Table if required.
4208 public function addAddressFromClause() {
4209 // include address field if address column is to be included
4210 if ((isset($this->_addressField
) &&
4211 $this->_addressField
4213 $this->isTableSelected('civicrm_address')
4216 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4217 ON ({$this->_aliases['civicrm_contact']}.id =
4218 {$this->_aliases['civicrm_address']}.contact_id) AND
4219 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4224 * Add Phone into From Table if required.
4226 public function addPhoneFromClause() {
4227 // include address field if address column is to be included
4228 if ($this->isTableSelected('civicrm_phone')
4231 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4232 ON ({$this->_aliases['civicrm_contact']}.id =
4233 {$this->_aliases['civicrm_phone']}.contact_id) AND
4234 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4239 * Get phone columns to add to array.
4241 * @param array $options
4242 * - prefix Prefix to add to table (in case of more than one instance of the table)
4243 * - prefix_label Label to give columns from this phone table instance
4246 * phone columns definition
4248 public function getPhoneColumns($options = array()) {
4249 $defaultOptions = array(
4251 'prefix_label' => '',
4254 $options = array_merge($defaultOptions, $options);
4257 $options['prefix'] . 'civicrm_phone' => array(
4258 'dao' => 'CRM_Core_DAO_Phone',
4260 $options['prefix'] . 'phone' => array(
4261 'title' => ts($options['prefix_label'] . 'Phone'),
4271 * Get address columns to add to array.
4273 * @param array $options
4274 * - prefix Prefix to add to table (in case of more than one instance of the table)
4275 * - prefix_label Label to give columns from this address table instance
4278 * address columns definition
4280 public function getAddressColumns($options = array()) {
4283 'prefix_label' => '',
4287 'defaults' => array(),
4289 return $this->addAddressFields(
4290 $options['group_by'],
4291 $options['order_by'],
4292 $options['filters'],
4293 $options['defaults']
4298 * Get a standard set of contact fields.
4302 public function getBasicContactFields() {
4304 'sort_name' => array(
4305 'title' => ts('Contact Name'),
4310 'no_display' => TRUE,
4313 'prefix_id' => array(
4314 'title' => ts('Contact Prefix'),
4316 'first_name' => array(
4317 'title' => ts('First Name'),
4319 'nick_name' => array(
4320 'title' => ts('Nick Name'),
4322 'middle_name' => array(
4323 'title' => ts('Middle Name'),
4325 'last_name' => array(
4326 'title' => ts('Last Name'),
4328 'suffix_id' => array(
4329 'title' => ts('Contact Suffix'),
4331 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4332 'email_greeting_display' => array('title' => ts('Email Greeting')),
4333 'addressee_display' => array('title' => ts('Address Greeting')),
4334 'contact_type' => array(
4335 'title' => ts('Contact Type'),
4337 'contact_sub_type' => array(
4338 'title' => ts('Contact Subtype'),
4340 'gender_id' => array(
4341 'title' => ts('Gender'),
4343 'birth_date' => array(
4344 'title' => ts('Birth Date'),
4347 'title' => ts('Age'),
4348 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4350 'job_title' => array(
4351 'title' => ts('Contact Job title'),
4353 'organization_name' => array(
4354 'title' => ts('Organization Name'),
4356 'external_identifier' => array(
4357 'title' => ts('Contact identifier from external system'),
4359 'do_not_email' => array(),
4360 'do_not_phone' => array(),
4361 'do_not_mail' => array(),
4362 'do_not_sms' => array(),
4363 'is_opt_out' => array(),
4364 'is_deceased' => array(),
4369 * Add contact to group.
4371 * @param int $groupID
4373 public function add2group($groupID) {
4374 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4375 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4377 // here are we are prepending / adding contact id field that could be used for adding group
4378 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4379 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select
)) {
4380 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4383 $select = str_ireplace('SELECT ', $select, $this->_select
);
4386 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4387 $sql = str_replace('WITH ROLLUP', '', $sql);
4388 $dao = CRM_Core_DAO
::executeQuery($sql);
4390 $contact_ids = array();
4391 // Add resulting contacts to group
4392 while ($dao->fetch()) {
4393 if ($dao->addtogroup_contact_id
) {
4394 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4398 if (!empty($contact_ids)) {
4399 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4400 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4403 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4409 * Show charts on print screen.
4411 public static function uploadChartImage() {
4412 // upload strictly for '.png' images
4413 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4414 if (preg_match('/\.png$/', $name)) {
4416 // POST data is usually string data, but we are passing a RAW .png
4417 // so PHP is a bit confused and $_POST is empty. But it has saved
4418 // the raw bits into $HTTP_RAW_POST_DATA
4420 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4422 // prepare the directory
4423 $config = CRM_Core_Config
::singleton();
4425 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4427 if (!file_exists($defaultPath)) {
4428 mkdir($defaultPath, 0777, TRUE);
4431 // full path to the saved image including filename
4432 $destination = $defaultPath . $name;
4435 $jfh = fopen($destination, 'w') or die("can't open file");
4436 fwrite($jfh, $httpRawPostData);
4438 CRM_Utils_System
::civiExit();
4443 * Apply common settings to entityRef fields.
4445 * @param array $field
4446 * @param string $table
4448 private function setEntityRefDefaults(&$field, $table) {
4449 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4450 $field['attributes'] +
= array(
4451 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4453 'placeholder' => ts('- select -'),
4458 * Add link fields to the row.
4460 * Function adds the _link & _hover fields to the row.
4463 * @param string $baseUrl
4464 * @param string $linkText
4465 * @param string $value
4466 * @param string $fieldName
4467 * @param string $tablePrefix
4468 * @param string $fieldLabel
4472 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4473 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4474 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4475 "reset=1&force=1&{$criteriaQueryParams}&" .
4476 $fieldName . "_op=in&{$fieldName}_value={$value}",
4477 $this->_absoluteUrl
, $this->_id
4479 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4480 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4481 array(1 => $linkText, 2 => $fieldLabel)
4486 * Generate temporary table to hold all contributions with permissioned FTs.
4488 * @param object $query
4489 * @param string $alias
4490 * @param bool $return
4492 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4493 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4496 $financialTypes = NULL;
4497 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4498 if (empty($financialTypes)) {
4500 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4503 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4506 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4507 $query->_aliases
['civicrm_line_item'] = $alias;
4509 if (empty($query->_where
)) {
4510 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4512 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4513 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4514 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4515 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4516 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4517 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4519 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4520 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4521 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4522 CRM_Core_DAO
::executeQuery($sql);
4524 $query->_aliases
['civicrm_line_item'] = $temp;
4526 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4530 $query->_from
.= $from;
4534 * Get label for show results buttons.
4538 public function getResultsLabel() {
4539 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4540 return $showResultsLabel;
4544 * Determine the output mode from the url or input.
4547 * - pdf : Render as pdf
4548 * - csv : Render as csv
4549 * - print : Render in print format
4550 * - save : save the report and display the new report
4551 * - copy : save the report as a new instance and display that.
4552 * - group : go to the add to group screen.
4554 * Potentially chart variations could also be included but the complexity
4555 * is that we might print a bar chart as a pdf.
4557 protected function setOutputMode() {
4558 $buttonName = $this->controller
->getButtonName();
4559 $this->_outputMode
= CRM_Utils_Request
::retrieve(
4562 CRM_Core_DAO
::$_nullObject,
4564 CRM_Utils_Array
::value('task', $this->_params
)
4568 if ($buttonName == $this->_instanceButtonName
) {
4569 $this->_outputMode
= 'save';
4571 if ($buttonName == $this->_printButtonName
) {
4572 $this->_outputMode
= 'print';
4574 if ($buttonName == $this->_pdfButtonName
) {
4575 $this->_outputMode
= 'pdf';
4577 if ($this->_csvButtonName
== $buttonName) {
4578 $this->_outputMode
= 'csv';
4580 if ($this->_groupButtonName
== $buttonName) {
4581 $this->_outputMode
= 'group';
4583 if ($buttonName == $this->_createNewButtonName
) {
4584 $this->_outputMode
= 'copy';
4590 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4592 * @param $columnName
4594 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4595 // add new column with date value for the datetime field
4596 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4597 CRM_Core_DAO
::executeQuery($tempQuery);
4598 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4599 CRM_Core_DAO
::executeQuery($updateQuery);
4600 $this->_select
.= ", {$columnName}_date";
4601 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4602 unset($this->_sections
["{$columnName}"]);
4603 $this->assign('sections', $this->_sections
);
4607 * Get an array of the columns that have been selected for display.
4611 public function getSelectColumns() {
4612 $selectColumns = array();
4613 foreach ($this->_columns
as $tableName => $table) {
4614 if (array_key_exists('fields', $table)) {
4615 foreach ($table['fields'] as $fieldName => $field) {
4616 if (!empty($field['required']) ||
4617 !empty($this->_params
['fields'][$fieldName])
4620 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4625 return $selectColumns;
4629 * Add location tables to the query if they are used for filtering.
4631 * This is for when we are running the query separately for filtering and retrieving display fields.
4633 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4634 if ($this->isTableFiltered('civicrm_email')) {
4636 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4637 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4638 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4640 if ($this->isTableFiltered('civicrm_phone')) {
4642 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4643 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4644 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4646 if ($this->isTableFiltered('civicrm_address')) {
4648 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4649 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4650 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";