3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 protected $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * Array of tabs to display on report.
167 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
169 * $this->tabs['OrderBy'] = array(
170 * 'title' => ts('Sorting'),
171 * 'tpl' => 'OrderBy',
172 * 'div_label' => 'order-by',
177 protected $tabs = array();
180 * Should we add paging.
184 protected $addPaging = TRUE;
187 * An attribute for checkbox/radio form field layout
191 protected $_fourColumnAttribute = array(
192 '</td><td width="25%">',
193 '</td><td width="25%">',
194 '</td><td width="25%">',
198 protected $_force = 1;
200 protected $_params = NULL;
201 protected $_formValues = NULL;
202 protected $_instanceValues = NULL;
204 protected $_instanceForm = FALSE;
205 protected $_criteriaForm = FALSE;
207 protected $_instanceButtonName = NULL;
208 protected $_createNewButtonName = NULL;
209 protected $_printButtonName = NULL;
210 protected $_pdfButtonName = NULL;
211 protected $_csvButtonName = NULL;
212 protected $_groupButtonName = NULL;
213 protected $_chartButtonName = NULL;
214 protected $_csvSupported = TRUE;
215 protected $_add2groupSupported = TRUE;
216 protected $_groups = NULL;
217 protected $_grandFlag = FALSE;
218 protected $_rowsFound = NULL;
219 protected $_selectAliases = array();
220 protected $_rollup = NULL;
225 protected $_aliases = array();
241 protected $_limit = NULL;
244 * This can be set to specify a limit to the number of rows
245 * Since it is currently envisaged as part of the api usage it is only being applied
246 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
247 * of the code (see limit() fn.
251 protected $_limitValue = NULL;
254 * This can be set to specify row offset
255 * See notes on _limitValue
258 protected $_offsetValue = NULL;
262 protected $_sections = NULL;
263 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
264 protected $_absoluteUrl = FALSE;
267 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
271 protected $_storeResultSet = FALSE;
274 * When _storeResultSet Flag is set use this var to store result set in form of array
278 protected $_resultSet = array();
281 * To what frequency group-by a date column
285 protected $_groupByDateFreq = array(
287 'YEARWEEK' => 'Week',
288 'QUARTER' => 'Quarter',
293 * Variables to hold the acl inner join and where clause
295 protected $_aclFrom = NULL;
296 protected $_aclWhere = NULL;
299 * Array of DAO tables having columns included in SELECT or ORDER BY clause
303 protected $_selectedTables;
306 * Output mode e.g 'print', 'csv', 'pdf'.
310 protected $_outputMode;
313 * Format of any chart in use.
315 * (it's unclear if this could be merged with outputMode at this stage)
321 public $_having = NULL;
322 public $_select = NULL;
323 public $_selectClauses = array();
324 public $_columnHeaders = array();
325 public $_orderBy = NULL;
326 public $_orderByFields = array();
327 public $_orderByArray = array();
328 public $_groupBy = NULL;
329 public $_whereClauses = array();
330 public $_havingClauses = array();
333 * DashBoardRowCount Dashboard row count
336 public $_dashBoardRowCount;
339 * Is this being called without a form controller (ie. the report is being render outside the normal form
340 * - e.g the api is retrieving the rows
343 public $noController = FALSE;
346 * Variable to hold the currency alias
348 protected $_currencyColumn = NULL;
353 protected $_interval;
358 protected $_sendmail;
371 * @var string Report description.
373 public $_description;
376 * @var bool Is an address field selected.
377 * This was intended to determine if the address table should be joined in
378 * The isTableSelected function is now preferred for this purpose
380 protected $_addressField;
383 * @var bool Is an email field selected.
384 * This was intended to determine if the email table should be joined in
385 * The isTableSelected function is now preferred for this purpose
387 protected $_emailField;
390 * @var bool Is a phone field selected.
391 * This was intended to determine if the phone table should be joined in
392 * The isTableSelected function is now preferred for this purpose
394 protected $_phoneField;
397 * @var bool Create new report instance? (or update existing) on save.
399 protected $_createNew;
402 * When a grand total row has calculated the status we pop it off to here.
404 * This allows us to access it from the stats function and avoid recalculating.
406 protected $rollupRow = array();
409 * SQL being run in this report.
411 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
419 * SQL being run in this report as an array.
421 * The sql in the report is stored in this variable in order to be returned to api & test calls.
430 public function __construct() {
431 parent
::__construct();
433 $this->addClass('crm-report-form');
435 if ($this->_tagFilter
) {
436 $this->buildTagFilter();
438 if ($this->_exposeContactID
) {
439 if (array_key_exists('civicrm_contact', $this->_columns
)) {
440 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
442 'title' => 'Contact ID',
448 if ($this->_groupFilter
) {
449 $this->buildGroupFilter();
452 // Get all custom groups
453 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
455 // Get the custom groupIds for which the user has VIEW permission
456 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
457 // and addCustomDataToColumns() will allow access to all custom groups.
458 $permCustomGroupIds = array();
459 if (!CRM_Core_Permission
::check('access all custom data')) {
460 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
461 // do not allow custom data for reports if user doesn't have
462 // permission to access custom data.
463 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
464 $this->_customGroupExtends
= array();
468 // merge custom data columns to _columns list, if any
469 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
471 // add / modify display columns, filters ..etc
472 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
474 //assign currencyColumn variable to tpl
475 $this->assign('currencyColumn', $this->_currencyColumn
);
479 * Shared pre-process function.
481 * If overriding preProcess function this should still be called.
485 public function preProcessCommon() {
487 = CRM_Utils_Request
::retrieve(
490 CRM_Core_DAO
::$_nullObject
493 $this->_dashBoardRowCount
494 = CRM_Utils_Request
::retrieve(
497 CRM_Core_DAO
::$_nullObject
500 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
502 $this->assign('section', $this->_section
);
503 CRM_Core_Region
::instance('page-header')->add(array(
504 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
506 if (!$this->noController
) {
507 $this->setID($this->get('instanceId'));
510 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
512 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
516 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
517 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
518 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
522 $this->assign('instanceId', $this->_id
);
523 $params = array('id' => $this->_id
);
524 $this->_instanceValues
= array();
525 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
527 $this->_instanceValues
529 if (empty($this->_instanceValues
)) {
530 CRM_Core_Error
::fatal("Report could not be loaded.");
532 $this->_title
= $this->_instanceValues
['title'];
533 if (!empty($this->_instanceValues
['permission']) &&
534 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
535 CRM_Core_Permission
::check('administer Reports')
538 CRM_Utils_System
::permissionDenied();
539 CRM_Utils_System
::civiExit();
542 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
544 $this->_formValues
= unserialize($formValues);
547 $this->_formValues
= NULL;
550 $this->setOutputMode();
552 if ($this->_outputMode
== 'copy') {
553 $this->_createNew
= TRUE;
554 $this->_params
= $this->_formValues
;
555 $this->_params
['view_mode'] = 'criteria';
556 $this->_params
['title'] = ts('(copy)') . $this->getTitle();
557 // Do not pass go. Do not collect another chance to re-run the same query.
558 CRM_Report_Form_Instance
::postProcess($this);
561 // lets always do a force if reset is found in the url.
562 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
563 // in the comment line above these 2.
564 if (!empty($_REQUEST['reset'])
565 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
570 $this->assign('mode', 'instance');
572 elseif (!$this->noController
) {
573 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
574 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
575 if (($instanceCount > 0) && $optionValueID) {
576 $this->assign('instanceUrl',
577 CRM_Utils_System
::url('civicrm/report/list',
578 "reset=1&ovid=$optionValueID"
582 if ($optionValueID) {
583 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
587 $this->assign('mode', 'template');
590 // lets display the Report Settings section
591 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
593 // Do not display Report Settings section if administer Reports permission is absent OR
594 // if report instance is reserved and administer reserved reports absent
595 if (!CRM_Core_Permission
::check('administer Reports') ||
596 ($this->_instanceValues
['is_reserved'] &&
597 !CRM_Core_Permission
::check('administer reserved reports'))
599 $this->_instanceForm
= FALSE;
602 $this->assign('criteriaForm', FALSE);
603 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
604 if (CRM_Core_Permission
::check('administer Reports') ||
605 CRM_Core_Permission
::check('access Report Criteria')
607 if (!$this->_instanceValues
['is_reserved'] ||
608 CRM_Core_Permission
::check('administer reserved reports')
610 $this->assign('criteriaForm', TRUE);
611 $this->_criteriaForm
= TRUE;
615 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
616 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
617 $this->_printButtonName
= $this->getButtonName('submit', 'print');
618 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
619 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
620 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
621 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
627 public function addBreadCrumb() {
631 'title' => ts('Report Templates'),
632 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
636 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
640 * Pre process function.
642 * Called prior to build form.
644 public function preProcess() {
645 $this->preProcessCommon();
648 $this->addBreadCrumb();
651 foreach ($this->_columns
as $tableName => $table) {
653 if (!isset($table['alias'])) {
654 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
658 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
661 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
663 $daoOrBaoName = NULL;
664 // higher preference to bao object
665 if (array_key_exists('bao', $table)) {
666 $daoOrBaoName = $table['bao'];
667 $expFields = $daoOrBaoName::exportableFields();
669 elseif (array_key_exists('dao', $table)) {
670 $daoOrBaoName = $table['dao'];
671 $expFields = $daoOrBaoName::export();
674 $expFields = array();
677 $doNotCopy = array('required');
679 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
680 foreach ($fieldGroups as $fieldGrp) {
681 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
682 foreach ($table[$fieldGrp] as $fieldName => $field) {
683 // $name is the field name used to reference the BAO/DAO export fields array
684 $name = isset($field['name']) ?
$field['name'] : $fieldName;
686 // Sometimes the field name key in the BAO/DAO export fields array is
687 // different from the actual database field name.
688 // Unset $field['name'] so that actual database field name can be obtained
689 // from the BAO/DAO export fields array.
690 unset($field['name']);
692 if (array_key_exists($name, $expFields)) {
693 foreach ($doNotCopy as $dnc) {
694 // unset the values we don't want to be copied.
695 unset($expFields[$name][$dnc]);
698 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
701 foreach ($expFields[$name] as $property => $val) {
702 if (!array_key_exists($property, $field)) {
703 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
710 if (!empty($field['no_repeat'])) {
711 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
713 if (!empty($field['no_display'])) {
714 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
717 // set alias = table-name, unless already set
718 $alias = isset($field['alias']) ?
$field['alias'] : (
719 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
721 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
723 // set name = fieldName, unless already set
724 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
725 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
728 // set dbAlias = alias.name, unless already set
729 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
730 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
732 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
735 // a few auto fills for filters
736 if ($fieldGrp == 'filters') {
737 // fill operator types
738 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
739 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
740 case CRM_Utils_Type
::T_MONEY
:
741 case CRM_Utils_Type
::T_FLOAT
:
742 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
745 case CRM_Utils_Type
::T_INT
:
746 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
749 case CRM_Utils_Type
::T_DATE
:
750 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
753 case CRM_Utils_Type
::T_BOOLEAN
:
754 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
755 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
756 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
767 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
769 // with multiple options operator-type is generally multi-select
770 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
771 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
773 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
784 // copy filters to a separate handy variable
785 if (array_key_exists('filters', $table)) {
786 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
789 if (array_key_exists('group_bys', $table)) {
790 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
793 if (array_key_exists('fields', $table)) {
794 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
799 $this->setDefaultValues(FALSE);
802 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
803 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
804 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
805 CRM_Report_Utils_Get
::processChart($this->_defaults
);
808 $this->_formValues
= $this->_defaults
;
809 $this->postProcess();
814 * Set default values.
816 * @param bool $freeze
820 public function setDefaultValues($freeze = TRUE) {
821 $freezeGroup = array();
823 // FIXME: generalizing form field naming conventions would reduce
824 // Lots of lines below.
825 foreach ($this->_columns
as $tableName => $table) {
826 if (array_key_exists('fields', $table)) {
827 foreach ($table['fields'] as $fieldName => $field) {
828 if (empty($field['no_display'])) {
829 if (isset($field['required'])) {
831 $this->_defaults
['fields'][$fieldName] = 1;
834 // find element object, so that we could use quickform's freeze method
835 // for required elements
836 $obj = $this->getElementFromGroup("fields", $fieldName);
838 $freezeGroup[] = $obj;
842 elseif (isset($field['default'])) {
843 $this->_defaults
['fields'][$fieldName] = $field['default'];
849 if (array_key_exists('group_bys', $table)) {
850 foreach ($table['group_bys'] as $fieldName => $field) {
851 if (isset($field['default'])) {
852 if (!empty($field['frequency'])) {
853 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
855 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
859 if (array_key_exists('filters', $table)) {
860 foreach ($table['filters'] as $fieldName => $field) {
861 if (isset($field['default'])) {
862 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
864 if (is_array($field['default'])) {
865 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
866 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
867 $this->_defaults
["{$fieldName}_relative"] = 0;
870 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
874 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
875 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
876 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
878 $this->_defaults
["{$fieldName}_value"] = $field['default'];
881 //assign default value as "in" for multiselect
882 //operator, To freeze the select element
883 if (CRM_Utils_Array
::value('operatorType', $field) ==
884 CRM_Report_Form
::OP_MULTISELECT
886 $this->_defaults
["{$fieldName}_op"] = 'in';
888 if (CRM_Utils_Array
::value('operatorType', $field) ==
889 CRM_Report_Form
::OP_ENTITYREF
891 $this->_defaults
["{$fieldName}_op"] = 'in';
893 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
894 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
896 $this->_defaults
["{$fieldName}_op"] = 'mhas';
898 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
899 $this->_defaults
["{$fieldName}_op"] = $op;
905 empty($this->_formValues
['order_bys']) &&
906 (array_key_exists('order_bys', $table) &&
907 is_array($table['order_bys']))
909 if (!array_key_exists('order_bys', $this->_defaults
)) {
910 $this->_defaults
['order_bys'] = array();
912 foreach ($table['order_bys'] as $fieldName => $field) {
913 if (!empty($field['default']) ||
!empty($field['default_order']) ||
914 CRM_Utils_Array
::value('default_is_section', $field) ||
915 !empty($field['default_weight'])
918 'column' => $fieldName,
919 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
920 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
923 if (!empty($field['default_weight'])) {
924 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
927 array_unshift($this->_defaults
['order_bys'], $order_by);
933 foreach ($this->_options
as $fieldName => $field) {
934 if (isset($field['default'])) {
935 $this->_defaults
['options'][$fieldName] = $field['default'];
940 if (!empty($this->_submitValues
)) {
941 $this->preProcessOrderBy($this->_submitValues
);
944 $this->preProcessOrderBy($this->_defaults
);
947 // lets finish freezing task here itself
948 if (!empty($freezeGroup)) {
949 foreach ($freezeGroup as $elem) {
954 if ($this->_formValues
) {
955 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
958 if ($this->_instanceValues
) {
959 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
962 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
964 return $this->_defaults
;
968 * Get element from group.
970 * @param string $group
971 * @param string $grpFieldName
975 public function getElementFromGroup($group, $grpFieldName) {
976 $eleObj = $this->getElement($group);
977 foreach ($eleObj->_elements
as $index => $obj) {
978 if ($grpFieldName == $obj->_attributes
['name']) {
986 * Setter for $_params.
988 * @param array $params
990 public function setParams($params) {
991 $this->_params
= $params;
997 * @param int $instanceID
999 public function setID($instanceID) {
1000 $this->_id
= $instanceID;
1004 * Setter for $_force.
1006 * @param bool $isForce
1008 public function setForce($isForce) {
1009 $this->_force
= $isForce;
1013 * Setter for $_limitValue.
1015 * @param int $_limitValue
1017 public function setLimitValue($_limitValue) {
1018 $this->_limitValue
= $_limitValue;
1022 * Setter for $_offsetValue.
1024 * @param int $_offsetValue
1026 public function setOffsetValue($_offsetValue) {
1027 $this->_offsetValue
= $_offsetValue;
1031 * Setter for $addPaging.
1033 * @param bool $value
1035 public function setAddPaging($value) {
1036 $this->addPaging
= $value;
1040 * Getter for $_defaultValues.
1044 public function getDefaultValues() {
1045 return $this->_defaults
;
1049 * Add columns to report.
1051 public function addColumns() {
1054 foreach ($this->_columns
as $tableName => $table) {
1055 if (array_key_exists('fields', $table)) {
1056 foreach ($table['fields'] as $fieldName => $field) {
1058 if (empty($field['no_display'])) {
1059 foreach (array('table', 'field') as $var) {
1060 if (!empty($
{$var}['grouping'])) {
1061 if (!is_array($
{$var}['grouping'])) {
1062 $tableName = $
{$var}['grouping'];
1065 $tableName = array_keys($
{$var}['grouping']);
1066 $tableName = $tableName[0];
1067 $groupTitle = array_values($
{$var}['grouping']);
1068 $groupTitle = $groupTitle[0];
1073 if (!$groupTitle && isset($table['group_title'])) {
1074 $groupTitle = $table['group_title'];
1075 // Having a group_title is secret code for being a custom group
1076 // which cryptically translates to needing an accordion.
1077 // here we make that explicit.
1078 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1081 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1082 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1083 $colGroups[$tableName]['group_title'] = $groupTitle;
1085 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1091 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1092 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1094 if (!empty($colGroups)) {
1095 $this->tabs
['FieldSelection'] = array(
1096 'title' => ts('Columns'),
1097 'tpl' => 'FieldSelection',
1098 'div_label' => 'col-groups',
1101 // Note this assignment is only really required in buildForm. It is being 'over-called'
1102 // to reduce risk of being missed due to overridden functions.
1103 $this->assign('tabs', $this->tabs
);
1106 $this->assign('colGroups', $colGroups);
1110 * Add filters to report.
1112 public function addFilters() {
1113 $filters = $filterGroups = array();
1116 foreach ($this->_filters
as $table => $attributes) {
1117 if (isset($this->_columns
[$table]['group_title'])) {
1118 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1119 // which magically means to 'display in an accordian'
1120 // here we make this explicit.
1121 $filterGroups[$table] = array(
1122 'group_title' => $this->_columns
[$table]['group_title'],
1123 'use_accordian_for_field_selection' => TRUE,
1127 foreach ($attributes as $fieldName => $field) {
1128 // get ready with option value pair
1129 // @ 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
1131 $operations = $this->getOperationPair(
1132 CRM_Utils_Array
::value('operatorType', $field),
1135 $filters[$table][$fieldName] = $field;
1137 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1138 case CRM_Report_Form
::OP_MONTH
:
1139 if (!array_key_exists('options', $field) ||
1140 !is_array($field['options']) ||
empty($field['options'])
1142 // If there's no option list for this filter, define one.
1143 $field['options'] = array(
1145 2 => ts('February'),
1152 9 => ts('September'),
1153 10 => ts('October'),
1154 11 => ts('November'),
1155 12 => ts('December'),
1157 // Add this option list to this column _columns. This is
1158 // required so that filter statistics show properly.
1159 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1161 case CRM_Report_Form
::OP_MULTISELECT
:
1162 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1163 // assume a multi-select field
1164 if (!empty($field['options']) ||
1165 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1167 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1168 if (count($operations) <= 1) {
1171 if ($fieldName == 'state_province_id' ||
1172 $fieldName == 'county_id'
1174 $this->addChainSelect($fieldName . '_value', array(
1181 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1182 'style' => 'min-width:250px',
1183 'class' => 'crm-select2 huge',
1185 'placeholder' => ts('- select -'),
1191 case CRM_Report_Form
::OP_SELECT
:
1192 // assume a select field
1193 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1194 if (!empty($field['options'])) {
1195 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1199 case CRM_Report_Form
::OP_ENTITYREF
:
1200 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1201 $this->setEntityRefDefaults($field, $table);
1202 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1205 case CRM_Report_Form
::OP_DATE
:
1206 // build datetime fields
1207 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1211 case CRM_Report_Form
::OP_DATETIME
:
1212 // build datetime fields
1213 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1217 case CRM_Report_Form
::OP_INT
:
1218 case CRM_Report_Form
::OP_FLOAT
:
1219 // and a min value input box
1220 $this->add('text', "{$fieldName}_min", ts('Min'));
1221 // and a max value input box
1222 $this->add('text', "{$fieldName}_max", ts('Max'));
1224 // default type is string
1225 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1226 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1228 // we need text box for value input
1229 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1234 if (!empty($filters)) {
1235 $this->tabs
['Filters'] = array(
1236 'title' => ts('Filters'),
1238 'div_label' => 'set-filters',
1241 $this->assign('filters', $filters);
1242 $this->assign('filterGroups', $filterGroups);
1246 * Function to assign the tabs to the template in the correct order.
1248 * We want the tabs to wind up in this order (if not overridden).
1256 protected function assignTabs() {
1264 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1265 $order = array_merge($order, $this->tabs
);
1266 $this->assign('tabs', $order);
1270 * The intent is to add a tab for developers to view the sql.
1272 * Currently using dpm.
1274 * @param string $sql
1276 protected function addToDeveloperTab($sql) {
1277 if (!CRM_Core_Permission
::check('view report sql')) {
1280 $this->tabs
['Developer'] = array(
1281 'title' => ts('Developer'),
1282 'tpl' => 'Developer',
1283 'div_label' => 'set-developer',
1286 $this->assignTabs();
1287 $this->sqlArray
[] = $sql;
1288 foreach (array('LEFT JOIN') as $term) {
1289 $sql = str_replace($term, '<br>  ' . $term, $sql);
1291 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1292 $sql = str_replace($term, '<br><br>' . $term, $sql);
1294 $this->sql
.= $sql . "<br>";
1296 $this->assign('sql', $this->sql
);
1300 * Add options defined in $this->_options to the report.
1302 public function addOptions() {
1303 if (!empty($this->_options
)) {
1304 // FIXME: For now lets build all elements as checkboxes.
1305 // Once we clear with the format we can build elements based on type
1307 foreach ($this->_options
as $fieldName => $field) {
1310 if ($field['type'] == 'select') {
1311 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1313 elseif ($field['type'] == 'checkbox') {
1314 $options[$field['title']] = $fieldName;
1315 $this->addCheckBox($fieldName, NULL,
1317 NULL, NULL, NULL, $this->_fourColumnAttribute
1322 if (!empty($this->_options
)) {
1323 $this->tabs
['ReportOptions'] = array(
1324 'title' => ts('Display Options'),
1325 'tpl' => 'ReportOptions',
1326 'div_label' => 'other-options',
1329 $this->assign('otherOptions', $this->_options
);
1333 * Add chart options to the report.
1335 public function addChartOptions() {
1336 if (!empty($this->_charts
)) {
1337 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1338 $this->assign('charts', $this->_charts
);
1339 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1344 * Add group by options to the report.
1346 public function addGroupBys() {
1347 $options = $freqElements = array();
1349 foreach ($this->_columns
as $tableName => $table) {
1350 if (array_key_exists('group_bys', $table)) {
1351 foreach ($table['group_bys'] as $fieldName => $field) {
1352 if (!empty($field)) {
1353 $options[$field['title']] = $fieldName;
1354 if (!empty($field['frequency'])) {
1355 $freqElements[$field['title']] = $fieldName;
1361 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1362 NULL, NULL, NULL, $this->_fourColumnAttribute
1364 $this->assign('groupByElements', $options);
1365 if (!empty($options)) {
1366 $this->tabs
['GroupBy'] = array(
1367 'title' => ts('Grouping'),
1369 'div_label' => 'group-by-elements',
1373 foreach ($freqElements as $name) {
1374 $this->addElement('select', "group_bys_freq[$name]",
1375 ts('Frequency'), $this->_groupByDateFreq
1381 * Add data for order by tab.
1383 public function addOrderBys() {
1385 foreach ($this->_columns
as $tableName => $table) {
1387 // Report developer may define any column to order by; include these as order-by options.
1388 if (array_key_exists('order_bys', $table)) {
1389 foreach ($table['order_bys'] as $fieldName => $field) {
1390 if (!empty($field)) {
1391 $options[$fieldName] = $field['title'];
1396 // Add searchable custom fields as order-by options, if so requested
1397 // (These are already indexed, so allowing to order on them is cheap.)
1399 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1400 array_key_exists('extends', $table) && !empty($table['extends'])
1402 foreach ($table['fields'] as $fieldName => $field) {
1403 if (empty($field['no_display'])) {
1404 $options[$fieldName] = $field['title'];
1412 $this->assign('orderByOptions', $options);
1413 if (!empty($options)) {
1414 $this->tabs
['OrderBy'] = array(
1415 'title' => ts('Sorting'),
1417 'div_label' => 'order-by-elements',
1421 if (!empty($options)) {
1423 '-' => ' - none - ',
1425 for ($i = 1; $i <= 5; $i++
) {
1426 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1427 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1428 'ASC' => 'Ascending',
1429 'DESC' => 'Descending',
1431 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1432 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1438 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1440 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1441 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1444 public function buildInstanceAndButtons() {
1445 CRM_Report_Form_Instance
::buildForm($this);
1447 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1449 $this->addElement('submit', $this->_instanceButtonName
, $label);
1450 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1451 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1454 $this->addElement('submit', $this->_createNewButtonName
,
1455 ts('Save a Copy') . '...');
1457 $this->assign('instanceForm', $this->_instanceForm
);
1459 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1460 $this->addElement('submit', $this->_printButtonName
, $label);
1462 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1463 $this->addElement('submit', $this->_pdfButtonName
, $label);
1465 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1467 if ($this->_csvSupported
) {
1468 $this->addElement('submit', $this->_csvButtonName
, $label);
1471 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1472 $permission = CRM_Core_Permission
::getPermission();
1473 if ($permission == CRM_Core_Permission
::EDIT
&&
1474 $this->_add2groupSupported
1476 $this->addElement('select', 'groups', ts('Group'),
1477 array('' => ts('Add Contacts to Group')) +
1478 CRM_Core_PseudoConstant
::nestedGroup(),
1479 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1481 $this->assign('group', TRUE);
1484 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1486 $this->addChartOptions();
1487 $this->addButtons(array(
1490 'name' => ts('Preview Report'),
1491 'isDefault' => TRUE,
1498 * Main build form function.
1500 public function buildQuickForm() {
1501 $this->addColumns();
1503 $this->addFilters();
1505 $this->addOptions();
1507 $this->addGroupBys();
1509 $this->addOrderBys();
1511 $this->buildInstanceAndButtons();
1513 // Add form rule for report.
1514 if (is_callable(array(
1518 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1520 $this->assignTabs();
1524 * A form rule function for custom data.
1526 * The rule ensures that fields selected in group_by if any) should only be the ones
1527 * present in display/select fields criteria;
1528 * note: works if and only if any custom field selected in group_by.
1530 * @param array $fields
1531 * @param array $ignoreFields
1535 public function customDataFormRule($fields, $ignoreFields = array()) {
1537 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1538 !empty($fields['group_bys'])
1540 foreach ($this->_columns
as $tableName => $table) {
1541 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1542 substr($tableName, 0, 12) == 'custom_value') &&
1543 !empty($this->_columns
[$tableName]['fields'])
1545 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1546 if (array_key_exists($fieldName, $fields['group_bys']) &&
1547 !array_key_exists($fieldName, $fields['fields'])
1549 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1551 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1552 foreach ($fields['fields'] as $fld => $val) {
1553 if (!array_key_exists($fld, $fields['group_bys']) &&
1554 !in_array($fld, $ignoreFields)
1556 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1568 * Get operators to display on form.
1570 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1572 * @param string $type
1573 * @param string $fieldName
1577 public function getOperationPair($type = "string", $fieldName = NULL) {
1578 // FIXME: At some point we should move these key-val pairs
1579 // to option_group and option_value table.
1581 case CRM_Report_Form
::OP_INT
:
1582 case CRM_Report_Form
::OP_FLOAT
:
1585 'lte' => ts('Is less than or equal to'),
1586 'gte' => ts('Is greater than or equal to'),
1587 'bw' => ts('Is between'),
1588 'eq' => ts('Is equal to'),
1589 'lt' => ts('Is less than'),
1590 'gt' => ts('Is greater than'),
1591 'neq' => ts('Is not equal to'),
1592 'nbw' => ts('Is not between'),
1593 'nll' => ts('Is empty (Null)'),
1594 'nnll' => ts('Is not empty (Null)'),
1598 case CRM_Report_Form
::OP_SELECT
:
1600 'eq' => ts('Is equal to'),
1604 case CRM_Report_Form
::OP_MONTH
:
1605 case CRM_Report_Form
::OP_MULTISELECT
:
1606 case CRM_Report_Form
::OP_ENTITYREF
:
1609 'in' => ts('Is one of'),
1610 'notin' => ts('Is not one of'),
1614 case CRM_Report_Form
::OP_DATE
:
1617 'nll' => ts('Is empty (Null)'),
1618 'nnll' => ts('Is not empty (Null)'),
1622 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1623 // use this operator for the values, concatenated with separator. For e.g if
1624 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1626 'mhas' => ts('Is one of'),
1627 'mnot' => ts('Is not one of'),
1634 'has' => ts('Contains'),
1635 'sw' => ts('Starts with'),
1636 'ew' => ts('Ends with'),
1637 'nhas' => ts('Does not contain'),
1638 'eq' => ts('Is equal to'),
1639 'neq' => ts('Is not equal to'),
1640 'nll' => ts('Is empty (Null)'),
1641 'nnll' => ts('Is not empty (Null)'),
1648 * Build the tag filter field to display on the filters tab.
1650 public function buildTagFilter() {
1651 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1652 if (!empty($contactTags)) {
1653 $this->_columns
['civicrm_tag'] = array(
1654 'dao' => 'CRM_Core_DAO_Tag',
1658 'title' => ts('Tag'),
1660 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1661 'options' => $contactTags,
1669 * Adds group filters to _columns (called from _Construct).
1671 public function buildGroupFilter() {
1672 $this->_columns
['civicrm_group']['filters'] = array(
1674 'name' => 'group_id',
1675 'title' => ts('Group'),
1676 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1678 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1681 if (empty($this->_columns
['civicrm_group']['dao'])) {
1682 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1684 if (empty($this->_columns
['civicrm_group']['alias'])) {
1685 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1690 * Get SQL operator from form text version.
1692 * @param string $operator
1696 public function getSQLOperator($operator = "like") {
1697 switch ($operator) {
1730 return 'IS NOT NULL';
1739 * Generate where clause.
1741 * This can be overridden in reports for special treatment of a field
1743 * @param array $field Field specifications
1744 * @param string $op Query operator (not an exact match to sql)
1745 * @param mixed $value
1749 * @return null|string
1751 public function whereClause(&$field, $op, $value, $min, $max) {
1753 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1759 if (($min !== NULL && strlen($min) > 0) ||
1760 ($max !== NULL && strlen($max) > 0)
1762 $min = CRM_Utils_Type
::escape($min, $type);
1763 $max = CRM_Utils_Type
::escape($max, $type);
1767 $clauses[] = "( {$field['dbAlias']} >= $min )";
1770 $clauses[] = "( {$field['dbAlias']} < $min )";
1775 $clauses[] = "( {$field['dbAlias']} <= $max )";
1778 $clauses[] = "( {$field['dbAlias']} > $max )";
1782 if (!empty($clauses)) {
1784 $clause = implode(' AND ', $clauses);
1787 $clause = implode(' OR ', $clauses);
1795 if ($value !== NULL && strlen($value) > 0) {
1796 $value = CRM_Utils_Type
::escape($value, $type);
1797 if (strpos($value, '%') === FALSE) {
1798 $value = "'%{$value}%'";
1801 $value = "'{$value}'";
1803 $sqlOP = $this->getSQLOperator($op);
1804 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1810 if (is_string($value) && strlen($value)) {
1811 $value = explode(',', $value);
1813 if ($value !== NULL && is_array($value) && count($value) > 0) {
1814 $sqlOP = $this->getSQLOperator($op);
1815 if (CRM_Utils_Array
::value('type', $field) ==
1816 CRM_Utils_Type
::T_STRING
1818 //cycle through selections and escape values
1819 foreach ($value as $key => $selection) {
1820 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1823 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1827 // for numerical values
1828 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1831 if ($op == 'notin') {
1832 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1835 $clause = "( " . $clause . " )";
1842 // multiple has or multiple not
1843 if ($value !== NULL && count($value) > 0) {
1844 $value = CRM_Utils_Type
::escapeAll($value, $type);
1845 $operator = $op == 'mnot' ?
'NOT' : '';
1846 $regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', (array) $value) . "[[:cntrl:]]*";
1847 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1853 if ($value !== NULL && strlen($value) > 0) {
1854 $value = CRM_Utils_Type
::escape($value, $type);
1855 if (strpos($value, '%') === FALSE) {
1857 $value = "'{$value}%'";
1860 $value = "'%{$value}'";
1864 $value = "'{$value}'";
1866 $sqlOP = $this->getSQLOperator($op);
1867 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1873 $sqlOP = $this->getSQLOperator($op);
1874 $clause = "( {$field['dbAlias']} $sqlOP )";
1878 if ($value !== NULL && strlen($value) > 0) {
1879 if (isset($field['clause'])) {
1880 // FIXME: we not doing escape here. Better solution is to use two
1881 // different types - data-type and filter-type
1882 $clause = $field['clause'];
1885 $value = CRM_Utils_Type
::escape($value, $type);
1886 $sqlOP = $this->getSQLOperator($op);
1887 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1888 $value = "'{$value}'";
1890 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1896 if (!empty($field['group']) && $clause) {
1897 $clause = $this->whereGroupClause($field, $value, $op);
1899 elseif (!empty($field['tag']) && $clause) {
1900 // not using left join in query because if any contact
1901 // belongs to more than one tag, results duplicate
1903 $clause = $this->whereTagClause($field, $value, $op);
1905 elseif (!empty($field['membership_org']) && $clause) {
1906 $clause = $this->whereMembershipOrgClause($value, $op);
1908 elseif (!empty($field['membership_type']) && $clause) {
1909 $clause = $this->whereMembershipTypeClause($value, $op);
1915 * Get SQL where clause for a date field.
1917 * @param string $fieldName
1918 * @param string $relative
1919 * @param string $from
1921 * @param string $type
1922 * @param string $fromTime
1923 * @param string $toTime
1925 * @return null|string
1927 public function dateClause(
1929 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1932 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1933 $sqlOP = $this->getSQLOperator($relative);
1934 return "( {$fieldName} {$sqlOP} )";
1937 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1940 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1941 $clauses[] = "( {$fieldName} >= $from )";
1945 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1946 $clauses[] = "( {$fieldName} <= {$to} )";
1949 if (!empty($clauses)) {
1950 return implode(' AND ', $clauses);
1957 * Possibly unused function.
1959 * @todo - could not find any instances where this is called
1961 * @param bool $relative
1962 * @param string $from
1965 * @return string|NULL
1967 public function dateDisplay($relative, $from, $to) {
1968 list($from, $to) = $this->getFromTo($relative, $from, $to);
1971 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1974 $clauses[] = 'Past';
1978 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1981 $clauses[] = 'Today';
1984 if (!empty($clauses)) {
1985 return implode(' - ', $clauses);
1992 * Get values for from and to for date ranges.
1994 * @param bool $relative
1995 * @param string $from
1997 * @param string $fromTime
1998 * @param string $toTime
2002 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2003 if (empty($toTime)) {
2006 //FIX ME not working for relative
2008 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2009 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2010 $from = substr($dateRange['from'], 0, 8);
2011 //Take only Date Part, Sometime Time part is also present in 'to'
2012 $to = substr($dateRange['to'], 0, 8);
2014 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2015 $to = CRM_Utils_Date
::processDate($to, $toTime);
2016 return array($from, $to);
2020 * Alter display of rows.
2022 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2023 * such as rendering contacts as links.
2025 * @param array $rows
2026 * Rows generated by SQL, with an array for each row.
2028 public function alterDisplay(&$rows) {
2032 * Alter the way in which custom data fields are displayed.
2034 * @param array $rows
2036 public function alterCustomDataDisplay(&$rows) {
2037 // custom code to alter rows having custom values
2038 if (empty($this->_customGroupExtends
)) {
2042 $customFieldIds = array();
2043 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2044 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2045 $customFieldIds[$fieldAlias] = $fieldId;
2048 if (empty($customFieldIds)) {
2052 // skip for type date and ContactReference since date format is already handled
2054 SELECT cg.table_name, cf.id
2055 FROM civicrm_custom_field cf
2056 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2057 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2058 cg.is_active = 1 AND
2059 cf.is_active = 1 AND
2060 cf.is_searchable = 1 AND
2061 cf.data_type NOT IN ('ContactReference', 'Date') AND
2062 cf.id IN (" . implode(",", $customFieldIds) . ")";
2064 $dao = CRM_Core_DAO
::executeQuery($query);
2065 while ($dao->fetch()) {
2066 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2070 $entryFound = FALSE;
2071 foreach ($rows as $rowNum => $row) {
2072 foreach ($row as $tableCol => $val) {
2073 if (array_key_exists($tableCol, $customFields)) {
2074 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2079 // skip looking further in rows, if first row itself doesn't
2080 // have the column we need
2088 * Remove duplicate rows.
2090 * @param array $rows
2092 public function removeDuplicates(&$rows) {
2093 if (empty($this->_noRepeats
)) {
2096 $checkList = array();
2098 foreach ($rows as $key => $list) {
2099 foreach ($list as $colName => $colVal) {
2100 if (array_key_exists($colName, $checkList) &&
2101 $checkList[$colName] == $colVal
2103 $rows[$key][$colName] = "";
2105 if (in_array($colName, $this->_noRepeats
)) {
2106 $checkList[$colName] = $colVal;
2113 * Fix subtotal display.
2116 * @param array $fields
2117 * @param bool $subtotal
2119 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2120 foreach ($row as $colName => $colVal) {
2121 if (in_array($colName, $fields)) {
2123 elseif (isset($this->_columnHeaders
[$colName])) {
2125 $row[$colName] = "Subtotal";
2129 unset($row[$colName]);
2136 * Calculate grant total.
2138 * @param array $rows
2142 public function grandTotal(&$rows) {
2143 if (!$this->_rollup ||
($this->_rollup
== '' ||
count($rows) == 1) ||
2144 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2149 $this->rollupRow
= array_pop($rows);
2151 foreach ($this->_columnHeaders
as $fld => $val) {
2152 if (!in_array($fld, $this->_statFields
)) {
2153 if (!$this->_grandFlag
) {
2154 $this->rollupRow
[$fld] = ts('Grand Total');
2155 $this->_grandFlag
= TRUE;
2158 $this->rollupRow
[$fld] = "";
2163 $this->assign('grandStat', $this->rollupRow
);
2168 * Format display output.
2170 * @param array $rows
2171 * @param bool $pager
2173 public function formatDisplay(&$rows, $pager = TRUE) {
2174 // set pager based on if any limit was applied in the query.
2179 // allow building charts if any
2180 if (!empty($this->_params
['charts']) && !empty($rows)) {
2181 $this->buildChart($rows);
2182 $this->assign('chartEnabled', TRUE);
2183 $this->_chartId
= "{$this->_params['charts']}_" .
2184 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2186 $this->assign('chartId', $this->_chartId
);
2189 // unset columns not to be displayed.
2190 foreach ($this->_columnHeaders
as $key => $value) {
2191 if (!empty($value['no_display'])) {
2192 unset($this->_columnHeaders
[$key]);
2196 // unset columns not to be displayed.
2197 if (!empty($rows)) {
2198 foreach ($this->_noDisplay
as $noDisplayField) {
2199 foreach ($rows as $rowNum => $row) {
2200 unset($this->_columnHeaders
[$noDisplayField]);
2205 // build array of section totals
2206 $this->sectionTotals();
2208 // process grand-total row
2209 $this->grandTotal($rows);
2211 // use this method for formatting rows for display purpose.
2212 $this->alterDisplay($rows);
2213 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2215 // use this method for formatting custom rows for display purpose.
2216 $this->alterCustomDataDisplay($rows);
2222 * @param array $rows
2224 public function buildChart(&$rows) {
2225 // override this method for building charts.
2228 // select() method below has been added recently (v3.3), and many of the report templates might
2229 // still be having their own select() method. We should fix them as and when encountered and move
2230 // towards generalizing the select() method below.
2233 * Generate the SELECT clause and set class variable $_select.
2235 public function select() {
2236 $select = $this->_selectAliases
= array();
2238 foreach ($this->_columns
as $tableName => $table) {
2239 if (array_key_exists('fields', $table)) {
2240 foreach ($table['fields'] as $fieldName => $field) {
2241 if ($tableName == 'civicrm_address') {
2242 $this->_addressField
= TRUE;
2244 if ($tableName == 'civicrm_email') {
2245 $this->_emailField
= TRUE;
2247 if ($tableName == 'civicrm_phone') {
2248 $this->_phoneField
= TRUE;
2251 if (!empty($field['required']) ||
2252 !empty($this->_params
['fields'][$fieldName])
2255 // 1. In many cases we want select clause to be built in slightly different way
2256 // for a particular field of a particular type.
2257 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2259 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2260 if ($selectClause) {
2261 $select[] = $selectClause;
2265 // include statistics columns only if set
2266 if (!empty($field['statistics'])) {
2267 foreach ($field['statistics'] as $stat => $label) {
2268 $alias = "{$tableName}_{$fieldName}_{$stat}";
2269 switch (strtolower($stat)) {
2272 $select[] = "$stat({$field['dbAlias']}) as $alias";
2273 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2274 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2275 $this->_statFields
[$label] = $alias;
2276 $this->_selectAliases
[] = $alias;
2280 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2281 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2282 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2283 $this->_statFields
[$label] = $alias;
2284 $this->_selectAliases
[] = $alias;
2287 case 'count_distinct':
2288 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2289 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2290 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2291 $this->_statFields
[$label] = $alias;
2292 $this->_selectAliases
[] = $alias;
2296 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2297 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2298 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2299 $this->_statFields
[$label] = $alias;
2300 $this->_selectAliases
[] = $alias;
2306 $alias = "{$tableName}_{$fieldName}";
2307 $select[] = "{$field['dbAlias']} as $alias";
2308 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2309 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2310 $this->_selectAliases
[] = $alias;
2316 // select for group bys
2317 if (array_key_exists('group_bys', $table)) {
2318 foreach ($table['group_bys'] as $fieldName => $field) {
2320 if ($tableName == 'civicrm_address') {
2321 $this->_addressField
= TRUE;
2323 if ($tableName == 'civicrm_email') {
2324 $this->_emailField
= TRUE;
2326 if ($tableName == 'civicrm_phone') {
2327 $this->_phoneField
= TRUE;
2329 // 1. In many cases we want select clause to be built in slightly different way
2330 // for a particular field of a particular type.
2331 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2333 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2334 if ($selectClause) {
2335 $select[] = $selectClause;
2339 if (!empty($this->_params
['group_bys']) &&
2340 !empty($this->_params
['group_bys'][$fieldName]) &&
2341 !empty($this->_params
['group_bys_freq'])
2343 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2345 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2346 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2347 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2348 $field['title'] = 'Week';
2352 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2353 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2354 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2355 $field['title'] = 'Year';
2359 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2360 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2361 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2362 $field['title'] = 'Month';
2366 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2367 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2368 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2369 $field['title'] = 'Quarter';
2372 // for graphs and charts -
2373 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2374 $this->_interval
= $field['title'];
2375 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2376 = $field['title'] . ' Beginning';
2377 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2378 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2380 // just to make sure these values are transferred to rows.
2381 // since we 'll need them for calculation purpose,
2382 // e.g making subtotals look nicer or graphs
2383 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2384 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2391 $this->_selectClauses
= $select;
2392 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2396 * Build select clause for a single field.
2398 * @param string $tableName
2399 * @param string $tableKey
2400 * @param string $fieldName
2401 * @param string $field
2405 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2410 * Build where clause.
2412 public function where() {
2413 $this->storeWhereHavingClauseArray();
2415 if (empty($this->_whereClauses
)) {
2416 $this->_where
= "WHERE ( 1 ) ";
2417 $this->_having
= "";
2420 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2423 if ($this->_aclWhere
) {
2424 $this->_where
.= " AND {$this->_aclWhere} ";
2427 if (!empty($this->_havingClauses
)) {
2428 // use this clause to construct group by clause.
2429 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2434 * Store Where clauses into an array.
2436 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2437 * temp table that may not be part of the final where clause or added
2438 * in other functions
2440 public function storeWhereHavingClauseArray() {
2441 foreach ($this->_columns
as $tableName => $table) {
2442 if (array_key_exists('filters', $table)) {
2443 foreach ($table['filters'] as $fieldName => $field) {
2444 // respect pseudofield to filter spec so fields can be marked as
2445 // not to be handled here
2446 if (!empty($field['pseudofield'])) {
2450 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2451 if (CRM_Utils_Array
::value('operatorType', $field) ==
2452 CRM_Report_Form
::OP_MONTH
2454 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2455 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2456 if (is_array($value) && !empty($value)) {
2458 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2463 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2464 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2465 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2466 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2467 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2468 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2472 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2474 $clause = $this->whereClause($field,
2476 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2477 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2478 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2483 if (!empty($clause)) {
2484 if (!empty($field['having'])) {
2485 $this->_havingClauses
[] = $clause;
2488 $this->_whereClauses
[] = $clause;
2500 public function processReportMode() {
2501 $this->setOutputMode();
2504 = CRM_Utils_Request
::retrieve(
2507 CRM_Core_DAO
::$_nullObject
2510 $this->_absoluteUrl
= FALSE;
2512 $this->assign('printOnly', FALSE);
2514 if ($this->_outputMode
== 'print' ||
2515 ($this->_sendmail
&& !$this->_outputMode
)
2517 $this->assign('printOnly', TRUE);
2519 $this->addPaging
= FALSE;
2520 $this->assign('outputMode', 'print');
2521 $this->_outputMode
= 'print';
2522 if ($this->_sendmail
) {
2523 $this->_absoluteUrl
= TRUE;
2526 elseif ($this->_outputMode
== 'pdf') {
2528 $this->addPaging
= FALSE;
2529 $this->_absoluteUrl
= TRUE;
2531 elseif ($this->_outputMode
== 'csv') {
2533 $this->_absoluteUrl
= TRUE;
2534 $this->addPaging
= FALSE;
2536 elseif ($this->_outputMode
== 'group') {
2537 $this->assign('outputMode', 'group');
2539 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2540 $this->assign('outputMode', 'create_report');
2542 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2543 $this->_createNew
= TRUE;
2546 $this->assign('outputMode', $this->_outputMode
);
2547 $this->assign('printOnly', $printOnly);
2548 // Get today's date to include in printed reports
2550 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2551 $this->assign('reportDate', $reportDate);
2556 * Post Processing function for Form.
2558 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2559 * This function is not accessed when the api calls the report.
2561 public function beginPostProcess() {
2562 $this->setParams($this->controller
->exportValues($this->_name
));
2563 if (empty($this->_params
) &&
2566 $this->setParams($this->_formValues
);
2569 // hack to fix params when submitted from dashboard, CRM-8532
2570 // fields array is missing because form building etc is skipped
2571 // in dashboard mode for report
2572 //@todo - this could be done in the dashboard no we have a setter
2573 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2574 $this->setParams($this->_formValues
);
2577 $this->_formValues
= $this->_params
;
2578 if (CRM_Core_Permission
::check('administer Reports') &&
2579 isset($this->_id
) &&
2580 ($this->_instanceButtonName
==
2581 $this->controller
->getButtonName() . '_save' ||
2582 $this->_chartButtonName
== $this->controller
->getButtonName()
2585 $this->assign('updateReportButton', TRUE);
2588 $this->processReportMode();
2590 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2591 $this->_createNew
= ($this->_outputMode
== 'copy');
2592 // Do not pass go. Do not collect another chance to re-run the same query.
2593 // This will be called from the button - there is an earlier response to the url
2594 // perhaps they can still be consolidated more.
2595 CRM_Report_Form_Instance
::postProcess($this);
2597 $this->beginPostProcessCommon();
2601 * BeginPostProcess function run in both report mode and non-report mode (api).
2603 public function beginPostProcessCommon() {}
2606 * Build the report query.
2608 * @param bool $applyLimit
2612 public function buildQuery($applyLimit = TRUE) {
2615 $this->customDataFrom();
2620 // order_by columns not selected for display need to be included in SELECT
2621 $unselectedSectionColumns = $this->unselectedSectionColumns();
2622 foreach ($unselectedSectionColumns as $alias => $section) {
2623 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2626 if ($applyLimit && empty($this->_params
['charts'])) {
2629 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2631 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2632 $this->addToDeveloperTab($sql);
2637 * Build group by clause.
2639 public function groupBy() {
2640 $groupBys = array();
2641 if (!empty($this->_params
['group_bys']) &&
2642 is_array($this->_params
['group_bys'])
2644 foreach ($this->_columns
as $tableName => $table) {
2645 if (array_key_exists('group_bys', $table)) {
2646 foreach ($table['group_bys'] as $fieldName => $field) {
2647 if (!empty($this->_params
['group_bys'][$fieldName])) {
2648 $groupBys[] = $field['dbAlias'];
2655 if (!empty($groupBys)) {
2656 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2661 * Build order by clause.
2663 public function orderBy() {
2664 $this->_orderBy
= "";
2665 $this->_sections
= array();
2666 $this->storeOrderByArray();
2667 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2668 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2670 $this->assign('sections', $this->_sections
);
2674 * Extract order by fields and store as an array.
2676 * In some cases other functions want to know which fields are selected for ordering by
2677 * Separating this into a separate function allows it to be called separately from constructing
2678 * the order by clause
2680 public function storeOrderByArray() {
2681 $orderBys = array();
2683 if (!empty($this->_params
['order_bys']) &&
2684 is_array($this->_params
['order_bys']) &&
2685 !empty($this->_params
['order_bys'])
2688 // Process order_bys in user-specified order
2689 foreach ($this->_params
['order_bys'] as $orderBy) {
2690 $orderByField = array();
2691 foreach ($this->_columns
as $tableName => $table) {
2692 if (array_key_exists('order_bys', $table)) {
2693 // For DAO columns defined in $this->_columns
2694 $fields = $table['order_bys'];
2696 elseif (array_key_exists('extends', $table)) {
2697 // For custom fields referenced in $this->_customGroupExtends
2698 $fields = CRM_Utils_Array
::value('fields', $table, array());
2703 if (!empty($fields) && is_array($fields)) {
2704 foreach ($fields as $fieldName => $field) {
2705 if ($fieldName == $orderBy['column']) {
2706 $orderByField = array_merge($field, $orderBy);
2707 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2714 if (!empty($orderByField)) {
2715 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2716 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2718 // Record any section headers for assignment to the template
2719 if (!empty($orderBy['section'])) {
2720 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2721 $this->_sections
[$orderByField['tplField']] = $orderByField;
2727 $this->_orderByArray
= $orderBys;
2729 $this->assign('sections', $this->_sections
);
2733 * Determine unselected columns.
2737 public function unselectedSectionColumns() {
2738 if (is_array($this->_sections
)) {
2739 return array_diff_key($this->_sections
, $this->getSelectColumns());
2747 * Build output rows.
2749 * @param string $sql
2750 * @param array $rows
2752 public function buildRows($sql, &$rows) {
2753 $dao = CRM_Core_DAO
::executeQuery($sql);
2754 if (!is_array($rows)) {
2758 // use this method to modify $this->_columnHeaders
2759 $this->modifyColumnHeaders();
2761 $unselectedSectionColumns = $this->unselectedSectionColumns();
2763 while ($dao->fetch()) {
2765 foreach ($this->_columnHeaders
as $key => $value) {
2766 if (property_exists($dao, $key)) {
2767 $row[$key] = $dao->$key;
2771 // section headers not selected for display need to be added to row
2772 foreach ($unselectedSectionColumns as $key => $values) {
2773 if (property_exists($dao, $key)) {
2774 $row[$key] = $dao->$key;
2783 * Calculate section totals.
2785 * When "order by" fields are marked as sections, this assigns to the template
2786 * an array of total counts for each section. This data is used by the Smarty
2787 * plugin {sectionTotal}.
2789 public function sectionTotals() {
2791 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2792 if (empty($this->_selectAliases
)) {
2796 if (!empty($this->_sections
)) {
2797 // build the query with no LIMIT clause
2798 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2799 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2801 // pull section aliases out of $this->_sections
2802 $sectionAliases = array_keys($this->_sections
);
2805 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2806 $ifnulls[] = "ifnull($alias, '') as $alias";
2809 // Group (un-limited) report by all aliases and get counts. This might
2810 // be done more efficiently when the contents of $sql are known, ie. by
2811 // overriding this method in the report class.
2813 $query = "select " . implode(", ", $ifnulls) .
2814 ", count(*) as ct from ($sql) as subquery group by " .
2815 implode(", ", $sectionAliases);
2817 // initialize array of total counts
2819 $dao = CRM_Core_DAO
::executeQuery($query);
2820 while ($dao->fetch()) {
2822 // let $this->_alterDisplay translate any integer ids to human-readable values.
2823 $rows[0] = $dao->toArray();
2824 $this->alterDisplay($rows);
2827 // add totals for all permutations of section values
2830 $aliasCount = count($sectionAliases);
2831 foreach ($sectionAliases as $alias) {
2832 $values[] = $row[$alias];
2833 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2834 if ($i == $aliasCount) {
2835 // the last alias is the lowest-level section header; use count as-is
2836 $totals[$key] = $dao->ct
;
2839 // other aliases are higher level; roll count into their total
2840 $totals[$key] +
= $dao->ct
;
2844 $this->assign('sectionTotals', $totals);
2849 * Modify column headers.
2851 public function modifyColumnHeaders() {
2852 // use this method to modify $this->_columnHeaders
2856 * Assign rows to the template.
2858 * @param array $rows
2860 public function doTemplateAssignment(&$rows) {
2861 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2862 $this->assign_by_ref('rows', $rows);
2863 $this->assign('statistics', $this->statistics($rows));
2867 * Build report statistics.
2869 * Override this method to build your own statistics.
2871 * @param array $rows
2875 public function statistics(&$rows) {
2876 $statistics = array();
2878 $count = count($rows);
2879 // Why do we increment the count for rollup seems to artificially inflate the count.
2880 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2884 $this->countStat($statistics, $count);
2886 $this->groupByStat($statistics);
2888 $this->filterStat($statistics);
2894 * Add count statistics.
2896 * @param array $statistics
2899 public function countStat(&$statistics, $count) {
2900 $statistics['counts']['rowCount'] = array(
2901 'title' => ts('Row(s) Listed'),
2905 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2906 $statistics['counts']['rowsFound'] = array(
2907 'title' => ts('Total Row(s)'),
2908 'value' => $this->_rowsFound
,
2914 * Add group by statistics.
2916 * @param array $statistics
2918 public function groupByStat(&$statistics) {
2919 if (!empty($this->_params
['group_bys']) &&
2920 is_array($this->_params
['group_bys']) &&
2921 !empty($this->_params
['group_bys'])
2923 foreach ($this->_columns
as $tableName => $table) {
2924 if (array_key_exists('group_bys', $table)) {
2925 foreach ($table['group_bys'] as $fieldName => $field) {
2926 if (!empty($this->_params
['group_bys'][$fieldName])) {
2927 $combinations[] = $field['title'];
2932 $statistics['groups'][] = array(
2933 'title' => ts('Grouping(s)'),
2934 'value' => implode(' & ', $combinations),
2940 * Filter statistics.
2942 * @param array $statistics
2944 public function filterStat(&$statistics) {
2945 foreach ($this->_columns
as $tableName => $table) {
2946 if (array_key_exists('filters', $table)) {
2947 foreach ($table['filters'] as $fieldName => $field) {
2948 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2949 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2950 CRM_Utils_Array
::value('operatorType', $field) !=
2951 CRM_Report_Form
::OP_MONTH
2955 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2956 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2957 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2958 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2959 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2961 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2962 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2964 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2965 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2968 $statistics['filters'][] = array(
2969 'title' => $field['title'],
2970 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2973 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2974 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2976 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2977 $statistics['filters'][] = array(
2978 'title' => $field['title'],
2979 'value' => $pair[$rel],
2984 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2987 $pair = $this->getOperationPair(
2988 CRM_Utils_Array
::value('operatorType', $field),
2991 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2992 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2993 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2994 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
2995 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2997 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
2998 $this->setEntityRefDefaults($field, $tableName);
2999 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3000 array('id' => $val) +
3001 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3003 foreach ($result['values'] as $v) {
3004 $values[] = $v['label'];
3006 $value = "{$pair[$op]} " . implode(', ', $values);
3008 elseif ($op == 'nll' ||
$op == 'nnll') {
3009 $value = $pair[$op];
3011 elseif (is_array($val) && (!empty($val))) {
3012 $options = CRM_Utils_Array
::value('options', $field, array());
3013 foreach ($val as $key => $valIds) {
3014 if (isset($options[$valIds])) {
3015 $val[$key] = $options[$valIds];
3018 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3019 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3020 $val = implode(', ', $val);
3021 $value = "{$pair[$op]} " . $val;
3023 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3024 isset($field['options']) &&
3025 is_array($field['options']) && !empty($field['options'])
3027 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3028 CRM_Utils_Array
::value($val, $field['options'], $val);
3031 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3035 $statistics['filters'][] = array(
3036 'title' => CRM_Utils_Array
::value('title', $field),
3047 * End post processing.
3049 * @param array|null $rows
3051 public function endPostProcess(&$rows = NULL) {
3052 if ($this->_storeResultSet
) {
3053 $this->_resultSet
= $rows;
3056 if ($this->_outputMode
== 'print' ||
3057 $this->_outputMode
== 'pdf' ||
3061 $content = $this->compileContent();
3062 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3066 if ($this->_sendmail
) {
3067 $config = CRM_Core_Config
::singleton();
3068 $attachments = array();
3070 if ($this->_outputMode
== 'csv') {
3072 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3073 ": {$url}</p>" . '<p>' .
3074 ts('The report is attached as a CSV file.') . '</p>' .
3075 $this->_formValues
['report_footer'];
3077 $csvFullFilename = $config->templateCompileDir
.
3078 CRM_Utils_File
::makeFileName('CiviReport.csv');
3079 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3080 file_put_contents($csvFullFilename, $csvContent);
3081 $attachments[] = array(
3082 'fullPath' => $csvFullFilename,
3083 'mime_type' => 'text/csv',
3084 'cleanName' => 'CiviReport.csv',
3087 if ($this->_outputMode
== 'pdf') {
3088 // generate PDF content
3089 $pdfFullFilename = $config->templateCompileDir
.
3090 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3091 file_put_contents($pdfFullFilename,
3092 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3093 TRUE, array('orientation' => 'landscape')
3096 // generate Email Content
3098 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3099 ": {$url}</p>" . '<p>' .
3100 ts('The report is attached as a PDF file.') . '</p>' .
3101 $this->_formValues
['report_footer'];
3103 $attachments[] = array(
3104 'fullPath' => $pdfFullFilename,
3105 'mime_type' => 'application/pdf',
3106 'cleanName' => 'CiviReport.pdf',
3110 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3111 $this->_outputMode
, $attachments
3114 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3117 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3121 elseif ($this->_outputMode
== 'print') {
3125 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3126 $config = CRM_Core_Config
::singleton();
3127 //get chart image name
3128 $chartImg = $this->_chartId
. '.png';
3129 //get image url path
3131 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3133 $uploadUrl .= $chartImg;
3134 //get image doc path to overwrite
3136 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3137 'openFlashChart/' . $chartImg;
3139 $chart = imagecreatefrompng($uploadUrl);
3140 //convert it into formatted png
3141 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3142 //overwrite with same image
3143 imagepng($chart, $uploadImg);
3145 imagedestroy($chart);
3147 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3149 CRM_Utils_System
::civiExit();
3151 elseif ($this->_outputMode
== 'csv') {
3152 CRM_Report_Utils_Report
::export2csv($this, $rows);
3154 elseif ($this->_outputMode
== 'group') {
3155 $group = $this->_params
['groups'];
3156 $this->add2group($group);
3161 * Set store result set indicator to TRUE.
3163 * @todo explain what this does
3165 public function storeResultSet() {
3166 $this->_storeResultSet
= TRUE;
3174 public function getResultSet() {
3175 return $this->_resultSet
;
3179 * Get the sql used to generate the report.
3183 public function getReportSql() {
3184 return $this->sqlArray
;
3188 * Use the form name to create the tpl file name.
3192 public function getTemplateFileName() {
3193 $defaultTpl = parent
::getTemplateFileName();
3194 $template = CRM_Core_Smarty
::singleton();
3195 if (!$template->template_exists($defaultTpl)) {
3196 $defaultTpl = 'CRM/Report/Form.tpl';
3202 * Compile the report content.
3204 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3208 public function compileContent() {
3209 $templateFile = $this->getHookedTemplateFileName();
3210 return $this->_formValues
['report_header'] .
3211 CRM_Core_Form
::$_template->fetch($templateFile) .
3212 $this->_formValues
['report_footer'];
3217 * Post process function.
3219 public function postProcess() {
3220 // get ready with post process params
3221 $this->beginPostProcess();
3224 $sql = $this->buildQuery();
3226 // build array of result based on column headers. This method also allows
3227 // modifying column headers before using it to build result set i.e $rows.
3229 $this->buildRows($sql, $rows);
3231 // format result set.
3232 $this->formatDisplay($rows);
3234 // assign variables to templates
3235 $this->doTemplateAssignment($rows);
3237 // do print / pdf / instance stuff if needed
3238 $this->endPostProcess($rows);
3244 * @param int $rowCount
3248 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3249 // lets do the pager if in html mode
3250 $this->_limit
= NULL;
3252 // CRM-14115, over-ride row count if rowCount is specified in URL
3253 if ($this->_dashBoardRowCount
) {
3254 $rowCount = $this->_dashBoardRowCount
;
3256 if ($this->addPaging
) {
3257 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3259 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3261 // @todo all http vars should be extracted in the preProcess
3262 // - not randomly in the class
3263 if (!$pageId && !empty($_POST)) {
3264 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3265 $pageId = max((int) $_POST['crmPID_B'], 1);
3267 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3268 $pageId = max((int) $_POST['crmPID'], 1);
3270 unset($_POST['crmPID_B'], $_POST['crmPID']);
3273 $pageId = $pageId ?
$pageId : 1;
3274 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3275 $offset = ($pageId - 1) * $rowCount;
3277 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3278 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3280 $this->_limit
= " LIMIT $offset, $rowCount";
3281 return array($offset, $rowCount);
3283 if ($this->_limitValue
) {
3284 if ($this->_offsetValue
) {
3285 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3288 $this->_limit
= " LIMIT " . $this->_limitValue
;
3296 * @param int $rowCount
3298 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3300 // CRM-14115, over-ride row count if rowCount is specified in URL
3301 if ($this->_dashBoardRowCount
) {
3302 $rowCount = $this->_dashBoardRowCount
;
3305 if ($this->_limit
&& ($this->_limit
!= '')) {
3306 $sql = "SELECT FOUND_ROWS();";
3307 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3309 'total' => $this->_rowsFound
,
3310 'rowCount' => $rowCount,
3311 'status' => ts('Records') . ' %%StatusMessage%%',
3312 'buttonBottom' => 'PagerBottomButton',
3313 'buttonTop' => 'PagerTopButton',
3315 if (!empty($this->controller
)) {
3316 // This happens when being called from the api Really we want the api to be able to
3317 // pass paging parameters, but at this stage just preventing test crashes.
3318 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3321 $pager = new CRM_Utils_Pager($params);
3322 $this->assign_by_ref('pager', $pager);
3323 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3328 * Build where clause for groups.
3330 * @param string $field
3331 * @param mixed $value
3336 public function whereGroupClause($field, $value, $op) {
3338 $smartGroupQuery = "";
3340 $group = new CRM_Contact_DAO_Group();
3341 $group->is_active
= 1;
3343 $smartGroups = array();
3344 while ($group->fetch()) {
3345 if (in_array($group->id
, $this->_params
['gid_value']) &&
3346 $group->saved_search_id
3348 $smartGroups[] = $group->id
;
3352 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3354 $smartGroupQuery = '';
3355 if (!empty($smartGroups)) {
3356 $smartGroups = implode(',', $smartGroups);
3357 $smartGroupQuery = " UNION DISTINCT
3358 SELECT DISTINCT smartgroup_contact.contact_id
3359 FROM civicrm_group_contact_cache smartgroup_contact
3360 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3363 $sqlOp = $this->getSQLOperator($op);
3364 if (!is_array($value)) {
3365 $value = array($value);
3367 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3369 $contactAlias = $this->_aliases
['civicrm_contact'];
3370 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3371 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3373 return " {$contactAlias}.id {$sqlOp} (
3374 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3375 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3376 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3377 {$smartGroupQuery} ) ";
3381 * Build where clause for tags.
3383 * @param string $field
3384 * @param mixed $value
3389 public function whereTagClause($field, $value, $op) {
3390 // not using left join in query because if any contact
3391 // belongs to more than one tag, results duplicate
3393 $sqlOp = $this->getSQLOperator($op);
3394 if (!is_array($value)) {
3395 $value = array($value);
3397 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3398 $entity_table = $this->_tagFilterTable
;
3399 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3400 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3401 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3402 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3406 * Generate membership organization clause.
3408 * @param mixed $value
3409 * @param string $op SQL Operator
3413 public function whereMembershipOrgClause($value, $op) {
3414 $sqlOp = $this->getSQLOperator($op);
3415 if (!is_array($value)) {
3416 $value = array($value);
3419 $tmp_membership_org_sql_list = implode(', ', $value);
3420 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3421 SELECT DISTINCT mem.contact_id
3422 FROM civicrm_membership mem
3423 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3424 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3425 WHERE mt.member_of_contact_id IN (" .
3426 $tmp_membership_org_sql_list . ")
3427 AND mt.is_active = '1'
3428 AND mem_status.is_current_member = '1'
3429 AND mem_status.is_active = '1' ) ";
3433 * Generate Membership Type SQL Clause.
3435 * @param mixed $value
3441 public function whereMembershipTypeClause($value, $op) {
3442 $sqlOp = $this->getSQLOperator($op);
3443 if (!is_array($value)) {
3444 $value = array($value);
3447 $tmp_membership_sql_list = implode(', ', $value);
3448 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3449 SELECT DISTINCT mem.contact_id
3450 FROM civicrm_membership mem
3451 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3452 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3453 WHERE mem.membership_type_id IN (" .
3454 $tmp_membership_sql_list . ")
3455 AND mt.is_active = '1'
3456 AND mem_status.is_current_member = '1'
3457 AND mem_status.is_active = '1' ) ";
3461 * Build acl clauses.
3463 * @param string $tableAlias
3465 public function buildACLClause($tableAlias = 'contact_a') {
3466 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3470 * Add custom data to the columns.
3472 * @param bool $addFields
3473 * @param array $permCustomGroupIds
3475 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3476 if (empty($this->_customGroupExtends
)) {
3479 if (!is_array($this->_customGroupExtends
)) {
3480 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3482 $customGroupWhere = '';
3483 if (!empty($permCustomGroupIds)) {
3484 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3488 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3489 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3490 FROM civicrm_custom_group cg
3491 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3492 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3494 cg.is_active = 1 AND
3495 cf.is_active = 1 AND
3496 cf.is_searchable = 1
3497 ORDER BY cg.weight, cf.weight";
3498 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3501 while ($customDAO->fetch()) {
3502 if ($customDAO->table_name
!= $curTable) {
3503 $curTable = $customDAO->table_name
;
3504 $curFields = $curFilters = array();
3507 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3508 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3509 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3510 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3512 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3513 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3514 $this->_columns
[$curTable][$colKey] = array();
3518 $fieldName = 'custom_' . $customDAO->cf_id
;
3521 // this makes aliasing work in favor
3522 $curFields[$fieldName] = array(
3523 'name' => $customDAO->column_name
,
3524 'title' => $customDAO->label
,
3525 'dataType' => $customDAO->data_type
,
3526 'htmlType' => $customDAO->html_type
,
3529 if ($this->_customGroupFilters
) {
3530 // this makes aliasing work in favor
3531 $curFilters[$fieldName] = array(
3532 'name' => $customDAO->column_name
,
3533 'title' => $customDAO->label
,
3534 'dataType' => $customDAO->data_type
,
3535 'htmlType' => $customDAO->html_type
,
3539 switch ($customDAO->data_type
) {
3542 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3543 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3544 // CRM-6946, show time part for datetime date fields
3545 if ($customDAO->time_format
) {
3546 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3551 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3552 $curFilters[$fieldName]['options'] = array('' => ts('- select -'))
3553 + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3554 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3558 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3559 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3563 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3564 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3568 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3569 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3573 case 'StateProvince':
3575 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3577 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3578 if ($options !== FALSE) {
3579 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3580 $curFilters[$fieldName]['options'] = $options;
3584 case 'ContactReference':
3585 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3586 $curFilters[$fieldName]['name'] = 'display_name';
3587 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3589 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3590 $curFields[$fieldName]['name'] = 'display_name';
3591 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3595 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3596 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3599 if (!array_key_exists('type', $curFields[$fieldName])) {
3600 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3604 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3606 if ($this->_customGroupFilters
) {
3607 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3609 if ($this->_customGroupGroupBy
) {
3610 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3616 * Build custom data from clause.
3618 public function customDataFrom() {
3619 if (empty($this->_customGroupExtends
)) {
3622 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3623 $customTables = explode(',', CRM_Core_DAO
::singleValueQuery("SELECT GROUP_CONCAT(table_name) FROM civicrm_custom_group"));
3625 foreach ($this->_columns
as $table => $prop) {
3626 if (in_array($table, $customTables)) {
3627 $extendsTable = $mapper[$prop['extends']];
3629 // check field is in params
3630 if (!$this->isFieldSelected($prop)) {
3633 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3635 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3637 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3638 // handle for ContactReference
3639 if (array_key_exists('fields', $prop)) {
3640 foreach ($prop['fields'] as $fieldName => $field) {
3641 if (CRM_Utils_Array
::value('dataType', $field) ==
3644 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3646 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3655 * Check if the field is selected.
3657 * @param string $prop
3661 public function isFieldSelected($prop) {
3666 if (!empty($this->_params
['fields'])) {
3667 foreach (array_keys($prop['fields']) as $fieldAlias) {
3668 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3669 if ($customFieldId) {
3670 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3674 //might be survey response field.
3675 if (!empty($this->_params
['fields']['survey_response']) &&
3676 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3684 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3685 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3686 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3687 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3694 if (!empty($this->_params
['order_bys'])) {
3695 foreach (array_keys($prop['fields']) as $fieldAlias) {
3696 foreach ($this->_params
['order_bys'] as $orderBy) {
3697 if ($fieldAlias == $orderBy['column'] &&
3698 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3706 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3707 foreach ($prop['filters'] as $fieldAlias => $val) {
3716 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3717 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3718 ||
($attach != 'relative' &&
3719 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3725 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3726 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3737 * Check for empty order_by configurations and remove them.
3739 * Also set template to hide them.
3741 * @param array $formValues
3743 public function preProcessOrderBy(&$formValues) {
3744 // Object to show/hide form elements
3745 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3747 $_showHide->addShow('optionField_1');
3749 // Cycle through order_by options; skip any empty ones, and hide them as well
3752 if (!empty($formValues['order_bys'])) {
3753 foreach ($formValues['order_bys'] as $order_by) {
3754 if ($order_by['column'] && $order_by['column'] != '-') {
3755 $_showHide->addShow('optionField_' . $n);
3756 $orderBys[$n] = $order_by;
3761 for ($i = $n; $i <= 5; $i++
) {
3763 $_showHide->addHide('optionField_' . $i);
3767 // overwrite order_by options with modified values
3768 if (!empty($orderBys)) {
3769 $formValues['order_bys'] = $orderBys;
3772 $formValues['order_bys'] = array(1 => array('column' => '-'));
3775 // assign show/hide data to template
3776 $_showHide->addToTemplate();
3780 * Check if table name has columns in SELECT clause.
3782 * @param string $tableName
3783 * Name of table (index of $this->_columns array).
3787 public function isTableSelected($tableName) {
3788 return in_array($tableName, $this->selectedTables());
3792 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3794 * If the array is unset it will be built.
3799 public function selectedTables() {
3800 if (!$this->_selectedTables
) {
3801 $orderByColumns = array();
3802 if (array_key_exists('order_bys', $this->_params
) &&
3803 is_array($this->_params
['order_bys'])
3805 foreach ($this->_params
['order_bys'] as $orderBy) {
3806 $orderByColumns[] = $orderBy['column'];
3810 foreach ($this->_columns
as $tableName => $table) {
3811 if (array_key_exists('fields', $table)) {
3812 foreach ($table['fields'] as $fieldName => $field) {
3813 if (!empty($field['required']) ||
3814 !empty($this->_params
['fields'][$fieldName])
3816 $this->_selectedTables
[] = $tableName;
3821 if (array_key_exists('order_bys', $table)) {
3822 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3823 if (in_array($orderByName, $orderByColumns)) {
3824 $this->_selectedTables
[] = $tableName;
3829 if (array_key_exists('filters', $table)) {
3830 foreach ($table['filters'] as $filterName => $filter) {
3831 if (!empty($this->_params
["{$filterName}_value"]) ||
3832 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3834 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3837 $this->_selectedTables
[] = $tableName;
3844 return $this->_selectedTables
;
3848 * Add address fields.
3850 * @deprecated - use getAddressColumns which is a more accurate description
3851 * and also accepts an array of options rather than a long list
3853 * adding address fields to construct function in reports
3855 * @param bool $groupBy
3856 * Add GroupBy? Not appropriate for detail report.
3857 * @param bool $orderBy
3858 * Add GroupBy? Not appropriate for detail report.
3859 * @param bool $filters
3860 * @param array $defaults
3863 * address fields for construct clause
3865 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3866 $addressFields = array(
3867 'civicrm_address' => array(
3868 'dao' => 'CRM_Core_DAO_Address',
3870 'address_name' => array(
3871 'title' => ts('Address Name'),
3872 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3875 'street_address' => array(
3876 'title' => ts('Street Address'),
3877 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3879 'supplemental_address_1' => array(
3880 'title' => ts('Supplementary Address Field 1'),
3881 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3883 'supplemental_address_2' => array(
3884 'title' => ts('Supplementary Address Field 2'),
3885 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3887 'street_number' => array(
3888 'name' => 'street_number',
3889 'title' => ts('Street Number'),
3891 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3893 'street_name' => array(
3894 'name' => 'street_name',
3895 'title' => ts('Street Name'),
3897 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3899 'street_unit' => array(
3900 'name' => 'street_unit',
3901 'title' => ts('Street Unit'),
3903 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3906 'title' => ts('City'),
3907 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3909 'postal_code' => array(
3910 'title' => ts('Postal Code'),
3911 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3913 'postal_code_suffix' => array(
3914 'title' => ts('Postal Code Suffix'),
3915 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3917 'country_id' => array(
3918 'title' => ts('Country'),
3919 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3921 'state_province_id' => array(
3922 'title' => ts('State/Province'),
3923 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3925 'county_id' => array(
3926 'title' => ts('County'),
3927 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3930 'grouping' => 'location-fields',
3935 $addressFields['civicrm_address']['filters'] = array(
3936 'street_number' => array(
3937 'title' => ts('Street Number'),
3939 'name' => 'street_number',
3941 'street_name' => array(
3942 'title' => ts('Street Name'),
3943 'name' => 'street_name',
3944 'operator' => 'like',
3946 'postal_code' => array(
3947 'title' => ts('Postal Code'),
3949 'name' => 'postal_code',
3952 'title' => ts('City'),
3953 'operator' => 'like',
3956 'country_id' => array(
3957 'name' => 'country_id',
3958 'title' => ts('Country'),
3959 'type' => CRM_Utils_Type
::T_INT
,
3960 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3961 'options' => CRM_Core_PseudoConstant
::country(),
3963 'state_province_id' => array(
3964 'name' => 'state_province_id',
3965 'title' => ts('State/Province'),
3966 'type' => CRM_Utils_Type
::T_INT
,
3967 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3968 'options' => array(),
3970 'county_id' => array(
3971 'name' => 'county_id',
3972 'title' => ts('County'),
3973 'type' => CRM_Utils_Type
::T_INT
,
3974 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3975 'options' => array(),
3981 $addressFields['civicrm_address']['order_bys'] = array(
3982 'street_name' => array('title' => ts('Street Name')),
3983 'street_number' => array('title' => 'Odd / Even Street Number'),
3984 'street_address' => NULL,
3986 'postal_code' => NULL,
3991 $addressFields['civicrm_address']['group_bys'] = array(
3992 'street_address' => NULL,
3994 'postal_code' => NULL,
3995 'state_province_id' => array(
3996 'title' => ts('State/Province'),
3998 'country_id' => array(
3999 'title' => ts('Country'),
4001 'county_id' => array(
4002 'title' => ts('County'),
4006 return $addressFields;
4010 * Do AlterDisplay processing on Address Fields.
4013 * @param array $rows
4014 * @param int $rowNum
4015 * @param string $baseUrl
4016 * @param string $linkText
4020 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4021 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4022 $entryFound = FALSE;
4024 if (array_key_exists('civicrm_address_country_id', $row)) {
4025 if ($value = $row['civicrm_address_country_id']) {
4026 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4027 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4028 "reset=1&force=1&{$criteriaQueryParams}&" .
4029 "country_id_op=in&country_id_value={$value}",
4030 $this->_absoluteUrl
, $this->_id
4032 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4033 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4034 array(1 => $linkText)
4040 if (array_key_exists('civicrm_address_county_id', $row)) {
4041 if ($value = $row['civicrm_address_county_id']) {
4042 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4043 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4044 "reset=1&force=1&{$criteriaQueryParams}&" .
4045 "county_id_op=in&county_id_value={$value}",
4046 $this->_absoluteUrl
, $this->_id
4048 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4049 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4050 array(1 => $linkText)
4055 // handle state province
4056 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4057 if ($value = $row['civicrm_address_state_province_id']) {
4058 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4060 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4061 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4062 $this->_absoluteUrl
, $this->_id
4064 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4065 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4066 array(1 => $linkText)
4076 * Do AlterDisplay processing on Address Fields.
4079 * @param array $rows
4080 * @param int $rowNum
4081 * @param string $baseUrl
4082 * @param string $linkText
4086 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4087 $entryFound = FALSE;
4088 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4089 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4090 $addLinks = array('gender_id' => 'Gender');
4091 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4092 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4093 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4094 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4095 if (($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4096 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4106 * Adjusts dates passed in to YEAR() for fiscal year.
4108 * @param string $fieldName
4112 public function fiscalYearOffset($fieldName) {
4113 $config = CRM_Core_Config
::singleton();
4114 $fy = $config->fiscalYearStart
;
4115 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4116 ($fy['d'] == 1 && $fy['M'] == 1)
4118 return "YEAR( $fieldName )";
4120 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4121 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4125 * Add Address into From Table if required.
4127 public function addAddressFromClause() {
4128 // include address field if address column is to be included
4129 if ((isset($this->_addressField
) &&
4130 $this->_addressField
4132 $this->isTableSelected('civicrm_address')
4135 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4136 ON ({$this->_aliases['civicrm_contact']}.id =
4137 {$this->_aliases['civicrm_address']}.contact_id) AND
4138 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4143 * Add Phone into From Table if required.
4145 public function addPhoneFromClause() {
4146 // include address field if address column is to be included
4147 if ($this->isTableSelected('civicrm_phone')
4150 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4151 ON ({$this->_aliases['civicrm_contact']}.id =
4152 {$this->_aliases['civicrm_phone']}.contact_id) AND
4153 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4158 * Get phone columns to add to array.
4160 * @param array $options
4161 * - prefix Prefix to add to table (in case of more than one instance of the table)
4162 * - prefix_label Label to give columns from this phone table instance
4165 * phone columns definition
4167 public function getPhoneColumns($options = array()) {
4168 $defaultOptions = array(
4170 'prefix_label' => '',
4173 $options = array_merge($defaultOptions, $options);
4176 $options['prefix'] . 'civicrm_phone' => array(
4177 'dao' => 'CRM_Core_DAO_Phone',
4179 $options['prefix'] . 'phone' => array(
4180 'title' => ts($options['prefix_label'] . 'Phone'),
4190 * Get address columns to add to array.
4192 * @param array $options
4193 * - prefix Prefix to add to table (in case of more than one instance of the table)
4194 * - prefix_label Label to give columns from this address table instance
4197 * address columns definition
4199 public function getAddressColumns($options = array()) {
4202 'prefix_label' => '',
4206 'defaults' => array(),
4208 return $this->addAddressFields(
4209 $options['group_by'],
4210 $options['order_by'],
4211 $options['filters'],
4212 $options['defaults']
4217 * Get a standard set of contact fields.
4221 public function getBasicContactFields() {
4223 'sort_name' => array(
4224 'title' => ts('Contact Name'),
4229 'no_display' => TRUE,
4232 'prefix_id' => array(
4233 'title' => ts('Contact Prefix'),
4235 'first_name' => array(
4236 'title' => ts('First Name'),
4238 'nick_name' => array(
4239 'title' => ts('Nick Name'),
4241 'middle_name' => array(
4242 'title' => ts('Middle Name'),
4244 'last_name' => array(
4245 'title' => ts('Last Name'),
4247 'suffix_id' => array(
4248 'title' => ts('Contact Suffix'),
4250 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4251 'email_greeting_display' => array('title' => ts('Email Greeting')),
4252 'addressee_display' => array('title' => ts('Address Greeting')),
4253 'contact_type' => array(
4254 'title' => ts('Contact Type'),
4256 'contact_sub_type' => array(
4257 'title' => ts('Contact Subtype'),
4259 'gender_id' => array(
4260 'title' => ts('Gender'),
4262 'birth_date' => array(
4263 'title' => ts('Birth Date'),
4266 'title' => ts('Age'),
4267 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4269 'job_title' => array(
4270 'title' => ts('Contact Job title'),
4272 'organization_name' => array(
4273 'title' => ts('Organization Name'),
4275 'external_identifier' => array(
4276 'title' => ts('Contact identifier from external system'),
4282 * Add contact to group.
4284 * @param int $groupID
4286 public function add2group($groupID) {
4287 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4288 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4290 // here are we are prepending / adding contact id field that could be used for adding group
4291 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4292 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select
)) {
4293 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4296 $select = str_ireplace('SELECT ', $select, $this->_select
);
4299 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4300 $sql = str_replace('WITH ROLLUP', '', $sql);
4301 $dao = CRM_Core_DAO
::executeQuery($sql);
4303 $contact_ids = array();
4304 // Add resulting contacts to group
4305 while ($dao->fetch()) {
4306 if ($dao->addtogroup_contact_id
) {
4307 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4311 if (!empty($contact_ids)) {
4312 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4313 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4316 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4322 * Show charts on print screen.
4324 public static function uploadChartImage() {
4325 // upload strictly for '.png' images
4326 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4327 if (preg_match('/\.png$/', $name)) {
4329 // POST data is usually string data, but we are passing a RAW .png
4330 // so PHP is a bit confused and $_POST is empty. But it has saved
4331 // the raw bits into $HTTP_RAW_POST_DATA
4333 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4335 // prepare the directory
4336 $config = CRM_Core_Config
::singleton();
4338 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4340 if (!file_exists($defaultPath)) {
4341 mkdir($defaultPath, 0777, TRUE);
4344 // full path to the saved image including filename
4345 $destination = $defaultPath . $name;
4348 $jfh = fopen($destination, 'w') or die("can't open file");
4349 fwrite($jfh, $httpRawPostData);
4351 CRM_Utils_System
::civiExit();
4356 * Apply common settings to entityRef fields.
4358 * @param array $field
4359 * @param string $table
4361 private function setEntityRefDefaults(&$field, $table) {
4362 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4363 $field['attributes'] +
= array(
4364 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4366 'placeholder' => ts('- select -'),
4371 * Add link fields to the row.
4373 * Function adds the _link & _hover fields to the row.
4376 * @param string $baseUrl
4377 * @param string $linkText
4378 * @param string $value
4379 * @param string $fieldName
4380 * @param string $tablePrefix
4381 * @param string $fieldLabel
4385 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4386 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4387 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4388 "reset=1&force=1&{$criteriaQueryParams}&" .
4389 $fieldName . "_op=in&{$fieldName}_value={$value}",
4390 $this->_absoluteUrl
, $this->_id
4392 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4393 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4394 array(1 => $linkText, 2 => $fieldLabel)
4399 * Generate temporary table to hold all contributions with permissioned FTs.
4401 * @param object $query
4402 * @param string $alias
4403 * @param bool $return
4405 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4406 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4409 $financialTypes = NULL;
4410 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4411 if (empty($financialTypes)) {
4413 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4416 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4419 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4420 $query->_aliases
['civicrm_line_item'] = $alias;
4422 if (empty($query->_where
)) {
4423 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4425 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4426 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4427 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4428 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4429 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4430 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4432 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4433 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4434 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4435 CRM_Core_DAO
::executeQuery($sql);
4437 $query->_aliases
['civicrm_line_item'] = $temp;
4439 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4443 $query->_from
.= $from;
4447 * Get label for show results buttons.
4451 public function getResultsLabel() {
4452 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4453 return $showResultsLabel;
4457 * Determine the output mode from the url or input.
4460 * - pdf : Render as pdf
4461 * - csv : Render as csv
4462 * - print : Render in print format
4463 * - save : save the report and display the new report
4464 * - copy : save the report as a new instance and display that.
4465 * - group : go to the add to group screen.
4467 * Potentially chart variations could also be included but the complexity
4468 * is that we might print a bar chart as a pdf.
4470 protected function setOutputMode() {
4471 $buttonName = $this->controller
->getButtonName();
4472 $this->_outputMode
= CRM_Utils_Request
::retrieve(
4475 CRM_Core_DAO
::$_nullObject,
4477 CRM_Utils_Array
::value('task', $this->_params
)
4481 if ($buttonName == $this->_instanceButtonName
) {
4482 $this->_outputMode
= 'save';
4484 if ($buttonName == $this->_printButtonName
) {
4485 $this->_outputMode
= 'print';
4487 if ($buttonName == $this->_pdfButtonName
) {
4488 $this->_outputMode
= 'pdf';
4490 if ($this->_csvButtonName
== $buttonName) {
4491 $this->_outputMode
= 'csv';
4493 if ($this->_groupButtonName
== $buttonName) {
4494 $this->_outputMode
= 'group';
4496 if ($buttonName == $this->_createNewButtonName
) {
4497 $this->_outputMode
= 'copy';
4503 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4505 * @param $columnName
4507 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4508 // add new column with date value for the datetime field
4509 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4510 CRM_Core_DAO
::executeQuery($tempQuery);
4511 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4512 CRM_Core_DAO
::executeQuery($updateQuery);
4513 $this->_select
.= ", {$columnName}_date";
4514 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4515 unset($this->_sections
["{$columnName}"]);
4516 $this->assign('sections', $this->_sections
);
4520 * Get an array of the columns that have been selected for display.
4524 public function getSelectColumns() {
4525 $selectColumns = array();
4526 foreach ($this->_columns
as $tableName => $table) {
4527 if (array_key_exists('fields', $table)) {
4528 foreach ($table['fields'] as $fieldName => $field) {
4529 if (!empty($field['required']) ||
4530 !empty($this->_params
['fields'][$fieldName])
4533 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4538 return $selectColumns;