3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 const ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
54 * The id of the report instance
61 * The id of the report template
65 protected $_templateID;
73 protected $_noFields = FALSE;
76 * The set of all columns in the report. An associative array
77 * with column name as the key and attribues as the value
81 protected $_columns = array();
84 * The set of filters in the report
88 protected $_filters = array();
91 * The set of optional columns in the report
95 protected $_options = array();
97 protected $_defaults = array();
100 * By default most reports hide contact id.
101 * Setting this to true makes it available
103 protected $_exposeContactID = TRUE;
106 * Set of statistic fields
110 protected $_statFields = array();
113 * Set of statistics data
117 protected $_statistics = array();
120 * List of fields not to be repeated during display
124 protected $_noRepeats = array();
127 * List of fields not to be displayed
131 protected $_noDisplay = array();
134 * Object type that a custom group extends
138 protected $_customGroupExtends = NULL;
139 protected $_customGroupExtendsJoin = array();
140 protected $_customGroupFilters = TRUE;
141 protected $_customGroupGroupBy = FALSE;
142 protected $_customGroupJoin = 'LEFT JOIN';
147 protected $_tagFilter = FALSE;
151 * Build groups filter
153 * specify entity table for tags filter
156 protected $_tagFilterTable = 'civicrm_contact';
159 * build groups filter
161 * >>>>>>> 098a61330d0fe12153370741ec98cb1172ece849
163 protected $_groupFilter = FALSE;
170 public $_navigation = array();
172 public $_drilldownReport = array();
175 * An attribute for checkbox/radio form field layout
179 protected $_fourColumnAttribute = array(
180 '</td><td width="25%">',
181 '</td><td width="25%">',
182 '</td><td width="25%">',
186 protected $_force = 1;
188 protected $_params = NULL;
189 protected $_formValues = NULL;
190 protected $_instanceValues = NULL;
192 protected $_instanceForm = FALSE;
193 protected $_criteriaForm = FALSE;
195 protected $_instanceButtonName = NULL;
196 protected $_createNewButtonName = NULL;
197 protected $_printButtonName = NULL;
198 protected $_pdfButtonName = NULL;
199 protected $_csvButtonName = NULL;
200 protected $_groupButtonName = NULL;
201 protected $_chartButtonName = NULL;
202 protected $_csvSupported = TRUE;
203 protected $_add2groupSupported = TRUE;
204 protected $_groups = NULL;
205 protected $_grandFlag = FALSE;
206 protected $_rowsFound = NULL;
207 protected $_selectAliases = array();
208 protected $_rollup = NULL;
214 protected $_limit = NULL;
217 * This can be set to specify a limit to the number of rows
218 * Since it is currently envisaged as part of the api usage it is only being applied
219 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
220 * of the code (see limit() fn
223 protected $_limitValue = NULL;
226 * This can be set to specify row offset
227 * See notes on _limitValue
230 protected $_offsetValue = NULL;
231 protected $_sections = NULL;
232 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
233 protected $_absoluteUrl = FALSE;
236 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
240 protected $_storeResultSet = FALSE;
243 * When _storeResultSet Flag is set use this var to store result set in form of array
247 protected $_resultSet = array();
250 * To what frequency group-by a date column
254 protected $_groupByDateFreq = array(
256 'YEARWEEK' => 'Week',
257 'QUARTER' => 'Quarter',
262 * Variables to hold the acl inner join and where clause
264 protected $_aclFrom = NULL;
265 protected $_aclWhere = NULL;
268 * Array of DAO tables having columns included in SELECT or ORDER BY clause
272 protected $_selectedTables;
275 * Outputmode e.g 'print', 'csv', 'pdf'
278 protected $_outputMode;
280 public $_having = NULL;
281 public $_select = NULL;
282 public $_selectClauses = array();
283 public $_columnHeaders = array();
284 public $_orderBy = NULL;
285 public $_orderByFields = array();
286 public $_orderByArray = array();
287 public $_groupBy = NULL;
288 public $_whereClauses = array();
289 public $_havingClauses = array();
292 * DashBoardRowCount Dashboard row count
295 public $_dashBoardRowCount;
298 * Is this being called without a form controller (ie. the report is being render outside the normal form
299 * - e.g the api is retrieving the rows
302 public $noController = FALSE;
305 * Variable to hold the currency alias
307 protected $_currencyColumn = NULL;
311 public function __construct() {
312 parent
::__construct();
315 if ($this->_tagFilter
) {
316 $this->buildTagFilter();
318 if ($this->_exposeContactID
) {
319 if (array_key_exists('civicrm_contact', $this->_columns
)) {
320 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
322 'title' => 'Contact ID',
328 if ($this->_groupFilter
) {
329 $this->buildGroupFilter();
332 // Get all custom groups
333 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
335 // Get the custom groupIds for which the user has VIEW permission
336 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
337 // and addCustomDataToColumns() will allow access to all custom groups.
338 $permCustomGroupIds = array();
339 if (!CRM_Core_Permission
::check('access all custom data')) {
340 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
341 // do not allow custom data for reports if user doesn't have
342 // permission to access custom data.
343 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
344 $this->_customGroupExtends
= array();
348 // merge custom data columns to _columns list, if any
349 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
351 // add / modify display columns, filters ..etc
352 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
354 //assign currencyColumn variable to tpl
355 $this->assign('currencyColumn', $this->_currencyColumn
);
358 public function preProcessCommon() {
360 CRM_Utils_Request
::retrieve(
363 CRM_Core_DAO
::$_nullObject
366 $this->_dashBoardRowCount
=
367 CRM_Utils_Request
::retrieve(
370 CRM_Core_DAO
::$_nullObject
373 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
375 $this->assign('section', $this->_section
);
376 CRM_Core_Region
::instance('page-header')->add(array(
377 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
379 if (!$this->noController
) {
380 $this->setID($this->get('instanceId'));
383 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
385 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
389 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
390 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
391 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
395 $this->assign('instanceId', $this->_id
);
396 $params = array('id' => $this->_id
);
397 $this->_instanceValues
= array();
398 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
400 $this->_instanceValues
402 if (empty($this->_instanceValues
)) {
403 CRM_Core_Error
::fatal("Report could not be loaded.");
405 $this->_title
= $this->_instanceValues
['title'];
406 if (!empty($this->_instanceValues
['permission']) &&
407 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
408 CRM_Core_Permission
::check('administer Reports')
411 CRM_Utils_System
::permissionDenied();
412 CRM_Utils_System
::civiExit();
415 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
417 $this->_formValues
= unserialize($formValues);
420 $this->_formValues
= NULL;
423 // lets always do a force if reset is found in the url.
424 if (!empty($_REQUEST['reset'])) {
429 $this->assign('mode', 'instance');
431 elseif (!$this->noController
) {
432 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
433 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
434 if (($instanceCount > 0) && $optionValueID) {
435 $this->assign('instanceUrl',
436 CRM_Utils_System
::url('civicrm/report/list',
437 "reset=1&ovid=$optionValueID"
441 if ($optionValueID) {
442 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
446 $this->assign('mode', 'template');
449 // lets display the Report Settings section
450 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
452 // Do not display Report Settings section if administer Reports permission is absent OR
453 // if report instance is reserved and administer reserved reports absent
454 if (!CRM_Core_Permission
::check('administer Reports') ||
455 ($this->_instanceValues
['is_reserved'] &&
456 !CRM_Core_Permission
::check('administer reserved reports'))
458 $this->_instanceForm
= FALSE;
461 $this->assign('criteriaForm', FALSE);
462 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
463 if (CRM_Core_Permission
::check('administer Reports') ||
464 CRM_Core_Permission
::check('access Report Criteria')
466 if (!$this->_instanceValues
['is_reserved'] ||
467 CRM_Core_Permission
::check('administer reserved reports')
469 $this->assign('criteriaForm', TRUE);
470 $this->_criteriaForm
= TRUE;
474 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
475 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
476 $this->_printButtonName
= $this->getButtonName('submit', 'print');
477 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
478 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
479 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
480 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
483 public function addBreadCrumb() {
487 'title' => ts('Report Templates'),
488 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
492 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
495 public function preProcess() {
496 $this->preProcessCommon();
499 $this->addBreadCrumb();
502 foreach ($this->_columns
as $tableName => $table) {
504 if (!isset($table['alias'])) {
505 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
509 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
512 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
514 $daoOrBaoName = NULL;
515 // higher preference to bao object
516 if (array_key_exists('bao', $table)) {
517 $daoOrBaoName = $table['bao'];
518 $expFields = $daoOrBaoName::exportableFields();
520 elseif (array_key_exists('dao', $table)) {
521 $daoOrBaoName = $table['dao'];
522 $expFields = $daoOrBaoName::export();
525 $expFields = array();
528 $doNotCopy = array('required');
530 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
531 foreach ($fieldGroups as $fieldGrp) {
532 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
533 foreach ($table[$fieldGrp] as $fieldName => $field) {
534 // $name is the field name used to reference the BAO/DAO export fields array
535 $name = isset($field['name']) ?
$field['name'] : $fieldName;
537 // Sometimes the field name key in the BAO/DAO export fields array is
538 // different from the actual database field name.
539 // Unset $field['name'] so that actual database field name can be obtained
540 // from the BAO/DAO export fields array.
541 unset($field['name']);
543 if (array_key_exists($name, $expFields)) {
544 foreach ($doNotCopy as $dnc) {
545 // unset the values we don't want to be copied.
546 unset($expFields[$name][$dnc]);
549 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
552 foreach ($expFields[$name] as $property => $val) {
553 if (!array_key_exists($property, $field)) {
554 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
561 if (!empty($field['no_repeat'])) {
562 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
564 if (!empty($field['no_display'])) {
565 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
568 // set alias = table-name, unless already set
569 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
570 $this->_columns
[$tableName]['alias'] : $tableName
572 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
574 // set name = fieldName, unless already set
575 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
576 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
579 // set dbAlias = alias.name, unless already set
580 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
581 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] =
583 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
586 // a few auto fills for filters
587 if ($fieldGrp == 'filters') {
588 // fill operator types
589 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
590 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
591 case CRM_Utils_Type
::T_MONEY
:
592 case CRM_Utils_Type
::T_FLOAT
:
593 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
596 case CRM_Utils_Type
::T_INT
:
597 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
600 case CRM_Utils_Type
::T_DATE
:
601 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
604 case CRM_Utils_Type
::T_BOOLEAN
:
605 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
606 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
607 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
618 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
620 // with multiple options operator-type is generally multi-select
621 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
622 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
624 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
635 // copy filters to a separate handy variable
636 if (array_key_exists('filters', $table)) {
637 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
640 if (array_key_exists('group_bys', $table)) {
641 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
644 if (array_key_exists('fields', $table)) {
645 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
650 $this->setDefaultValues(FALSE);
653 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
654 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
655 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
656 CRM_Report_Utils_Get
::processChart($this->_defaults
);
659 $this->_formValues
= $this->_defaults
;
660 $this->postProcess();
665 * @param bool $freeze
669 public function setDefaultValues($freeze = TRUE) {
670 $freezeGroup = array();
672 // FIXME: generalizing form field naming conventions would reduce
673 // lots of lines below.
674 foreach ($this->_columns
as $tableName => $table) {
675 if (array_key_exists('fields', $table)) {
676 foreach ($table['fields'] as $fieldName => $field) {
677 if (empty($field['no_display'])) {
678 if (isset($field['required'])) {
680 $this->_defaults
['fields'][$fieldName] = 1;
683 // find element object, so that we could use quickform's freeze method
684 // for required elements
685 $obj = $this->getElementFromGroup("fields", $fieldName);
687 $freezeGroup[] = $obj;
691 elseif (isset($field['default'])) {
692 $this->_defaults
['fields'][$fieldName] = $field['default'];
698 if (array_key_exists('group_bys', $table)) {
699 foreach ($table['group_bys'] as $fieldName => $field) {
700 if (isset($field['default'])) {
701 if (!empty($field['frequency'])) {
702 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
704 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
708 if (array_key_exists('filters', $table)) {
709 foreach ($table['filters'] as $fieldName => $field) {
710 if (isset($field['default'])) {
711 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
713 if (is_array($field['default'])) {
714 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
715 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
716 $this->_defaults
["{$fieldName}_relative"] = 0;
719 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
723 $this->_defaults
["{$fieldName}_value"] = $field['default'];
726 //assign default value as "in" for multiselect
727 //operator, To freeze the select element
728 if (CRM_Utils_Array
::value('operatorType', $field) ==
729 CRM_Report_Form
::OP_MULTISELECT
731 $this->_defaults
["{$fieldName}_op"] = 'in';
733 if (CRM_Utils_Array
::value('operatorType', $field) ==
734 CRM_Report_Form
::OP_ENTITYREF
736 $this->_defaults
["{$fieldName}_op"] = 'in';
738 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
739 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
741 $this->_defaults
["{$fieldName}_op"] = 'mhas';
743 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
744 $this->_defaults
["{$fieldName}_op"] = $op;
750 array_key_exists('order_bys', $table) &&
751 is_array($table['order_bys'])
753 if (!array_key_exists('order_bys', $this->_defaults
)) {
754 $this->_defaults
['order_bys'] = array();
756 foreach ($table['order_bys'] as $fieldName => $field) {
757 if (!empty($field['default']) ||
!empty($field['default_order']) ||
758 CRM_Utils_Array
::value('default_is_section', $field) ||
759 !empty($field['default_weight'])
762 'column' => $fieldName,
763 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
764 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
767 if (!empty($field['default_weight'])) {
768 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
771 array_unshift($this->_defaults
['order_bys'], $order_by);
777 foreach ($this->_options
as $fieldName => $field) {
778 if (isset($field['default'])) {
779 $this->_defaults
['options'][$fieldName] = $field['default'];
784 if (!empty($this->_submitValues
)) {
785 $this->preProcessOrderBy($this->_submitValues
);
788 $this->preProcessOrderBy($this->_defaults
);
791 // lets finish freezing task here itself
792 if (!empty($freezeGroup)) {
793 foreach ($freezeGroup as $elem) {
798 if ($this->_formValues
) {
799 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
802 if ($this->_instanceValues
) {
803 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
806 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
808 return $this->_defaults
;
813 * @param string $grpFieldName
817 public function getElementFromGroup($group, $grpFieldName) {
818 $eleObj = $this->getElement($group);
819 foreach ($eleObj->_elements
as $index => $obj) {
820 if ($grpFieldName == $obj->_attributes
['name']) {
828 * Setter for $_params
830 * @param array $params
832 public function setParams($params) {
833 $this->_params
= $params;
839 * @param int $instanceid
841 public function setID($instanceid) {
842 $this->_id
= $instanceid;
850 public function setForce($isForce) {
851 $this->_force
= $isForce;
855 * Setter for $_limitValue
857 * @param int $_limitValue
859 public function setLimitValue($_limitValue) {
860 $this->_limitValue
= $_limitValue;
864 * Setter for $_offsetValue
866 * @param int $_offsetValue
868 public function setOffsetValue($_offsetValue) {
869 $this->_offsetValue
= $_offsetValue;
873 * Getter for $_defaultValues
876 public function getDefaultValues() {
877 return $this->_defaults
;
880 public function addColumns() {
883 foreach ($this->_columns
as $tableName => $table) {
884 if (array_key_exists('fields', $table)) {
885 foreach ($table['fields'] as $fieldName => $field) {
887 if (empty($field['no_display'])) {
888 foreach (array('table', 'field') as $var) {
889 if (!empty($
{$var}['grouping'])) {
890 if (!is_array($
{$var}['grouping'])) {
891 $tableName = $
{$var}['grouping'];
894 $tableName = array_keys($
{$var}['grouping']);
895 $tableName = $tableName[0];
896 $groupTitle = array_values($
{$var}['grouping']);
897 $groupTitle = $groupTitle[0];
902 if (!$groupTitle && isset($table['group_title'])) {
903 $groupTitle = $table['group_title'];
906 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
907 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
908 $colGroups[$tableName]['group_title'] = $groupTitle;
911 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
917 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
918 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
920 $this->assign('colGroups', $colGroups);
923 public function addFilters() {
926 foreach ($this->_filters
as $table => $attributes) {
927 foreach ($attributes as $fieldName => $field) {
928 // get ready with option value pair
929 // @ 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
931 $operations = $this->getOperationPair(
932 CRM_Utils_Array
::value('operatorType', $field),
935 $filters[$table][$fieldName] = $field;
937 switch (CRM_Utils_Array
::value('operatorType', $field)) {
938 case CRM_Report_Form
::OP_MONTH
:
939 if (!array_key_exists('options', $field) ||
940 !is_array($field['options']) ||
empty($field['options'])
942 // If there's no option list for this filter, define one.
943 $field['options'] = array(
952 9 => ts('September'),
954 11 => ts('November'),
955 12 => ts('December'),
957 // Add this option list to this column _columns. This is
958 // required so that filter statistics show properly.
959 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
961 case CRM_Report_Form
::OP_MULTISELECT
:
962 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
963 // assume a multi-select field
964 if (!empty($field['options']) ||
965 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
967 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
968 if (count($operations) <= 1) {
971 if ($fieldName == 'state_province_id' ||
972 $fieldName == 'county_id'
974 $this->addChainSelect($fieldName . '_value', array(
981 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
982 'style' => 'min-width:250px',
983 'class' => 'crm-select2 huge',
985 'placeholder' => ts('- select -'),
991 case CRM_Report_Form
::OP_SELECT
:
992 // assume a select field
993 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
994 if (!empty($field['options'])) {
995 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
999 case CRM_Report_Form
::OP_ENTITYREF
:
1000 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1001 $this->setEntityRefDefaults($field, $table);
1002 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1005 case CRM_Report_Form
::OP_DATE
:
1006 // build datetime fields
1007 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1011 case CRM_Report_Form
::OP_DATETIME
:
1012 // build datetime fields
1013 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1017 case CRM_Report_Form
::OP_INT
:
1018 case CRM_Report_Form
::OP_FLOAT
:
1019 // and a min value input box
1020 $this->add('text', "{$fieldName}_min", ts('Min'));
1021 // and a max value input box
1022 $this->add('text', "{$fieldName}_max", ts('Max'));
1024 // default type is string
1025 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1026 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1028 // we need text box for value input
1029 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1034 $this->assign('filters', $filters);
1037 public function addOptions() {
1038 if (!empty($this->_options
)) {
1039 // FIXME: For now lets build all elements as checkboxes.
1040 // Once we clear with the format we can build elements based on type
1043 foreach ($this->_options
as $fieldName => $field) {
1044 if ($field['type'] == 'select') {
1045 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1047 elseif ($field['type'] == 'checkbox') {
1048 $options[$field['title']] = $fieldName;
1049 $this->addCheckBox($fieldName, NULL,
1051 NULL, NULL, NULL, $this->_fourColumnAttribute
1056 $this->assign('otherOptions', $this->_options
);
1059 public function addChartOptions() {
1060 if (!empty($this->_charts
)) {
1061 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
1062 $this->assign('charts', $this->_charts
);
1063 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1067 public function addGroupBys() {
1068 $options = $freqElements = array();
1070 foreach ($this->_columns
as $tableName => $table) {
1071 if (array_key_exists('group_bys', $table)) {
1072 foreach ($table['group_bys'] as $fieldName => $field) {
1073 if (!empty($field)) {
1074 $options[$field['title']] = $fieldName;
1075 if (!empty($field['frequency'])) {
1076 $freqElements[$field['title']] = $fieldName;
1082 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1083 NULL, NULL, NULL, $this->_fourColumnAttribute
1085 $this->assign('groupByElements', $options);
1087 foreach ($freqElements as $name) {
1088 $this->addElement('select', "group_bys_freq[$name]",
1089 ts('Frequency'), $this->_groupByDateFreq
1094 public function addOrderBys() {
1096 foreach ($this->_columns
as $tableName => $table) {
1098 // Report developer may define any column to order by; include these as order-by options
1099 if (array_key_exists('order_bys', $table)) {
1100 foreach ($table['order_bys'] as $fieldName => $field) {
1101 if (!empty($field)) {
1102 $options[$fieldName] = $field['title'];
1107 /* Add searchable custom fields as order-by options, if so requested
1108 * (These are already indexed, so allowing to order on them is cheap.)
1112 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1113 array_key_exists('extends', $table) && !empty($table['extends'])
1115 foreach ($table['fields'] as $fieldName => $field) {
1116 if (empty($field['no_display'])) {
1117 $options[$fieldName] = $field['title'];
1125 $this->assign('orderByOptions', $options);
1127 if (!empty($options)) {
1129 '-' => ' - none - ',
1131 for ($i = 1; $i <= 5; $i++
) {
1132 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1133 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1134 'ASC' => 'Ascending',
1135 'DESC' => 'Descending',
1137 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1138 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1143 public function buildInstanceAndButtons() {
1144 CRM_Report_Form_Instance
::buildForm($this);
1146 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1148 $this->addElement('submit', $this->_instanceButtonName
, $label);
1149 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1150 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1153 $this->addElement('submit', $this->_createNewButtonName
,
1154 ts('Save a Copy') . '...');
1156 $this->assign('instanceForm', $this->_instanceForm
);
1158 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1159 $this->addElement('submit', $this->_printButtonName
, $label);
1161 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1162 $this->addElement('submit', $this->_pdfButtonName
, $label);
1164 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1166 if ($this->_csvSupported
) {
1167 $this->addElement('submit', $this->_csvButtonName
, $label);
1170 if (CRM_Core_Permission
::check('administer Reports') &&
1171 $this->_add2groupSupported
1173 $this->addElement('select', 'groups', ts('Group'),
1174 array('' => ts('Add Contacts to Group')) +
1175 CRM_Core_PseudoConstant
::nestedGroup(),
1176 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1178 $this->assign('group', TRUE);
1181 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1183 $this->addChartOptions();
1184 $this->addButtons(array(
1187 'name' => ts('Preview Report'),
1188 'isDefault' => TRUE,
1194 public function buildQuickForm() {
1195 $this->addColumns();
1197 $this->addFilters();
1199 $this->addOptions();
1201 $this->addGroupBys();
1203 $this->addOrderBys();
1205 $this->buildInstanceAndButtons();
1207 //add form rule for report
1208 if (is_callable(array(
1212 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1217 * a formrule function to ensure that fields selected in group_by
1218 * (if any) should only be the ones present in display/select fields criteria;
1219 * note: works if and only if any custom field selected in group_by.
1221 * @param array $ignoreFields
1225 public function customDataFormRule($fields, $ignoreFields = array()) {
1227 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1228 !empty($fields['group_bys'])
1230 foreach ($this->_columns
as $tableName => $table) {
1231 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1232 substr($tableName, 0, 12) == 'custom_value') &&
1233 !empty($this->_columns
[$tableName]['fields'])
1235 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1236 if (array_key_exists($fieldName, $fields['group_bys']) &&
1237 !array_key_exists($fieldName, $fields['fields'])
1239 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1241 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1242 foreach ($fields['fields'] as $fld => $val) {
1243 if (!array_key_exists($fld, $fields['group_bys']) &&
1244 !in_array($fld, $ignoreFields)
1246 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1258 * Note: $fieldName param allows inheriting class to build operationPairs
1259 * specific to a field.
1260 * @param string $type
1261 * @param null $fieldName
1265 public function getOperationPair($type = "string", $fieldName = NULL) {
1266 // FIXME: At some point we should move these key-val pairs
1267 // to option_group and option_value table.
1269 case CRM_Report_Form
::OP_INT
:
1270 case CRM_Report_Form
::OP_FLOAT
:
1272 'lte' => ts('Is less than or equal to'),
1273 'gte' => ts('Is greater than or equal to'),
1274 'bw' => ts('Is between'),
1275 'eq' => ts('Is equal to'),
1276 'lt' => ts('Is less than'),
1277 'gt' => ts('Is greater than'),
1278 'neq' => ts('Is not equal to'),
1279 'nbw' => ts('Is not between'),
1280 'nll' => ts('Is empty (Null)'),
1281 'nnll' => ts('Is not empty (Null)'),
1284 case CRM_Report_Form
::OP_SELECT
:
1286 'eq' => ts('Is equal to'),
1289 case CRM_Report_Form
::OP_MONTH
:
1290 case CRM_Report_Form
::OP_MULTISELECT
:
1291 case CRM_Report_Form
::OP_ENTITYREF
:
1293 'in' => ts('Is one of'),
1294 'notin' => ts('Is not one of'),
1297 case CRM_Report_Form
::OP_DATE
:
1299 'nll' => ts('Is empty (Null)'),
1300 'nnll' => ts('Is not empty (Null)'),
1303 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1304 // use this operator for the values, concatenated with separator. For e.g if
1305 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1307 'mhas' => ts('Is one of'),
1308 'mnot' => ts('Is not one of'),
1314 'has' => ts('Contains'),
1315 'sw' => ts('Starts with'),
1316 'ew' => ts('Ends with'),
1317 'nhas' => ts('Does not contain'),
1318 'eq' => ts('Is equal to'),
1319 'neq' => ts('Is not equal to'),
1320 'nll' => ts('Is empty (Null)'),
1321 'nnll' => ts('Is not empty (Null)'),
1326 public function buildTagFilter() {
1327 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1328 if (!empty($contactTags)) {
1329 $this->_columns
['civicrm_tag'] = array(
1330 'dao' => 'CRM_Core_DAO_Tag',
1334 'title' => ts('Tag'),
1336 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1337 'options' => $contactTags,
1345 * Adds group filters to _columns (called from _Constuct
1347 public function buildGroupFilter() {
1348 $this->_columns
['civicrm_group']['filters'] = array(
1350 'name' => 'group_id',
1351 'title' => ts('Group'),
1352 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1354 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1357 if (empty($this->_columns
['civicrm_group']['dao'])) {
1358 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1360 if (empty($this->_columns
['civicrm_group']['alias'])) {
1361 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1366 * @param string $operator
1370 public function getSQLOperator($operator = "like") {
1371 switch ($operator) {
1404 return 'IS NOT NULL';
1419 * @return null|string
1421 function whereClause(
1426 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1432 if (($min !== NULL && strlen($min) > 0) ||
1433 ($max !== NULL && strlen($max) > 0)
1435 $min = CRM_Utils_Type
::escape($min, $type);
1436 $max = CRM_Utils_Type
::escape($max, $type);
1440 $clauses[] = "( {$field['dbAlias']} >= $min )";
1443 $clauses[] = "( {$field['dbAlias']} < $min )";
1448 $clauses[] = "( {$field['dbAlias']} <= $max )";
1451 $clauses[] = "( {$field['dbAlias']} > $max )";
1455 if (!empty($clauses)) {
1457 $clause = implode(' AND ', $clauses);
1460 $clause = implode(' OR ', $clauses);
1468 if ($value !== NULL && strlen($value) > 0) {
1469 $value = CRM_Utils_Type
::escape($value, $type);
1470 if (strpos($value, '%') === FALSE) {
1471 $value = "'%{$value}%'";
1474 $value = "'{$value}'";
1476 $sqlOP = $this->getSQLOperator($op);
1477 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1483 if (is_string($value) && strlen($value)) {
1484 $value = explode(',', $value);
1486 if ($value !== NULL && is_array($value) && count($value) > 0) {
1487 $sqlOP = $this->getSQLOperator($op);
1488 if (CRM_Utils_Array
::value('type', $field) ==
1489 CRM_Utils_Type
::T_STRING
1491 //cycle through selections and esacape values
1492 foreach ($value as $key => $selection) {
1493 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1496 "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1500 // for numerical values
1501 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1504 if ($op == 'notin') {
1505 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1508 $clause = "( " . $clause . " )";
1514 // mhas == multiple has
1515 if ($value !== NULL && count($value) > 0) {
1516 $sqlOP = $this->getSQLOperator($op);
1518 "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) .
1524 // mnot == multiple is not one of
1525 if ($value !== NULL && count($value) > 0) {
1526 $sqlOP = $this->getSQLOperator($op);
1528 "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) .
1529 "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1535 if ($value !== NULL && strlen($value) > 0) {
1536 $value = CRM_Utils_Type
::escape($value, $type);
1537 if (strpos($value, '%') === FALSE) {
1539 $value = "'{$value}%'";
1542 $value = "'%{$value}'";
1546 $value = "'{$value}'";
1548 $sqlOP = $this->getSQLOperator($op);
1549 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1555 $sqlOP = $this->getSQLOperator($op);
1556 $clause = "( {$field['dbAlias']} $sqlOP )";
1560 if ($value !== NULL && strlen($value) > 0) {
1561 if (isset($field['clause'])) {
1562 // FIXME: we not doing escape here. Better solution is to use two
1563 // different types - data-type and filter-type
1564 $clause = $field['clause'];
1567 $value = CRM_Utils_Type
::escape($value, $type);
1568 $sqlOP = $this->getSQLOperator($op);
1569 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1570 $value = "'{$value}'";
1572 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1578 if (!empty($field['group']) && $clause) {
1579 $clause = $this->whereGroupClause($field, $value, $op);
1581 elseif (!empty($field['tag']) && $clause) {
1582 // not using left join in query because if any contact
1583 // belongs to more than one tag, results duplicate
1585 $clause = $this->whereTagClause($field, $value, $op);
1587 elseif (!empty($field['membership_org']) && $clause) {
1588 $clause = $this->whereMembershipOrgClause($field, $value, $op);
1590 elseif (!empty($field['membership_type']) && $clause) {
1591 $clause = $this->whereMembershipTypeClause($field, $value, $op);
1597 * @param string $fieldName
1602 * @param null $fromTime
1603 * @param null $toTime
1605 * @return null|string
1607 function dateClause(
1609 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1612 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1613 $sqlOP = $this->getSQLOperator($relative);
1614 return "( {$fieldName} {$sqlOP} )";
1617 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1620 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1621 $clauses[] = "( {$fieldName} >= $from )";
1625 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1626 $clauses[] = "( {$fieldName} <= {$to} )";
1629 if (!empty($clauses)) {
1630 return implode(' AND ', $clauses);
1637 * @todo - could not find any instances where this is called
1639 * @param unknown_type $relative
1640 * @param string $from
1641 * @param string_type $to
1643 * @return string|NULL
1645 public function dateDisplay($relative, $from, $to) {
1646 list($from, $to) = $this->getFromTo($relative, $from, $to);
1649 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1652 $clauses[] = 'Past';
1656 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1659 $clauses[] = 'Today';
1662 if (!empty($clauses)) {
1663 return implode(' - ', $clauses);
1673 * @param null $fromtime
1674 * @param null $totime
1678 public function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1679 if (empty($totime)) {
1682 //FIX ME not working for relative
1684 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1685 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1686 $from = substr($dateRange['from'], 0, 8);
1687 //Take only Date Part, Sometime Time part is also present in 'to'
1688 $to = substr($dateRange['to'], 0, 8);
1690 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1691 $to = CRM_Utils_Date
::processDate($to, $totime);
1692 return array($from, $to);
1698 public function alterDisplay(&$rows) {
1699 // custom code to alter rows
1705 public function alterCustomDataDisplay(&$rows) {
1706 // custom code to alter rows having custom values
1707 if (empty($this->_customGroupExtends
)) {
1711 $customFieldIds = array();
1712 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1713 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1714 $customFieldIds[$fieldAlias] = $fieldId;
1717 if (empty($customFieldIds)) {
1721 $customFields = $fieldValueMap = array();
1722 $customFieldCols = array(
1730 // skip for type date and ContactReference since date format is already handled
1732 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1733 FROM civicrm_custom_field cf
1734 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1735 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1736 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1737 cg.is_active = 1 AND
1738 cf.is_active = 1 AND
1739 cf.is_searchable = 1 AND
1740 cf.data_type NOT IN ('ContactReference', 'Date') AND
1741 cf.id IN (" . implode(",", $customFieldIds) . ")";
1743 $dao = CRM_Core_DAO
::executeQuery($query);
1744 while ($dao->fetch()) {
1745 foreach ($customFieldCols as $key) {
1746 $customFields[$dao->table_name
. '_custom_' .
1747 $dao->id
][$key] = $dao->$key;
1749 if ($dao->option_group_id
) {
1750 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1755 $entryFound = FALSE;
1756 foreach ($rows as $rowNum => $row) {
1757 foreach ($row as $tableCol => $val) {
1758 if (array_key_exists($tableCol, $customFields)) {
1759 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1764 // skip looking further in rows, if first row itself doesn't
1765 // have the column we need
1774 * @param $customField
1775 * @param $fieldValueMap
1777 * @return float|string
1779 public function formatCustomValues($value, $customField, $fieldValueMap) {
1780 if (CRM_Utils_System
::isNull($value)) {
1784 $htmlType = $customField['html_type'];
1786 switch ($customField['data_type']) {
1788 if ($value == '1') {
1789 $retValue = ts('Yes');
1792 $retValue = ts('No');
1797 $retValue = CRM_Utils_System
::formatWikiURL($value);
1809 if ($htmlType == 'Text') {
1810 $retValue = (float) $value;
1814 if ($htmlType == 'Text') {
1817 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1822 if (in_array($htmlType, array(
1829 case 'StateProvince':
1832 switch ($htmlType) {
1833 case 'Multi-Select Country':
1834 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1835 $customData = array();
1836 foreach ($value as $val) {
1838 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1841 $retValue = implode(', ', $customData);
1844 case 'Select Country':
1845 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1848 case 'Select State/Province':
1849 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1852 case 'Multi-Select State/Province':
1853 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1854 $customData = array();
1855 foreach ($value as $val) {
1857 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1860 $retValue = implode(', ', $customData);
1865 case 'Autocomplete-Select':
1866 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1870 case 'AdvMulti-Select':
1871 case 'Multi-Select':
1872 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1873 $customData = array();
1874 foreach ($value as $val) {
1876 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1879 $retValue = implode(', ', $customData);
1897 public function removeDuplicates(&$rows) {
1898 if (empty($this->_noRepeats
)) {
1901 $checkList = array();
1903 foreach ($rows as $key => $list) {
1904 foreach ($list as $colName => $colVal) {
1905 if (array_key_exists($colName, $checkList) &&
1906 $checkList[$colName] == $colVal
1908 $rows[$key][$colName] = "";
1910 if (in_array($colName, $this->_noRepeats
)) {
1911 $checkList[$colName] = $colVal;
1920 * @param bool $subtotal
1922 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1923 foreach ($row as $colName => $colVal) {
1924 if (in_array($colName, $fields)) {
1925 $row[$colName] = $row[$colName];
1927 elseif (isset($this->_columnHeaders
[$colName])) {
1929 $row[$colName] = "Subtotal";
1933 unset($row[$colName]);
1944 public function grandTotal(&$rows) {
1945 if (!$this->_rollup ||
($this->_rollup
== '') ||
1946 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1950 $lastRow = array_pop($rows);
1952 foreach ($this->_columnHeaders
as $fld => $val) {
1953 if (!in_array($fld, $this->_statFields
)) {
1954 if (!$this->_grandFlag
) {
1955 $lastRow[$fld] = "Grand Total";
1956 $this->_grandFlag
= TRUE;
1959 $lastRow[$fld] = "";
1964 $this->assign('grandStat', $lastRow);
1970 * @param bool $pager
1972 public function formatDisplay(&$rows, $pager = TRUE) {
1973 // set pager based on if any limit was applied in the query.
1978 // allow building charts if any
1979 if (!empty($this->_params
['charts']) && !empty($rows)) {
1980 $this->buildChart($rows);
1981 $this->assign('chartEnabled', TRUE);
1982 $this->_chartId
= "{$this->_params['charts']}_" .
1983 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
1985 $this->assign('chartId', $this->_chartId
);
1988 // unset columns not to be displayed.
1989 foreach ($this->_columnHeaders
as $key => $value) {
1990 if (!empty($value['no_display'])) {
1991 unset($this->_columnHeaders
[$key]);
1995 // unset columns not to be displayed.
1996 if (!empty($rows)) {
1997 foreach ($this->_noDisplay
as $noDisplayField) {
1998 foreach ($rows as $rowNum => $row) {
1999 unset($this->_columnHeaders
[$noDisplayField]);
2004 // build array of section totals
2005 $this->sectionTotals();
2007 // process grand-total row
2008 $this->grandTotal($rows);
2010 // use this method for formatting rows for display purpose.
2011 $this->alterDisplay($rows);
2012 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2014 // use this method for formatting custom rows for display purpose.
2015 $this->alterCustomDataDisplay($rows);
2021 public function buildChart(&$rows) {
2022 // override this method for building charts.
2025 // select() method below has been added recently (v3.3), and many of the report templates might
2026 // still be having their own select() method. We should fix them as and when encountered and move
2027 // towards generalizing the select() method below.
2028 public function select() {
2029 $select = $this->_selectAliases
= array();
2031 foreach ($this->_columns
as $tableName => $table) {
2032 if (array_key_exists('fields', $table)) {
2033 foreach ($table['fields'] as $fieldName => $field) {
2034 if ($tableName == 'civicrm_address') {
2035 $this->_addressField
= TRUE;
2037 if ($tableName == 'civicrm_email') {
2038 $this->_emailField
= TRUE;
2040 if ($tableName == 'civicrm_phone') {
2041 $this->_phoneField
= TRUE;
2044 if (!empty($field['required']) ||
2045 !empty($this->_params
['fields'][$fieldName])
2048 // 1. In many cases we want select clause to be built in slightly different way
2049 // for a particular field of a particular type.
2050 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2052 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2053 if ($selectClause) {
2054 $select[] = $selectClause;
2058 // include statistics columns only if set
2059 if (!empty($field['statistics'])) {
2060 foreach ($field['statistics'] as $stat => $label) {
2061 $alias = "{$tableName}_{$fieldName}_{$stat}";
2062 switch (strtolower($stat)) {
2065 $select[] = "$stat({$field['dbAlias']}) as $alias";
2066 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2067 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2068 $this->_statFields
[$label] = $alias;
2069 $this->_selectAliases
[] = $alias;
2073 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2074 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2075 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2076 $this->_statFields
[$label] = $alias;
2077 $this->_selectAliases
[] = $alias;
2080 case 'count_distinct':
2081 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2082 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2083 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2084 $this->_statFields
[$label] = $alias;
2085 $this->_selectAliases
[] = $alias;
2089 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2090 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2091 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2092 $this->_statFields
[$label] = $alias;
2093 $this->_selectAliases
[] = $alias;
2099 $alias = "{$tableName}_{$fieldName}";
2100 $select[] = "{$field['dbAlias']} as $alias";
2101 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2102 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2103 $this->_selectAliases
[] = $alias;
2109 // select for group bys
2110 if (array_key_exists('group_bys', $table)) {
2111 foreach ($table['group_bys'] as $fieldName => $field) {
2113 if ($tableName == 'civicrm_address') {
2114 $this->_addressField
= TRUE;
2116 if ($tableName == 'civicrm_email') {
2117 $this->_emailField
= TRUE;
2119 if ($tableName == 'civicrm_phone') {
2120 $this->_phoneField
= TRUE;
2122 // 1. In many cases we want select clause to be built in slightly different way
2123 // for a particular field of a particular type.
2124 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2126 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2127 if ($selectClause) {
2128 $select[] = $selectClause;
2132 if (!empty($this->_params
['group_bys']) &&
2133 !empty($this->_params
['group_bys'][$fieldName]) &&
2134 !empty($this->_params
['group_bys_freq'])
2136 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2138 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2139 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2140 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2141 $field['title'] = 'Week';
2145 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2146 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2147 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2148 $field['title'] = 'Year';
2152 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2153 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2154 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2155 $field['title'] = 'Month';
2159 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2160 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2161 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2162 $field['title'] = 'Quarter';
2165 // for graphs and charts -
2166 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2167 $this->_interval
= $field['title'];
2168 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] =
2169 $field['title'] . ' Beginning';
2170 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2171 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2173 // just to make sure these values are transfered to rows.
2174 // since we 'll need them for calculation purpose,
2175 // e.g making subtotals look nicer or graphs
2176 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2177 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2184 $this->_selectClauses
= $select;
2185 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2189 * @param string $tableName
2191 * @param string $fieldName
2196 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2200 public function where() {
2201 $this->storeWhereHavingClauseArray();
2203 if (empty($this->_whereClauses
)) {
2204 $this->_where
= "WHERE ( 1 ) ";
2205 $this->_having
= "";
2208 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2211 if ($this->_aclWhere
) {
2212 $this->_where
.= " AND {$this->_aclWhere} ";
2215 if (!empty($this->_havingClauses
)) {
2216 // use this clause to construct group by clause.
2217 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2222 * Store Where clauses into an array - breaking out this step makes
2223 * over-riding more flexible as the clauses can be used in constructing a
2224 * temp table that may not be part of the final where clause or added
2225 * in other functions
2227 public function storeWhereHavingClauseArray() {
2228 foreach ($this->_columns
as $tableName => $table) {
2229 if (array_key_exists('filters', $table)) {
2230 foreach ($table['filters'] as $fieldName => $field) {
2231 // respect pseudofield to filter spec so fields can be marked as
2232 // not to be handled here
2233 if (!empty($field['pseudofield'])) {
2237 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2238 if (CRM_Utils_Array
::value('operatorType', $field) ==
2239 CRM_Report_Form
::OP_MONTH
2241 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2242 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2243 if (is_array($value) && !empty($value)) {
2245 "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2250 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2251 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2252 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2253 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2254 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2255 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2259 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2261 $clause = $this->whereClause($field,
2263 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2264 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2265 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2270 if (!empty($clause)) {
2271 if (!empty($field['having'])) {
2272 $this->_havingClauses
[] = $clause;
2275 $this->_whereClauses
[] = $clause;
2284 public function processReportMode() {
2285 $buttonName = $this->controller
->getButtonName();
2287 $output = CRM_Utils_Request
::retrieve(
2290 CRM_Core_DAO
::$_nullObject
2294 CRM_Utils_Request
::retrieve(
2297 CRM_Core_DAO
::$_nullObject
2300 $this->_absoluteUrl
= FALSE;
2302 $this->assign('printOnly', FALSE);
2304 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2305 ($this->_sendmail
&& !$output)
2307 $this->assign('printOnly', TRUE);
2309 $this->assign('outputMode', 'print');
2310 $this->_outputMode
= 'print';
2311 if ($this->_sendmail
) {
2312 $this->_absoluteUrl
= TRUE;
2315 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2316 $this->assign('printOnly', TRUE);
2318 $this->assign('outputMode', 'pdf');
2319 $this->_outputMode
= 'pdf';
2320 $this->_absoluteUrl
= TRUE;
2322 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2323 $this->assign('printOnly', TRUE);
2325 $this->assign('outputMode', 'csv');
2326 $this->_outputMode
= 'csv';
2327 $this->_absoluteUrl
= TRUE;
2329 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2330 $this->assign('outputMode', 'group');
2331 $this->_outputMode
= 'group';
2333 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2334 $this->assign('outputMode', 'create_report');
2335 $this->_outputMode
= 'create_report';
2338 $this->assign('outputMode', 'html');
2339 $this->_outputMode
= 'html';
2342 // Get today's date to include in printed reports
2344 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2345 $this->assign('reportDate', $reportDate);
2350 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2352 public function beginPostProcess() {
2353 $this->setParams($this->controller
->exportValues($this->_name
));
2355 if (empty($this->_params
) &&
2358 $this->setParams($this->_formValues
);
2361 // hack to fix params when submitted from dashboard, CRM-8532
2362 // fields array is missing because form building etc is skipped
2363 // in dashboard mode for report
2364 //@todo - this could be done in the dashboard no we have a setter
2365 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2366 $this->setParams($this->_formValues
);
2369 $this->_formValues
= $this->_params
;
2370 if (CRM_Core_Permission
::check('administer Reports') &&
2371 isset($this->_id
) &&
2372 ($this->_instanceButtonName
==
2373 $this->controller
->getButtonName() . '_save' ||
2374 $this->_chartButtonName
== $this->controller
->getButtonName()
2377 $this->assign('updateReportButton', TRUE);
2379 $this->processReportMode();
2380 $this->beginPostProcessCommon();
2384 * BeginPostProcess function run in both report mode and non-report mode (api)
2386 public function beginPostProcessCommon() {
2391 * @param bool $applyLimit
2395 public function buildQuery($applyLimit = TRUE) {
2398 $this->customDataFrom();
2403 // order_by columns not selected for display need to be included in SELECT
2404 $unselectedSectionColumns = $this->unselectedSectionColumns();
2405 foreach ($unselectedSectionColumns as $alias => $section) {
2406 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2409 if ($applyLimit && empty($this->_params
['charts'])) {
2412 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2414 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2418 public function groupBy() {
2419 $groupBys = array();
2420 if (!empty($this->_params
['group_bys']) &&
2421 is_array($this->_params
['group_bys']) &&
2422 !empty($this->_params
['group_bys'])
2424 foreach ($this->_columns
as $tableName => $table) {
2425 if (array_key_exists('group_bys', $table)) {
2426 foreach ($table['group_bys'] as $fieldName => $field) {
2427 if (!empty($this->_params
['group_bys'][$fieldName])) {
2428 $groupBys[] = $field['dbAlias'];
2435 if (!empty($groupBys)) {
2436 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2440 public function orderBy() {
2441 $this->_orderBy
= "";
2442 $this->_sections
= array();
2443 $this->storeOrderByArray();
2444 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2445 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2447 $this->assign('sections', $this->_sections
);
2451 * In some cases other functions want to know which fields are selected for ordering by
2452 * Separating this into a separate function allows it to be called separately from constructing
2453 * the order by clause
2455 public function storeOrderByArray() {
2456 $orderBys = array();
2458 if (!empty($this->_params
['order_bys']) &&
2459 is_array($this->_params
['order_bys']) &&
2460 !empty($this->_params
['order_bys'])
2463 // Proces order_bys in user-specified order
2464 foreach ($this->_params
['order_bys'] as $orderBy) {
2465 $orderByField = array();
2466 foreach ($this->_columns
as $tableName => $table) {
2467 if (array_key_exists('order_bys', $table)) {
2468 // For DAO columns defined in $this->_columns
2469 $fields = $table['order_bys'];
2471 elseif (array_key_exists('extends', $table)) {
2472 // For custom fields referenced in $this->_customGroupExtends
2473 $fields = CRM_Utils_Array
::value('fields', $table, array());
2475 if (!empty($fields) && is_array($fields)) {
2476 foreach ($fields as $fieldName => $field) {
2477 if ($fieldName == $orderBy['column']) {
2478 $orderByField = array_merge($field, $orderBy);
2479 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2486 if (!empty($orderByField)) {
2487 $this->_orderByFields
[] = $orderByField;
2488 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2490 // Record any section headers for assignment to the template
2491 if (!empty($orderBy['section'])) {
2492 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2493 $this->_sections
[$orderByField['tplField']] = $orderByField;
2499 $this->_orderByArray
= $orderBys;
2501 $this->assign('sections', $this->_sections
);
2507 public function unselectedSectionColumns() {
2508 $selectColumns = array();
2509 foreach ($this->_columns
as $tableName => $table) {
2510 if (array_key_exists('fields', $table)) {
2511 foreach ($table['fields'] as $fieldName => $field) {
2512 if (!empty($field['required']) ||
2513 !empty($this->_params
['fields'][$fieldName])
2516 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2522 if (is_array($this->_sections
)) {
2523 return array_diff_key($this->_sections
, $selectColumns);
2534 public function buildRows($sql, &$rows) {
2535 $dao = CRM_Core_DAO
::executeQuery($sql);
2536 if (!is_array($rows)) {
2540 // use this method to modify $this->_columnHeaders
2541 $this->modifyColumnHeaders();
2543 $unselectedSectionColumns = $this->unselectedSectionColumns();
2545 while ($dao->fetch()) {
2547 foreach ($this->_columnHeaders
as $key => $value) {
2548 if (property_exists($dao, $key)) {
2549 $row[$key] = $dao->$key;
2553 // section headers not selected for display need to be added to row
2554 foreach ($unselectedSectionColumns as $key => $values) {
2555 if (property_exists($dao, $key)) {
2556 $row[$key] = $dao->$key;
2565 * When "order by" fields are marked as sections, this assigns to the template
2566 * an array of total counts for each section. This data is used by the Smarty
2567 * plugin {sectionTotal}
2569 public function sectionTotals() {
2571 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2572 if (empty($this->_selectAliases
)) {
2576 if (!empty($this->_sections
)) {
2577 // build the query with no LIMIT clause
2578 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2579 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2581 // pull section aliases out of $this->_sections
2582 $sectionAliases = array_keys($this->_sections
);
2585 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2586 $ifnulls[] = "ifnull($alias, '') as $alias";
2589 /* Group (un-limited) report by all aliases and get counts. This might
2590 * be done more efficiently when the contents of $sql are known, ie. by
2591 * overriding this method in the report class.
2595 $query = "select " . implode(", ", $ifnulls) .
2596 ", count(*) as ct from ($sql) as subquery group by " .
2597 implode(", ", $sectionAliases);
2599 // initialize array of total counts
2601 $dao = CRM_Core_DAO
::executeQuery($query);
2602 while ($dao->fetch()) {
2604 // let $this->_alterDisplay translate any integer ids to human-readable values.
2605 $rows[0] = $dao->toArray();
2606 $this->alterDisplay($rows);
2609 // add totals for all permutations of section values
2612 $aliasCount = count($sectionAliases);
2613 foreach ($sectionAliases as $alias) {
2614 $values[] = $row[$alias];
2615 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2616 if ($i == $aliasCount) {
2617 // the last alias is the lowest-level section header; use count as-is
2618 $totals[$key] = $dao->ct
;
2621 // other aliases are higher level; roll count into their total
2622 $totals[$key] +
= $dao->ct
;
2626 $this->assign('sectionTotals', $totals);
2630 public function modifyColumnHeaders() {
2631 // use this method to modify $this->_columnHeaders
2637 public function doTemplateAssignment(&$rows) {
2638 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2639 $this->assign_by_ref('rows', $rows);
2640 $this->assign('statistics', $this->statistics($rows));
2644 * override this method to build your own statistics
2649 public function statistics(&$rows) {
2650 $statistics = array();
2652 $count = count($rows);
2654 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2658 $this->countStat($statistics, $count);
2660 $this->groupByStat($statistics);
2662 $this->filterStat($statistics);
2668 * @param $statistics
2671 public function countStat(&$statistics, $count) {
2672 $statistics['counts']['rowCount'] = array(
2673 'title' => ts('Row(s) Listed'),
2677 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2678 $statistics['counts']['rowsFound'] = array(
2679 'title' => ts('Total Row(s)'),
2680 'value' => $this->_rowsFound
,
2686 * @param $statistics
2688 public function groupByStat(&$statistics) {
2689 if (!empty($this->_params
['group_bys']) &&
2690 is_array($this->_params
['group_bys']) &&
2691 !empty($this->_params
['group_bys'])
2693 foreach ($this->_columns
as $tableName => $table) {
2694 if (array_key_exists('group_bys', $table)) {
2695 foreach ($table['group_bys'] as $fieldName => $field) {
2696 if (!empty($this->_params
['group_bys'][$fieldName])) {
2697 $combinations[] = $field['title'];
2702 $statistics['groups'][] = array(
2703 'title' => ts('Grouping(s)'),
2704 'value' => implode(' & ', $combinations),
2710 * @param $statistics
2712 public function filterStat(&$statistics) {
2713 foreach ($this->_columns
as $tableName => $table) {
2714 if (array_key_exists('filters', $table)) {
2715 foreach ($table['filters'] as $fieldName => $field) {
2716 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
2717 CRM_Utils_Array
::value('operatorType', $field) !=
2718 CRM_Report_Form
::OP_MONTH
2722 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2723 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2724 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2725 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2726 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2728 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2729 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2731 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2732 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2735 $statistics['filters'][] = array(
2736 'title' => $field['title'],
2737 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2740 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2741 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2743 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2744 $statistics['filters'][] = array(
2745 'title' => $field['title'],
2746 'value' => $pair[$rel],
2751 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2754 $pair = $this->getOperationPair(
2755 CRM_Utils_Array
::value('operatorType', $field),
2758 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2759 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2760 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2761 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
2762 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2764 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
2765 $this->setEntityRefDefaults($field, $tableName);
2766 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
2767 array('id' => $val) +
2768 CRM_Utils_Array
::value('api', $field['attributes'], array()));
2770 foreach ($result['values'] as $v) {
2771 $values[] = $v['label'];
2773 $value = "{$pair[$op]} " . implode(', ', $values);
2775 elseif ($op == 'nll' ||
$op == 'nnll') {
2776 $value = $pair[$op];
2778 elseif (is_array($val) && (!empty($val))) {
2779 $options = CRM_Utils_Array
::value('options', $field, array());
2780 foreach ($val as $key => $valIds) {
2781 if (isset($options[$valIds])) {
2782 $val[$key] = $options[$valIds];
2785 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
2786 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2787 $val = implode(', ', $val);
2788 $value = "{$pair[$op]} " . $val;
2790 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
2791 isset($field['options']) &&
2792 is_array($field['options']) && !empty($field['options'])
2794 $value = CRM_Utils_Array
::value($op, $pair) . " " .
2795 CRM_Utils_Array
::value($val, $field['options'], $val);
2798 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2802 $statistics['filters'][] = array(
2803 'title' => CRM_Utils_Array
::value('title', $field),
2816 public function endPostProcess(&$rows = NULL) {
2817 if ($this->_storeResultSet
) {
2818 $this->_resultSet
= $rows;
2821 if ($this->_outputMode
== 'print' ||
2822 $this->_outputMode
== 'pdf' ||
2826 $content = $this->compileContent();
2827 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2831 if ($this->_sendmail
) {
2832 $config = CRM_Core_Config
::singleton();
2833 $attachments = array();
2835 if ($this->_outputMode
== 'csv') {
2837 $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
2838 ": {$url}</p>" . '<p>' .
2839 ts('The report is attached as a CSV file.') . '</p>' .
2840 $this->_formValues
['report_footer'];
2842 $csvFullFilename = $config->templateCompileDir
.
2843 CRM_Utils_File
::makeFileName('CiviReport.csv');
2844 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2845 file_put_contents($csvFullFilename, $csvContent);
2846 $attachments[] = array(
2847 'fullPath' => $csvFullFilename,
2848 'mime_type' => 'text/csv',
2849 'cleanName' => 'CiviReport.csv',
2852 if ($this->_outputMode
== 'pdf') {
2853 // generate PDF content
2854 $pdfFullFilename = $config->templateCompileDir
.
2855 CRM_Utils_File
::makeFileName('CiviReport.pdf');
2856 file_put_contents($pdfFullFilename,
2857 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2858 TRUE, array('orientation' => 'landscape')
2861 // generate Email Content
2863 $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
2864 ": {$url}</p>" . '<p>' .
2865 ts('The report is attached as a PDF file.') . '</p>' .
2866 $this->_formValues
['report_footer'];
2868 $attachments[] = array(
2869 'fullPath' => $pdfFullFilename,
2870 'mime_type' => 'application/pdf',
2871 'cleanName' => 'CiviReport.pdf',
2875 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2876 $this->_outputMode
, $attachments
2879 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2882 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2886 elseif ($this->_outputMode
== 'print') {
2890 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2891 $config = CRM_Core_Config
::singleton();
2892 //get chart image name
2893 $chartImg = $this->_chartId
. '.png';
2894 //get image url path
2896 str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
2898 $uploadUrl .= $chartImg;
2899 //get image doc path to overwrite
2901 str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
2902 'openFlashChart/' . $chartImg;
2904 $chart = imagecreatefrompng($uploadUrl);
2905 //convert it into formattd png
2906 header('Content-type: image/png');
2907 //overwrite with same image
2908 imagepng($chart, $uploadImg);
2910 imagedestroy($chart);
2912 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2914 CRM_Utils_System
::civiExit();
2916 elseif ($this->_outputMode
== 'csv') {
2917 CRM_Report_Utils_Report
::export2csv($this, $rows);
2919 elseif ($this->_outputMode
== 'group') {
2920 $group = $this->_params
['groups'];
2921 $this->add2group($group);
2923 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2924 CRM_Report_Form_Instance
::postProcess($this);
2926 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2927 $this->_outputMode
== 'create_report'
2929 $this->_createNew
= TRUE;
2930 CRM_Report_Form_Instance
::postProcess($this);
2934 public function storeResultSet() {
2935 $this->_storeResultSet
= TRUE;
2941 public function getResultSet() {
2942 return $this->_resultSet
;
2946 * Use the form name to create the tpl file name
2950 public function getTemplateFileName() {
2951 $defaultTpl = parent
::getTemplateFileName();
2952 $template = CRM_Core_Smarty
::singleton();
2953 if (!$template->template_exists($defaultTpl)) {
2954 $defaultTpl = 'CRM/Report/Form.tpl';
2960 * Compile the report content
2961 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2965 public function compileContent() {
2966 $templateFile = $this->getHookedTemplateFileName();
2967 return $this->_formValues
['report_header'] .
2968 CRM_Core_Form
::$_template->fetch($templateFile) .
2969 $this->_formValues
['report_footer'];
2973 public function postProcess() {
2974 // get ready with post process params
2975 $this->beginPostProcess();
2978 $sql = $this->buildQuery();
2980 // build array of result based on column headers. This method also allows
2981 // modifying column headers before using it to build result set i.e $rows.
2983 $this->buildRows($sql, $rows);
2985 // format result set.
2986 $this->formatDisplay($rows);
2988 // assign variables to templates
2989 $this->doTemplateAssignment($rows);
2991 // do print / pdf / instance stuff if needed
2992 $this->endPostProcess($rows);
2996 * @param int $rowCount
2999 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3000 // lets do the pager if in html mode
3001 $this->_limit
= NULL;
3003 // CRM-14115, over-ride row count if rowCount is specified in URL
3004 if ($this->_dashBoardRowCount
) {
3005 $rowCount = $this->_dashBoardRowCount
;
3007 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3008 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3010 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3012 if (!$pageId && !empty($_POST)) {
3013 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3014 $pageId = max((int) @$_POST['crmPID_B'], 1);
3016 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3017 $pageId = max((int) @$_POST['crmPID'], 1);
3019 unset($_POST['crmPID_B'], $_POST['crmPID']);
3022 $pageId = $pageId ?
$pageId : 1;
3023 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3024 $offset = ($pageId - 1) * $rowCount;
3026 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3027 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3029 $this->_limit
= " LIMIT $offset, $rowCount";
3030 return array($offset, $rowCount);
3032 if ($this->_limitValue
) {
3033 if ($this->_offsetValue
) {
3034 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3037 $this->_limit
= " LIMIT " . $this->_limitValue
;
3043 * @param int $rowCount
3045 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3047 // CRM-14115, over-ride row count if rowCount is specified in URL
3048 if ($this->_dashBoardRowCount
) {
3049 $rowCount = $this->_dashBoardRowCount
;
3052 if ($this->_limit
&& ($this->_limit
!= '')) {
3053 $sql = "SELECT FOUND_ROWS();";
3054 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3056 'total' => $this->_rowsFound
,
3057 'rowCount' => $rowCount,
3058 'status' => ts('Records') . ' %%StatusMessage%%',
3059 'buttonBottom' => 'PagerBottomButton',
3060 'buttonTop' => 'PagerTopButton',
3061 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3064 $pager = new CRM_Utils_Pager($params);
3065 $this->assign_by_ref('pager', $pager);
3066 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3077 public function whereGroupClause($field, $value, $op) {
3079 $smartGroupQuery = "";
3081 $group = new CRM_Contact_DAO_Group();
3082 $group->is_active
= 1;
3084 $smartGroups = array();
3085 while ($group->fetch()) {
3086 if (in_array($group->id
, $this->_params
['gid_value']) &&
3087 $group->saved_search_id
3089 $smartGroups[] = $group->id
;
3093 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3095 $smartGroupQuery = '';
3096 if (!empty($smartGroups)) {
3097 $smartGroups = implode(',', $smartGroups);
3098 $smartGroupQuery = " UNION DISTINCT
3099 SELECT DISTINCT smartgroup_contact.contact_id
3100 FROM civicrm_group_contact_cache smartgroup_contact
3101 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3104 $sqlOp = $this->getSQLOperator($op);
3105 if (!is_array($value)) {
3106 $value = array($value);
3108 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3110 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3111 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3112 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3113 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3114 {$smartGroupQuery} ) ";
3124 public function whereTagClause($field, $value, $op) {
3125 // not using left join in query because if any contact
3126 // belongs to more than one tag, results duplicate
3128 $sqlOp = $this->getSQLOperator($op);
3129 if (!is_array($value)) {
3130 $value = array($value);
3132 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3133 $entity_table = $this->_tagFilterTable
;
3134 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3135 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3136 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3137 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3140 public function whereMembershipOrgClause($field, $value, $op) {
3141 $sqlOp = $this->getSQLOperator($op);
3142 if (!is_array($value)) {
3143 $value = array($value);
3146 $tmp_membership_org_sql_list = implode(', ', $value);
3147 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3148 SELECT DISTINCT mem.contact_id
3149 FROM civicrm_membership mem
3150 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3151 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3152 WHERE mt.member_of_contact_id IN (" .
3153 $tmp_membership_org_sql_list . ")
3154 AND mt.is_active = '1'
3155 AND mem_status.is_current_member = '1'
3156 AND mem_status.is_active = '1' ) ";
3159 public function whereMembershipTypeClause($field, $value, $op) {
3160 $sqlOp = $this->getSQLOperator($op);
3161 if (!is_array($value)) {
3162 $value = array($value);
3165 $tmp_membership_sql_list = implode(', ', $value);
3166 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3167 SELECT DISTINCT mem.contact_id
3168 FROM civicrm_membership mem
3169 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3170 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3171 WHERE mem.membership_type_id IN (" .
3172 $tmp_membership_sql_list . ")
3173 AND mt.is_active = '1'
3174 AND mem_status.is_current_member = '1'
3175 AND mem_status.is_active = '1' ) ";
3179 * @param string $tableAlias
3181 public function buildACLClause($tableAlias = 'contact_a') {
3182 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3186 * @param bool $addFields
3187 * @param array $permCustomGroupIds
3189 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3190 if (empty($this->_customGroupExtends
)) {
3193 if (!is_array($this->_customGroupExtends
)) {
3194 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3196 $customGroupWhere = '';
3197 if (!empty($permCustomGroupIds)) {
3198 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3202 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3203 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3204 FROM civicrm_custom_group cg
3205 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3206 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3208 cg.is_active = 1 AND
3209 cf.is_active = 1 AND
3210 cf.is_searchable = 1
3211 ORDER BY cg.weight, cf.weight";
3212 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3215 while ($customDAO->fetch()) {
3216 if ($customDAO->table_name
!= $curTable) {
3217 $curTable = $customDAO->table_name
;
3218 $curFields = $curFilters = array();
3221 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3222 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3223 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3224 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3231 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3232 $this->_columns
[$curTable][$colKey] = array();
3236 $fieldName = 'custom_' . $customDAO->cf_id
;
3239 // this makes aliasing work in favor
3240 $curFields[$fieldName] = array(
3241 'name' => $customDAO->column_name
,
3242 'title' => $customDAO->label
,
3243 'dataType' => $customDAO->data_type
,
3244 'htmlType' => $customDAO->html_type
,
3247 if ($this->_customGroupFilters
) {
3248 // this makes aliasing work in favor
3249 $curFilters[$fieldName] = array(
3250 'name' => $customDAO->column_name
,
3251 'title' => $customDAO->label
,
3252 'dataType' => $customDAO->data_type
,
3253 'htmlType' => $customDAO->html_type
,
3257 switch ($customDAO->data_type
) {
3260 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3261 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3262 // CRM-6946, show time part for datetime date fields
3263 if ($customDAO->time_format
) {
3264 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3269 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3270 $curFilters[$fieldName]['options'] = array(
3271 '' => ts('- select -'),
3275 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3279 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3280 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3284 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3285 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3289 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3290 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3294 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3296 if (!empty($customDAO->option_group_id
)) {
3297 if (in_array($customDAO->html_type
, array(
3302 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3305 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3307 if ($this->_customGroupFilters
) {
3308 $curFilters[$fieldName]['options'] = array();
3309 $ogDAO = CRM_Core_DAO
::executeQuery("SELECT ov.value, ov.label FROM civicrm_option_value ov WHERE ov.option_group_id = %1 ORDER BY ov.weight", array(
3311 $customDAO->option_group_id
,
3315 while ($ogDAO->fetch()) {
3316 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3318 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3323 case 'StateProvince':
3324 if (in_array($customDAO->html_type
, array(
3325 'Multi-Select State/Province',
3327 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3330 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3332 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3336 if (in_array($customDAO->html_type
, array(
3337 'Multi-Select Country',
3339 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3342 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3344 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3347 case 'ContactReference':
3348 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3349 $curFilters[$fieldName]['name'] = 'display_name';
3350 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3352 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3353 $curFields[$fieldName]['name'] = 'display_name';
3354 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3358 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3359 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3362 if (!array_key_exists('type', $curFields[$fieldName])) {
3363 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3367 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3369 if ($this->_customGroupFilters
) {
3370 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3372 if ($this->_customGroupGroupBy
) {
3373 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3378 public function customDataFrom() {
3379 if (empty($this->_customGroupExtends
)) {
3382 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3384 foreach ($this->_columns
as $table => $prop) {
3385 if (substr($table, 0, 13) == 'civicrm_value' ||
3386 substr($table, 0, 12) == 'custom_value'
3388 $extendsTable = $mapper[$prop['extends']];
3390 // check field is in params
3391 if (!$this->isFieldSelected($prop)) {
3394 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3396 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3398 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3399 // handle for ContactReference
3400 if (array_key_exists('fields', $prop)) {
3401 foreach ($prop['fields'] as $fieldName => $field) {
3402 if (CRM_Utils_Array
::value('dataType', $field) ==
3405 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3407 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3420 public function isFieldSelected($prop) {
3425 if (!empty($this->_params
['fields'])) {
3426 foreach (array_keys($prop['fields']) as $fieldAlias) {
3427 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3428 if ($customFieldId) {
3429 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3433 //might be survey response field.
3434 if (!empty($this->_params
['fields']['survey_response']) &&
3435 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3443 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3444 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3445 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3446 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3453 if (!empty($this->_params
['order_bys'])) {
3454 foreach (array_keys($prop['fields']) as $fieldAlias) {
3455 foreach ($this->_params
['order_bys'] as $orderBy) {
3456 if ($fieldAlias == $orderBy['column'] &&
3457 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3465 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3466 foreach ($prop['filters'] as $fieldAlias => $val) {
3475 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3476 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3477 ||
($attach != 'relative' &&
3478 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3484 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3485 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3496 * Check for empty order_by configurations and remove them; also set
3497 * template to hide them.
3499 public function preProcessOrderBy(&$formValues) {
3500 // Object to show/hide form elements
3501 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3503 $_showHide->addShow('optionField_1');
3505 // Cycle through order_by options; skip any empty ones, and hide them as well
3508 if (!empty($formValues['order_bys'])) {
3509 foreach ($formValues['order_bys'] as $order_by) {
3510 if ($order_by['column'] && $order_by['column'] != '-') {
3511 $_showHide->addShow('optionField_' . $n);
3512 $orderBys[$n] = $order_by;
3517 for ($i = $n; $i <= 5; $i++
) {
3519 $_showHide->addHide('optionField_' . $i);
3523 // overwrite order_by options with modified values
3524 if (!empty($orderBys)) {
3525 $formValues['order_bys'] = $orderBys;
3528 $formValues['order_bys'] = array(1 => array('column' => '-'));
3531 // assign show/hide data to template
3532 $_showHide->addToTemplate();
3536 * Does table name have columns in SELECT clause?
3538 * @param string $tableName
3539 * Name of table (index of $this->_columns array).
3543 public function isTableSelected($tableName) {
3544 return in_array($tableName, $this->selectedTables());
3548 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3549 * (building the array if it's unset)
3554 public function selectedTables() {
3555 if (!$this->_selectedTables
) {
3556 $orderByColumns = array();
3557 if (array_key_exists('order_bys', $this->_params
) &&
3558 is_array($this->_params
['order_bys'])
3560 foreach ($this->_params
['order_bys'] as $orderBy) {
3561 $orderByColumns[] = $orderBy['column'];
3565 foreach ($this->_columns
as $tableName => $table) {
3566 if (array_key_exists('fields', $table)) {
3567 foreach ($table['fields'] as $fieldName => $field) {
3568 if (!empty($field['required']) ||
3569 !empty($this->_params
['fields'][$fieldName])
3571 $this->_selectedTables
[] = $tableName;
3576 if (array_key_exists('order_bys', $table)) {
3577 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3578 if (in_array($orderByName, $orderByColumns)) {
3579 $this->_selectedTables
[] = $tableName;
3584 if (array_key_exists('filters', $table)) {
3585 foreach ($table['filters'] as $filterName => $filter) {
3586 if (!empty($this->_params
["{$filterName}_value"]) ||
3587 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3589 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3592 $this->_selectedTables
[] = $tableName;
3599 return $this->_selectedTables
;
3603 * @deprecated - use getAddressColumns which is a more accurate description
3604 * and also accepts an array of options rather than a long list
3606 * adding address fields to construct function in reports
3608 * @param bool $groupBy
3609 * Add GroupBy? Not appropriate for detail report.
3610 * @param bool $orderBy
3611 * Add GroupBy? Not appropriate for detail report.
3612 * @param bool $filters
3613 * @param array $defaults
3616 * address fields for construct clause
3618 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3619 $addressFields = array(
3620 'civicrm_address' => array(
3621 'dao' => 'CRM_Core_DAO_Address',
3624 'title' => ts('Address Name'),
3625 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3627 'street_address' => array(
3628 'title' => ts('Street Address'),
3629 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3631 'supplemental_address_1' => array(
3632 'title' => ts('Supplementary Address Field 1'),
3633 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3635 'supplemental_address_2' => array(
3636 'title' => ts('Supplementary Address Field 2'),
3637 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3639 'street_number' => array(
3640 'name' => 'street_number',
3641 'title' => ts('Street Number'),
3643 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3645 'street_name' => array(
3646 'name' => 'street_name',
3647 'title' => ts('Street Name'),
3649 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3651 'street_unit' => array(
3652 'name' => 'street_unit',
3653 'title' => ts('Street Unit'),
3655 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3658 'title' => ts('City'),
3659 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3661 'postal_code' => array(
3662 'title' => ts('Postal Code'),
3663 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3665 'postal_code_suffix' => array(
3666 'title' => ts('Postal Code Suffix'),
3667 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3669 'country_id' => array(
3670 'title' => ts('Country'),
3671 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3673 'state_province_id' => array(
3674 'title' => ts('State/Province'),
3675 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3677 'county_id' => array(
3678 'title' => ts('County'),
3679 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3682 'grouping' => 'location-fields',
3687 $addressFields['civicrm_address']['filters'] = array(
3688 'street_number' => array(
3689 'title' => ts('Street Number'),
3691 'name' => 'street_number',
3693 'street_name' => array(
3694 'title' => ts('Street Name'),
3695 'name' => 'street_name',
3696 'operator' => 'like',
3698 'postal_code' => array(
3699 'title' => ts('Postal Code'),
3701 'name' => 'postal_code',
3704 'title' => ts('City'),
3705 'operator' => 'like',
3708 'country_id' => array(
3709 'name' => 'country_id',
3710 'title' => ts('Country'),
3711 'type' => CRM_Utils_Type
::T_INT
,
3712 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3713 'options' => CRM_Core_PseudoConstant
::country(),
3715 'state_province_id' => array(
3716 'name' => 'state_province_id',
3717 'title' => ts('State/Province'),
3718 'type' => CRM_Utils_Type
::T_INT
,
3719 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3720 'options' => array(),
3722 'county_id' => array(
3723 'name' => 'county_id',
3724 'title' => ts('County'),
3725 'type' => CRM_Utils_Type
::T_INT
,
3726 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3727 'options' => array(),
3733 $addressFields['civicrm_address']['order_bys'] = array(
3734 'street_name' => array('title' => ts('Street Name')),
3735 'street_number' => array('title' => 'Odd / Even Street Number'),
3736 'street_address' => NULL,
3738 'postal_code' => NULL,
3743 $addressFields['civicrm_address']['group_bys'] = array(
3744 'street_address' => NULL,
3746 'postal_code' => NULL,
3747 'state_province_id' => array(
3748 'title' => ts('State/Province'),
3750 'country_id' => array(
3751 'title' => ts('Country'),
3753 'county_id' => array(
3754 'title' => ts('County'),
3758 return $addressFields;
3762 * Do AlterDisplay processing on Address Fields
3772 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3773 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3774 $entryFound = FALSE;
3776 if (array_key_exists('civicrm_address_country_id', $row)) {
3777 if ($value = $row['civicrm_address_country_id']) {
3778 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3779 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3780 "reset=1&force=1&{$criteriaQueryParams}&" .
3781 "country_id_op=in&country_id_value={$value}",
3782 $this->_absoluteUrl
, $this->_id
3784 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3785 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3792 if (array_key_exists('civicrm_address_county_id', $row)) {
3793 if ($value = $row['civicrm_address_county_id']) {
3794 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3795 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3796 "reset=1&force=1&{$criteriaQueryParams}&" .
3797 "county_id_op=in&county_id_value={$value}",
3798 $this->_absoluteUrl
, $this->_id
3800 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3801 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3807 // handle state province
3808 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3809 if ($value = $row['civicrm_address_state_province_id']) {
3810 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3812 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3813 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3814 $this->_absoluteUrl
, $this->_id
3816 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3817 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3828 * Adjusts dates passed in to YEAR() for fiscal year.
3830 * @param string $fieldName
3834 public function fiscalYearOffset($fieldName) {
3835 $config = CRM_Core_Config
::singleton();
3836 $fy = $config->fiscalYearStart
;
3837 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
3838 ($fy['d'] == 1 && $fy['M'] == 1)
3840 return "YEAR( $fieldName )";
3842 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
3843 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3847 * Add Address into From Table if required
3849 public function addAddressFromClause() {
3850 // include address field if address column is to be included
3851 if ((isset($this->_addressField
) &&
3852 $this->_addressField
3854 $this->isTableSelected('civicrm_address')
3857 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3858 ON ({$this->_aliases['civicrm_contact']}.id =
3859 {$this->_aliases['civicrm_address']}.contact_id) AND
3860 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3865 * Add Phone into From Table if required
3867 public function addPhoneFromClause() {
3868 // include address field if address column is to be included
3869 if ($this->isTableSelected('civicrm_phone')
3872 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3873 ON ({$this->_aliases['civicrm_contact']}.id =
3874 {$this->_aliases['civicrm_phone']}.contact_id) AND
3875 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3880 * Get phone columns to add to array
3882 * @param array $options
3883 * - prefix Prefix to add to table (in case of more than one instance of the table)
3884 * - prefix_label Label to give columns from this phone table instance
3887 * phone columns definition
3889 public function getPhoneColumns($options = array()) {
3890 $defaultOptions = array(
3892 'prefix_label' => '',
3895 $options = array_merge($defaultOptions, $options);
3898 $options['prefix'] . 'civicrm_phone' => array(
3899 'dao' => 'CRM_Core_DAO_Phone',
3901 $options['prefix'] . 'phone' => array(
3902 'title' => ts($options['prefix_label'] . 'Phone'),
3912 * Get address columns to add to array
3914 * @param array $options
3915 * - prefix Prefix to add to table (in case of more than one instance of the table)
3916 * - prefix_label Label to give columns from this address table instance
3919 * address columns definition
3921 public function getAddressColumns($options = array()) {
3924 'prefix_label' => '',
3928 'defaults' => array(),
3930 return $this->addAddressFields(
3931 $options['group_by'],
3932 $options['order_by'],
3933 $options['filters'],
3934 $options['defaults']
3939 * @param int $groupID
3941 public function add2group($groupID) {
3942 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3943 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3944 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3946 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3947 $dao = CRM_Core_DAO
::executeQuery($sql);
3949 $contact_ids = array();
3950 // Add resulting contacts to group
3951 while ($dao->fetch()) {
3952 if ($dao->addtogroup_contact_id
) {
3953 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3957 if (!empty($contact_ids)) {
3958 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3959 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3962 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3968 * function used for showing charts on print screen
3970 public static function uploadChartImage() {
3971 // upload strictly for '.png' images
3972 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3973 if (preg_match('/\.png$/', $name)) {
3975 // POST data is usually string data, but we are passing a RAW .png
3976 // so PHP is a bit confused and $_POST is empty. But it has saved
3977 // the raw bits into $HTTP_RAW_POST_DATA
3979 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3981 // prepare the directory
3982 $config = CRM_Core_Config
::singleton();
3984 str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3986 if (!file_exists($defaultPath)) {
3987 mkdir($defaultPath, 0777, TRUE);
3990 // full path to the saved image including filename
3991 $destination = $defaultPath . $name;
3994 $jfh = fopen($destination, 'w') or die("can't open file");
3995 fwrite($jfh, $httpRawPostData);
3997 CRM_Utils_System
::civiExit();
4002 * Apply common settings to entityRef fields
4004 * @param array $field
4005 * @param string $table
4007 private function setEntityRefDefaults(&$field, $table) {
4008 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4009 $field['attributes'] +
= array(
4010 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4012 'placeholder' => ts('- select -'),