3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 protected $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * Array of tabs to display on report.
167 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
169 * $this->tabs['OrderBy'] = array(
170 * 'title' => ts('Sorting'),
171 * 'tpl' => 'OrderBy',
172 * 'div_label' => 'order-by',
177 protected $tabs = array();
180 * Should we add paging.
184 protected $addPaging = TRUE;
187 * An attribute for checkbox/radio form field layout
191 protected $_fourColumnAttribute = array(
192 '</td><td width="25%">',
193 '</td><td width="25%">',
194 '</td><td width="25%">',
198 protected $_force = 1;
200 protected $_params = NULL;
201 protected $_formValues = NULL;
202 protected $_instanceValues = NULL;
204 protected $_instanceForm = FALSE;
205 protected $_criteriaForm = FALSE;
207 protected $_instanceButtonName = NULL;
208 protected $_createNewButtonName = NULL;
209 protected $_printButtonName = NULL;
210 protected $_pdfButtonName = NULL;
211 protected $_csvButtonName = NULL;
212 protected $_groupButtonName = NULL;
213 protected $_chartButtonName = NULL;
214 protected $_csvSupported = TRUE;
215 protected $_add2groupSupported = TRUE;
216 protected $_groups = NULL;
217 protected $_grandFlag = FALSE;
218 protected $_rowsFound = NULL;
219 protected $_selectAliases = array();
220 protected $_rollup = NULL;
225 protected $_aliases = array();
241 protected $_limit = NULL;
244 * This can be set to specify a limit to the number of rows
245 * Since it is currently envisaged as part of the api usage it is only being applied
246 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
247 * of the code (see limit() fn.
251 protected $_limitValue = NULL;
254 * This can be set to specify row offset
255 * See notes on _limitValue
258 protected $_offsetValue = NULL;
262 protected $_sections = NULL;
263 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
264 protected $_absoluteUrl = FALSE;
267 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
271 protected $_storeResultSet = FALSE;
274 * When _storeResultSet Flag is set use this var to store result set in form of array
278 protected $_resultSet = array();
281 * To what frequency group-by a date column
285 protected $_groupByDateFreq = array(
287 'YEARWEEK' => 'Week',
288 'QUARTER' => 'Quarter',
293 * Variables to hold the acl inner join and where clause
295 protected $_aclFrom = NULL;
296 protected $_aclWhere = NULL;
299 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
301 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
305 protected $_selectedTables;
308 * Array of DAO tables having columns included in WHERE or HAVING clause
312 protected $filteredTables;
315 * Output mode e.g 'print', 'csv', 'pdf'.
319 protected $_outputMode;
322 * Format of any chart in use.
324 * (it's unclear if this could be merged with outputMode at this stage)
330 public $_having = NULL;
331 public $_select = NULL;
332 public $_selectClauses = array();
333 public $_columnHeaders = array();
334 public $_orderBy = NULL;
335 public $_orderByFields = array();
336 public $_orderByArray = array();
337 public $_groupBy = NULL;
338 public $_whereClauses = array();
339 public $_havingClauses = array();
342 * DashBoardRowCount Dashboard row count
345 public $_dashBoardRowCount;
348 * Is this being called without a form controller (ie. the report is being render outside the normal form
349 * - e.g the api is retrieving the rows
352 public $noController = FALSE;
355 * Variable to hold the currency alias
357 protected $_currencyColumn = NULL;
362 protected $_interval;
367 protected $_sendmail;
380 * @var string Report description.
382 public $_description;
385 * @var bool Is an address field selected.
386 * This was intended to determine if the address table should be joined in
387 * The isTableSelected function is now preferred for this purpose
389 protected $_addressField;
392 * @var bool Is an email field selected.
393 * This was intended to determine if the email table should be joined in
394 * The isTableSelected function is now preferred for this purpose
396 protected $_emailField;
399 * @var bool Is a phone field selected.
400 * This was intended to determine if the phone table should be joined in
401 * The isTableSelected function is now preferred for this purpose
403 protected $_phoneField;
406 * @var bool Create new report instance? (or update existing) on save.
408 protected $_createNew;
411 * When a grand total row has calculated the status we pop it off to here.
413 * This allows us to access it from the stats function and avoid recalculating.
415 protected $rollupRow = array();
418 * SQL being run in this report.
420 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
428 * SQL being run in this report as an array.
430 * The sql in the report is stored in this variable in order to be returned to api & test calls.
439 public function __construct() {
440 parent
::__construct();
442 $this->addClass('crm-report-form');
444 if ($this->_tagFilter
) {
445 $this->buildTagFilter();
447 if ($this->_exposeContactID
) {
448 if (array_key_exists('civicrm_contact', $this->_columns
)) {
449 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
451 'title' => ts('Contact ID'),
457 if ($this->_groupFilter
) {
458 $this->buildGroupFilter();
461 // Get all custom groups
462 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
464 // Get the custom groupIds for which the user has VIEW permission
465 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
466 // and addCustomDataToColumns() will allow access to all custom groups.
467 $permCustomGroupIds = array();
468 if (!CRM_Core_Permission
::check('access all custom data')) {
469 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
470 // do not allow custom data for reports if user doesn't have
471 // permission to access custom data.
472 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
473 $this->_customGroupExtends
= array();
477 // merge custom data columns to _columns list, if any
478 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
480 // add / modify display columns, filters ..etc
481 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
483 //assign currencyColumn variable to tpl
484 $this->assign('currencyColumn', $this->_currencyColumn
);
488 * Shared pre-process function.
490 * If overriding preProcess function this should still be called.
494 public function preProcessCommon() {
496 = CRM_Utils_Request
::retrieve(
499 CRM_Core_DAO
::$_nullObject
502 $this->_dashBoardRowCount
503 = CRM_Utils_Request
::retrieve(
506 CRM_Core_DAO
::$_nullObject
509 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
511 $this->assign('section', $this->_section
);
512 CRM_Core_Region
::instance('page-header')->add(array(
513 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
515 if (!$this->noController
) {
516 $this->setID($this->get('instanceId'));
519 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
521 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
525 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
526 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
527 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
531 $this->assign('instanceId', $this->_id
);
532 $params = array('id' => $this->_id
);
533 $this->_instanceValues
= array();
534 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
536 $this->_instanceValues
538 if (empty($this->_instanceValues
)) {
539 CRM_Core_Error
::fatal("Report could not be loaded.");
541 $this->_title
= $this->_instanceValues
['title'];
542 if (!empty($this->_instanceValues
['permission']) &&
543 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
544 CRM_Core_Permission
::check('administer Reports')
547 CRM_Utils_System
::permissionDenied();
548 CRM_Utils_System
::civiExit();
551 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
553 $this->_formValues
= unserialize($formValues);
556 $this->_formValues
= NULL;
559 $this->setOutputMode();
561 if ($this->_outputMode
== 'copy') {
562 $this->_createNew
= TRUE;
563 $this->_params
= $this->_formValues
;
564 $this->_params
['view_mode'] = 'criteria';
565 $this->_params
['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', array(
566 CRM_Core_Session
::singleton()->getLoggedInContactDisplayName(),
567 CRM_Utils_Date
::customFormat(date('Y-m-d H:i')),
569 // Do not pass go. Do not collect another chance to re-run the same query.
570 CRM_Report_Form_Instance
::postProcess($this);
573 // lets always do a force if reset is found in the url.
574 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
575 // in the comment line above these 2.
576 if (!empty($_REQUEST['reset'])
577 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
582 $this->assign('mode', 'instance');
584 elseif (!$this->noController
) {
585 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
586 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
587 if (($instanceCount > 0) && $optionValueID) {
588 $this->assign('instanceUrl',
589 CRM_Utils_System
::url('civicrm/report/list',
590 "reset=1&ovid=$optionValueID"
594 if ($optionValueID) {
595 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
599 $this->assign('mode', 'template');
602 // lets display the Report Settings section
603 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
605 // Do not display Report Settings section if administer Reports permission is absent OR
606 // if report instance is reserved and administer reserved reports absent
607 if (!CRM_Core_Permission
::check('administer Reports') ||
608 ($this->_instanceValues
['is_reserved'] &&
609 !CRM_Core_Permission
::check('administer reserved reports'))
611 $this->_instanceForm
= FALSE;
614 $this->assign('criteriaForm', FALSE);
615 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
616 if (CRM_Core_Permission
::check('administer Reports') ||
617 CRM_Core_Permission
::check('access Report Criteria')
619 if (!$this->_instanceValues
['is_reserved'] ||
620 CRM_Core_Permission
::check('administer reserved reports')
622 $this->assign('criteriaForm', TRUE);
623 $this->_criteriaForm
= TRUE;
627 // Special permissions check for private instance if it's not the current contact instance
629 (CRM_Report_BAO_ReportInstance
::reportIsPrivate($this->_id
) &&
630 !CRM_Report_BAO_ReportInstance
::contactIsOwner($this->_id
))) {
631 if (!CRM_Core_Permission
::check('access all private reports')) {
632 $this->_instanceForm
= FALSE;
633 $this->assign('criteriaForm', FALSE);
637 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
638 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
639 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
640 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
646 public function addBreadCrumb() {
650 'title' => ts('Report Templates'),
651 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
655 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
659 * Pre process function.
661 * Called prior to build form.
663 public function preProcess() {
664 $this->preProcessCommon();
667 $this->addBreadCrumb();
670 foreach ($this->_columns
as $tableName => $table) {
672 if (!isset($table['alias'])) {
673 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
677 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
680 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
682 $daoOrBaoName = NULL;
683 // higher preference to bao object
684 if (array_key_exists('bao', $table)) {
685 $daoOrBaoName = $table['bao'];
686 $expFields = $daoOrBaoName::exportableFields();
688 elseif (array_key_exists('dao', $table)) {
689 $daoOrBaoName = $table['dao'];
690 $expFields = $daoOrBaoName::export();
693 $expFields = array();
696 $doNotCopy = array('required');
698 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
699 foreach ($fieldGroups as $fieldGrp) {
700 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
701 foreach ($table[$fieldGrp] as $fieldName => $field) {
702 // $name is the field name used to reference the BAO/DAO export fields array
703 $name = isset($field['name']) ?
$field['name'] : $fieldName;
705 // Sometimes the field name key in the BAO/DAO export fields array is
706 // different from the actual database field name.
707 // Unset $field['name'] so that actual database field name can be obtained
708 // from the BAO/DAO export fields array.
709 unset($field['name']);
711 if (array_key_exists($name, $expFields)) {
712 foreach ($doNotCopy as $dnc) {
713 // unset the values we don't want to be copied.
714 unset($expFields[$name][$dnc]);
717 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
720 foreach ($expFields[$name] as $property => $val) {
721 if (!array_key_exists($property, $field)) {
722 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
729 if (!empty($field['no_repeat'])) {
730 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
732 if (!empty($field['no_display'])) {
733 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
736 // set alias = table-name, unless already set
737 $alias = isset($field['alias']) ?
$field['alias'] : (
738 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
740 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
742 // set name = fieldName, unless already set
743 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
744 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
747 // set dbAlias = alias.name, unless already set
748 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
749 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
751 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
754 // a few auto fills for filters
755 if ($fieldGrp == 'filters') {
756 // fill operator types
757 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
758 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
759 case CRM_Utils_Type
::T_MONEY
:
760 case CRM_Utils_Type
::T_FLOAT
:
761 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
764 case CRM_Utils_Type
::T_INT
:
765 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
768 case CRM_Utils_Type
::T_DATE
:
769 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
772 case CRM_Utils_Type
::T_BOOLEAN
:
773 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
774 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
775 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
786 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
788 // with multiple options operator-type is generally multi-select
789 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
790 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
792 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
803 // copy filters to a separate handy variable
804 if (array_key_exists('filters', $table)) {
805 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
808 if (array_key_exists('group_bys', $table)) {
809 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
812 if (array_key_exists('fields', $table)) {
813 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
818 $this->setDefaultValues(FALSE);
821 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
822 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
823 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
824 CRM_Report_Utils_Get
::processChart($this->_defaults
);
827 $this->_formValues
= $this->_defaults
;
828 $this->postProcess();
833 * Set default values.
835 * @param bool $freeze
839 public function setDefaultValues($freeze = TRUE) {
840 $freezeGroup = array();
842 // FIXME: generalizing form field naming conventions would reduce
843 // Lots of lines below.
844 foreach ($this->_columns
as $tableName => $table) {
845 if (array_key_exists('fields', $table)) {
846 foreach ($table['fields'] as $fieldName => $field) {
847 if (empty($field['no_display'])) {
848 if (isset($field['required'])) {
850 $this->_defaults
['fields'][$fieldName] = 1;
853 // find element object, so that we could use quickform's freeze method
854 // for required elements
855 $obj = $this->getElementFromGroup("fields", $fieldName);
857 $freezeGroup[] = $obj;
861 elseif (isset($field['default'])) {
862 $this->_defaults
['fields'][$fieldName] = $field['default'];
868 if (array_key_exists('group_bys', $table)) {
869 foreach ($table['group_bys'] as $fieldName => $field) {
870 if (isset($field['default'])) {
871 if (!empty($field['frequency'])) {
872 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
874 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
878 if (array_key_exists('filters', $table)) {
879 foreach ($table['filters'] as $fieldName => $field) {
880 if (isset($field['default'])) {
881 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
883 if (is_array($field['default'])) {
884 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
885 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
886 $this->_defaults
["{$fieldName}_relative"] = 0;
889 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
893 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
894 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
895 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
897 $this->_defaults
["{$fieldName}_value"] = $field['default'];
900 //assign default value as "in" for multiselect
901 //operator, To freeze the select element
902 if (CRM_Utils_Array
::value('operatorType', $field) ==
903 CRM_Report_Form
::OP_MULTISELECT
905 $this->_defaults
["{$fieldName}_op"] = 'in';
907 if (CRM_Utils_Array
::value('operatorType', $field) ==
908 CRM_Report_Form
::OP_ENTITYREF
910 $this->_defaults
["{$fieldName}_op"] = 'in';
912 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
913 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
915 $this->_defaults
["{$fieldName}_op"] = 'mhas';
917 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
918 $this->_defaults
["{$fieldName}_op"] = $op;
924 empty($this->_formValues
['order_bys']) &&
925 (array_key_exists('order_bys', $table) &&
926 is_array($table['order_bys']))
928 if (!array_key_exists('order_bys', $this->_defaults
)) {
929 $this->_defaults
['order_bys'] = array();
931 foreach ($table['order_bys'] as $fieldName => $field) {
932 if (!empty($field['default']) ||
!empty($field['default_order']) ||
933 CRM_Utils_Array
::value('default_is_section', $field) ||
934 !empty($field['default_weight'])
937 'column' => $fieldName,
938 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
939 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
942 if (!empty($field['default_weight'])) {
943 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
946 array_unshift($this->_defaults
['order_bys'], $order_by);
952 foreach ($this->_options
as $fieldName => $field) {
953 if (isset($field['default'])) {
954 $this->_defaults
['options'][$fieldName] = $field['default'];
959 if (!empty($this->_submitValues
)) {
960 $this->preProcessOrderBy($this->_submitValues
);
963 $this->preProcessOrderBy($this->_defaults
);
966 // lets finish freezing task here itself
967 if (!empty($freezeGroup)) {
968 foreach ($freezeGroup as $elem) {
973 if ($this->_formValues
) {
974 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
977 if ($this->_instanceValues
) {
978 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
981 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
983 return $this->_defaults
;
987 * Get element from group.
989 * @param string $group
990 * @param string $grpFieldName
994 public function getElementFromGroup($group, $grpFieldName) {
995 $eleObj = $this->getElement($group);
996 foreach ($eleObj->_elements
as $index => $obj) {
997 if ($grpFieldName == $obj->_attributes
['name']) {
1005 * Setter for $_params.
1007 * @param array $params
1009 public function setParams($params) {
1010 $this->_params
= $params;
1016 * @param int $instanceID
1018 public function setID($instanceID) {
1019 $this->_id
= $instanceID;
1023 * Setter for $_force.
1025 * @param bool $isForce
1027 public function setForce($isForce) {
1028 $this->_force
= $isForce;
1032 * Setter for $_limitValue.
1034 * @param int $_limitValue
1036 public function setLimitValue($_limitValue) {
1037 $this->_limitValue
= $_limitValue;
1041 * Setter for $_offsetValue.
1043 * @param int $_offsetValue
1045 public function setOffsetValue($_offsetValue) {
1046 $this->_offsetValue
= $_offsetValue;
1050 * Setter for $addPaging.
1052 * @param bool $value
1054 public function setAddPaging($value) {
1055 $this->addPaging
= $value;
1059 * Getter for $_defaultValues.
1063 public function getDefaultValues() {
1064 return $this->_defaults
;
1068 * Add columns to report.
1070 public function addColumns() {
1073 foreach ($this->_columns
as $tableName => $table) {
1074 if (array_key_exists('fields', $table)) {
1075 foreach ($table['fields'] as $fieldName => $field) {
1077 if (empty($field['no_display'])) {
1078 foreach (array('table', 'field') as $var) {
1079 if (!empty($
{$var}['grouping'])) {
1080 if (!is_array($
{$var}['grouping'])) {
1081 $tableName = $
{$var}['grouping'];
1084 $tableName = array_keys($
{$var}['grouping']);
1085 $tableName = $tableName[0];
1086 $groupTitle = array_values($
{$var}['grouping']);
1087 $groupTitle = $groupTitle[0];
1092 if (!$groupTitle && isset($table['group_title'])) {
1093 $groupTitle = $table['group_title'];
1094 // Having a group_title is secret code for being a custom group
1095 // which cryptically translates to needing an accordion.
1096 // here we make that explicit.
1097 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1100 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1101 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1102 $colGroups[$tableName]['group_title'] = $groupTitle;
1104 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1110 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1111 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1113 if (!empty($colGroups)) {
1114 $this->tabs
['FieldSelection'] = array(
1115 'title' => ts('Columns'),
1116 'tpl' => 'FieldSelection',
1117 'div_label' => 'col-groups',
1120 // Note this assignment is only really required in buildForm. It is being 'over-called'
1121 // to reduce risk of being missed due to overridden functions.
1122 $this->assign('tabs', $this->tabs
);
1125 $this->assign('colGroups', $colGroups);
1129 * Add filters to report.
1131 public function addFilters() {
1132 $filters = $filterGroups = array();
1135 foreach ($this->_filters
as $table => $attributes) {
1136 if (isset($this->_columns
[$table]['group_title'])) {
1137 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1138 // which magically means to 'display in an accordian'
1139 // here we make this explicit.
1140 $filterGroups[$table] = array(
1141 'group_title' => $this->_columns
[$table]['group_title'],
1142 'use_accordian_for_field_selection' => TRUE,
1146 foreach ($attributes as $fieldName => $field) {
1147 // get ready with option value pair
1148 // @ 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
1150 $operations = $this->getOperationPair(
1151 CRM_Utils_Array
::value('operatorType', $field),
1154 $filters[$table][$fieldName] = $field;
1156 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1157 case CRM_Report_Form
::OP_MONTH
:
1158 if (!array_key_exists('options', $field) ||
1159 !is_array($field['options']) ||
empty($field['options'])
1161 // If there's no option list for this filter, define one.
1162 $field['options'] = array(
1164 2 => ts('February'),
1171 9 => ts('September'),
1172 10 => ts('October'),
1173 11 => ts('November'),
1174 12 => ts('December'),
1176 // Add this option list to this column _columns. This is
1177 // required so that filter statistics show properly.
1178 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1180 case CRM_Report_Form
::OP_MULTISELECT
:
1181 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1182 // assume a multi-select field
1183 if (!empty($field['options']) ||
1184 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1186 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1187 if (count($operations) <= 1) {
1190 if ($fieldName == 'state_province_id' ||
1191 $fieldName == 'county_id'
1193 $this->addChainSelect($fieldName . '_value', array(
1200 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1201 'style' => 'min-width:250px',
1202 'class' => 'crm-select2 huge',
1204 'placeholder' => ts('- select -'),
1210 case CRM_Report_Form
::OP_SELECT
:
1211 // assume a select field
1212 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1213 if (!empty($field['options'])) {
1214 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1218 case CRM_Report_Form
::OP_ENTITYREF
:
1219 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1220 $this->setEntityRefDefaults($field, $table);
1221 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1224 case CRM_Report_Form
::OP_DATE
:
1225 // build datetime fields
1226 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations);
1230 case CRM_Report_Form
::OP_DATETIME
:
1231 // build datetime fields
1232 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', ts('From:'), FALSE, $operations, 'searchDate', TRUE);
1236 case CRM_Report_Form
::OP_INT
:
1237 case CRM_Report_Form
::OP_FLOAT
:
1238 // and a min value input box
1239 $this->add('text', "{$fieldName}_min", ts('Min'));
1240 // and a max value input box
1241 $this->add('text', "{$fieldName}_max", ts('Max'));
1243 // default type is string
1244 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1245 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1247 // we need text box for value input
1248 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1253 if (!empty($filters)) {
1254 $this->tabs
['Filters'] = array(
1255 'title' => ts('Filters'),
1257 'div_label' => 'set-filters',
1260 $this->assign('filters', $filters);
1261 $this->assign('filterGroups', $filterGroups);
1265 * Function to assign the tabs to the template in the correct order.
1267 * We want the tabs to wind up in this order (if not overridden).
1275 protected function assignTabs() {
1283 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1284 $order = array_merge($order, $this->tabs
);
1285 $this->assign('tabs', $order);
1289 * The intent is to add a tab for developers to view the sql.
1291 * Currently using dpm.
1293 * @param string $sql
1295 protected function addToDeveloperTab($sql) {
1296 if (!CRM_Core_Permission
::check('view report sql')) {
1299 $this->tabs
['Developer'] = array(
1300 'title' => ts('Developer'),
1301 'tpl' => 'Developer',
1302 'div_label' => 'set-developer',
1305 $this->assignTabs();
1306 $this->sqlArray
[] = $sql;
1307 foreach (array('LEFT JOIN') as $term) {
1308 $sql = str_replace($term, '<br />  ' . $term, $sql);
1310 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1311 $sql = str_replace($term, '<br /><br />' . $term, $sql);
1313 $this->sql
.= $sql . "<br />";
1315 $this->assign('sql', $this->sql
);
1319 * Add options defined in $this->_options to the report.
1321 public function addOptions() {
1322 if (!empty($this->_options
)) {
1323 // FIXME: For now lets build all elements as checkboxes.
1324 // Once we clear with the format we can build elements based on type
1326 foreach ($this->_options
as $fieldName => $field) {
1329 if ($field['type'] == 'select') {
1330 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1332 elseif ($field['type'] == 'checkbox') {
1333 $options[$field['title']] = $fieldName;
1334 $this->addCheckBox($fieldName, NULL,
1336 NULL, NULL, NULL, $this->_fourColumnAttribute
1341 if (!empty($this->_options
) &&
1343 ||
($this->_id
&& CRM_Report_BAO_ReportInstance
::contactCanAdministerReport($this->_id
)))
1345 $this->tabs
['ReportOptions'] = array(
1346 'title' => ts('Display Options'),
1347 'tpl' => 'ReportOptions',
1348 'div_label' => 'other-options',
1351 $this->assign('otherOptions', $this->_options
);
1355 * Add chart options to the report.
1357 public function addChartOptions() {
1358 if (!empty($this->_charts
)) {
1359 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1360 $this->assign('charts', $this->_charts
);
1361 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1366 * Add group by options to the report.
1368 public function addGroupBys() {
1369 $options = $freqElements = array();
1371 foreach ($this->_columns
as $tableName => $table) {
1372 if (array_key_exists('group_bys', $table)) {
1373 foreach ($table['group_bys'] as $fieldName => $field) {
1374 if (!empty($field)) {
1375 $options[$field['title']] = $fieldName;
1376 if (!empty($field['frequency'])) {
1377 $freqElements[$field['title']] = $fieldName;
1383 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1384 NULL, NULL, NULL, $this->_fourColumnAttribute
1386 $this->assign('groupByElements', $options);
1387 if (!empty($options)) {
1388 $this->tabs
['GroupBy'] = array(
1389 'title' => ts('Grouping'),
1391 'div_label' => 'group-by-elements',
1395 foreach ($freqElements as $name) {
1396 $this->addElement('select', "group_bys_freq[$name]",
1397 ts('Frequency'), $this->_groupByDateFreq
1403 * Add data for order by tab.
1405 public function addOrderBys() {
1407 foreach ($this->_columns
as $tableName => $table) {
1409 // Report developer may define any column to order by; include these as order-by options.
1410 if (array_key_exists('order_bys', $table)) {
1411 foreach ($table['order_bys'] as $fieldName => $field) {
1412 if (!empty($field)) {
1413 $options[$fieldName] = $field['title'];
1418 // Add searchable custom fields as order-by options, if so requested
1419 // (These are already indexed, so allowing to order on them is cheap.)
1421 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1422 array_key_exists('extends', $table) && !empty($table['extends'])
1424 foreach ($table['fields'] as $fieldName => $field) {
1425 if (empty($field['no_display'])) {
1426 $options[$fieldName] = $field['title'];
1434 $this->assign('orderByOptions', $options);
1435 if (!empty($options)) {
1436 $this->tabs
['OrderBy'] = array(
1437 'title' => ts('Sorting'),
1439 'div_label' => 'order-by-elements',
1443 if (!empty($options)) {
1445 '-' => ' - none - ',
1447 for ($i = 1; $i <= 5; $i++
) {
1448 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1449 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1450 'ASC' => ts('Ascending'),
1451 'DESC' => ts('Descending'),
1453 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1454 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1460 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1462 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1463 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1466 public function buildInstanceAndButtons() {
1467 CRM_Report_Form_Instance
::buildForm($this);
1468 $this->_actionButtonName
= $this->getButtonName('submit');
1469 $this->addTaskMenu($this->getActions($this->_id
));
1471 $this->assign('instanceForm', $this->_instanceForm
);
1473 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1474 $permission = CRM_Core_Permission
::getPermission();
1475 if ($permission == CRM_Core_Permission
::EDIT
&&
1476 $this->_add2groupSupported
1478 $this->addElement('select', 'groups', ts('Group'),
1479 array('' => ts('Add Contacts to Group')) +
1480 CRM_Core_PseudoConstant
::nestedGroup(),
1481 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1483 $this->assign('group', TRUE);
1486 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1488 $this->addChartOptions();
1489 $showResultsLabel = $this->getResultsLabel();
1490 $this->addButtons(array(
1493 'name' => $showResultsLabel,
1494 'isDefault' => TRUE,
1501 * Has this form been submitted already?
1505 public function resultsDisplayed() {
1506 $buttonName = $this->controller
->getButtonName();
1507 return ($buttonName ||
$this->_outputMode
);
1511 * Get the actions for this report instance.
1513 * @param int $instanceId
1517 protected function getActions($instanceId) {
1518 $actions = CRM_Report_BAO_ReportInstance
::getActionMetadata();
1519 if (empty($instanceId)) {
1520 $actions['report_instance.save']['title'] = ts('Create Report');
1523 if (!$this->_csvSupported
) {
1524 unset($actions['report_instance.csv']);
1531 * Main build form function.
1533 public function buildQuickForm() {
1534 $this->addColumns();
1536 $this->addFilters();
1538 $this->addOptions();
1540 $this->addGroupBys();
1542 $this->addOrderBys();
1544 $this->buildInstanceAndButtons();
1546 // Add form rule for report.
1547 if (is_callable(array(
1551 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1553 $this->assignTabs();
1557 * A form rule function for custom data.
1559 * The rule ensures that fields selected in group_by if any) should only be the ones
1560 * present in display/select fields criteria;
1561 * note: works if and only if any custom field selected in group_by.
1563 * @param array $fields
1564 * @param array $ignoreFields
1568 public function customDataFormRule($fields, $ignoreFields = array()) {
1570 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1571 !empty($fields['group_bys'])
1573 foreach ($this->_columns
as $tableName => $table) {
1574 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1575 substr($tableName, 0, 12) == 'custom_value') &&
1576 !empty($this->_columns
[$tableName]['fields'])
1578 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1579 if (array_key_exists($fieldName, $fields['group_bys']) &&
1580 !array_key_exists($fieldName, $fields['fields'])
1582 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1584 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1585 foreach ($fields['fields'] as $fld => $val) {
1586 if (!array_key_exists($fld, $fields['group_bys']) &&
1587 !in_array($fld, $ignoreFields)
1589 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1601 * Get operators to display on form.
1603 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1605 * @param string $type
1606 * @param string $fieldName
1610 public function getOperationPair($type = "string", $fieldName = NULL) {
1611 // FIXME: At some point we should move these key-val pairs
1612 // to option_group and option_value table.
1614 case CRM_Report_Form
::OP_INT
:
1615 case CRM_Report_Form
::OP_FLOAT
:
1618 'lte' => ts('Is less than or equal to'),
1619 'gte' => ts('Is greater than or equal to'),
1620 'bw' => ts('Is between'),
1621 'eq' => ts('Is equal to'),
1622 'lt' => ts('Is less than'),
1623 'gt' => ts('Is greater than'),
1624 'neq' => ts('Is not equal to'),
1625 'nbw' => ts('Is not between'),
1626 'nll' => ts('Is empty (Null)'),
1627 'nnll' => ts('Is not empty (Null)'),
1631 case CRM_Report_Form
::OP_SELECT
:
1633 'eq' => ts('Is equal to'),
1637 case CRM_Report_Form
::OP_MONTH
:
1638 case CRM_Report_Form
::OP_MULTISELECT
:
1639 case CRM_Report_Form
::OP_ENTITYREF
:
1642 'in' => ts('Is one of'),
1643 'notin' => ts('Is not one of'),
1647 case CRM_Report_Form
::OP_DATE
:
1650 'nll' => ts('Is empty (Null)'),
1651 'nnll' => ts('Is not empty (Null)'),
1655 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1656 // use this operator for the values, concatenated with separator. For e.g if
1657 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1659 'mhas' => ts('Is one of'),
1660 'mnot' => ts('Is not one of'),
1667 'has' => ts('Contains'),
1668 'sw' => ts('Starts with'),
1669 'ew' => ts('Ends with'),
1670 'nhas' => ts('Does not contain'),
1671 'eq' => ts('Is equal to'),
1672 'neq' => ts('Is not equal to'),
1673 'nll' => ts('Is empty (Null)'),
1674 'nnll' => ts('Is not empty (Null)'),
1681 * Build the tag filter field to display on the filters tab.
1683 public function buildTagFilter() {
1684 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1685 if (!empty($contactTags)) {
1686 $this->_columns
['civicrm_tag'] = array(
1687 'dao' => 'CRM_Core_DAO_Tag',
1691 'title' => ts('Tag'),
1692 'type' => CRM_Utils_Type
::T_INT
,
1694 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1695 'options' => $contactTags,
1703 * Adds group filters to _columns (called from _Construct).
1705 public function buildGroupFilter() {
1706 $this->_columns
['civicrm_group']['filters'] = array(
1708 'name' => 'group_id',
1709 'title' => ts('Group'),
1710 'type' => CRM_Utils_Type
::T_INT
,
1711 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1713 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1716 if (empty($this->_columns
['civicrm_group']['dao'])) {
1717 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1719 if (empty($this->_columns
['civicrm_group']['alias'])) {
1720 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1725 * Get SQL operator from form text version.
1727 * @param string $operator
1731 public function getSQLOperator($operator = "like") {
1732 switch ($operator) {
1765 return 'IS NOT NULL';
1774 * Generate where clause.
1776 * This can be overridden in reports for special treatment of a field
1778 * @param array $field Field specifications
1779 * @param string $op Query operator (not an exact match to sql)
1780 * @param mixed $value
1784 * @return null|string
1786 public function whereClause(&$field, $op, $value, $min, $max) {
1788 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1790 // CRM-18010: Ensure type of each report filters
1792 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING
);
1799 if (($min !== NULL && strlen($min) > 0) ||
1800 ($max !== NULL && strlen($max) > 0)
1804 $min = CRM_Utils_Type
::escape($min, $type);
1806 $clauses[] = "( {$field['dbAlias']} >= $min )";
1809 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
1813 $max = CRM_Utils_Type
::escape($max, $type);
1815 $clauses[] = "( {$field['dbAlias']} <= $max )";
1818 $clauses[] = "( {$field['dbAlias']} > $max )";
1822 if (!empty($clauses)) {
1824 $clause = implode(' AND ', $clauses);
1827 $clause = '(' . implode('OR', $clauses) . ')';
1835 if ($value !== NULL && strlen($value) > 0) {
1836 $value = CRM_Utils_Type
::escape($value, $type);
1837 if (strpos($value, '%') === FALSE) {
1838 $value = "'%{$value}%'";
1841 $value = "'{$value}'";
1843 $sqlOP = $this->getSQLOperator($op);
1844 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1850 if (is_string($value) && strlen($value)) {
1851 $value = explode(',', $value);
1853 if ($value !== NULL && is_array($value) && count($value) > 0) {
1854 $sqlOP = $this->getSQLOperator($op);
1855 if (CRM_Utils_Array
::value('type', $field) ==
1856 CRM_Utils_Type
::T_STRING
1858 //cycle through selections and escape values
1859 foreach ($value as $key => $selection) {
1860 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1863 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1867 // for numerical values
1868 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1871 if ($op == 'notin') {
1872 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1875 $clause = "( " . $clause . " )";
1882 // multiple has or multiple not
1883 if ($value !== NULL && count($value) > 0) {
1884 $value = CRM_Utils_Type
::escapeAll($value, $type);
1885 $operator = $op == 'mnot' ?
'NOT' : '';
1886 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
1887 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1893 if ($value !== NULL && strlen($value) > 0) {
1894 $value = CRM_Utils_Type
::escape($value, $type);
1895 if (strpos($value, '%') === FALSE) {
1897 $value = "'{$value}%'";
1900 $value = "'%{$value}'";
1904 $value = "'{$value}'";
1906 $sqlOP = $this->getSQLOperator($op);
1907 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1913 $sqlOP = $this->getSQLOperator($op);
1914 $clause = "( {$field['dbAlias']} $sqlOP )";
1920 //CRM-18457: some custom field passes value in array format against binary operator
1921 if (is_array($value) && count($value)) {
1926 if ($value !== NULL && $value !== '') {
1927 if (isset($field['clause'])) {
1928 // FIXME: we not doing escape here. Better solution is to use two
1929 // different types - data-type and filter-type
1930 $clause = $field['clause'];
1932 elseif (!is_array($value)) {
1933 $value = CRM_Utils_Type
::escape($value, $type);
1934 $sqlOP = $this->getSQLOperator($op);
1935 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1936 $value = "'{$value}'";
1938 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1944 if (!empty($field['group']) && $clause) {
1945 $clause = $this->whereGroupClause($field, $value, $op);
1947 elseif (!empty($field['tag']) && $clause) {
1948 // not using left join in query because if any contact
1949 // belongs to more than one tag, results duplicate
1951 $clause = $this->whereTagClause($field, $value, $op);
1953 elseif (!empty($field['membership_org']) && $clause) {
1954 $clause = $this->whereMembershipOrgClause($value, $op);
1956 elseif (!empty($field['membership_type']) && $clause) {
1957 $clause = $this->whereMembershipTypeClause($value, $op);
1963 * Get SQL where clause for a date field.
1965 * @param string $fieldName
1966 * @param string $relative
1967 * @param string $from
1969 * @param string $type
1970 * @param string $fromTime
1971 * @param string $toTime
1973 * @return null|string
1975 public function dateClause(
1977 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1980 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1981 $sqlOP = $this->getSQLOperator($relative);
1982 return "( {$fieldName} {$sqlOP} )";
1985 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1988 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1989 $clauses[] = "( {$fieldName} >= $from )";
1993 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1994 $clauses[] = "( {$fieldName} <= {$to} )";
1997 if (!empty($clauses)) {
1998 return implode(' AND ', $clauses);
2005 * Get values for from and to for date ranges.
2007 * @param bool $relative
2008 * @param string $from
2010 * @param string $fromTime
2011 * @param string $toTime
2015 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2016 if (empty($toTime)) {
2019 //FIX ME not working for relative
2021 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
2022 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
2023 $from = substr($dateRange['from'], 0, 8);
2024 //Take only Date Part, Sometime Time part is also present in 'to'
2025 $to = substr($dateRange['to'], 0, 8);
2027 $from = CRM_Utils_Date
::processDate($from, $fromTime);
2028 $to = CRM_Utils_Date
::processDate($to, $toTime);
2029 return array($from, $to);
2033 * Alter display of rows.
2035 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2036 * such as rendering contacts as links.
2038 * @param array $rows
2039 * Rows generated by SQL, with an array for each row.
2041 public function alterDisplay(&$rows) {
2045 * Alter the way in which custom data fields are displayed.
2047 * @param array $rows
2049 public function alterCustomDataDisplay(&$rows) {
2050 // custom code to alter rows having custom values
2051 if (empty($this->_customGroupExtends
)) {
2055 $customFieldIds = array();
2056 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2057 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2058 $customFieldIds[$fieldAlias] = $fieldId;
2061 if (empty($customFieldIds)) {
2065 // skip for type date and ContactReference since date format is already handled
2067 SELECT cg.table_name, cf.id
2068 FROM civicrm_custom_field cf
2069 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2070 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2071 cg.is_active = 1 AND
2072 cf.is_active = 1 AND
2073 cf.is_searchable = 1 AND
2074 cf.data_type NOT IN ('ContactReference', 'Date') AND
2075 cf.id IN (" . implode(",", $customFieldIds) . ")";
2077 $dao = CRM_Core_DAO
::executeQuery($query);
2078 while ($dao->fetch()) {
2079 $customFields[$dao->table_name
. '_custom_' . $dao->id
] = $dao->id
;
2083 $entryFound = FALSE;
2084 foreach ($rows as $rowNum => $row) {
2085 foreach ($row as $tableCol => $val) {
2086 if (array_key_exists($tableCol, $customFields)) {
2087 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField
::displayValue($val, $customFields[$tableCol]);
2092 // skip looking further in rows, if first row itself doesn't
2093 // have the column we need
2101 * Remove duplicate rows.
2103 * @param array $rows
2105 public function removeDuplicates(&$rows) {
2106 if (empty($this->_noRepeats
)) {
2109 $checkList = array();
2111 foreach ($rows as $key => $list) {
2112 foreach ($list as $colName => $colVal) {
2113 if (array_key_exists($colName, $checkList) &&
2114 $checkList[$colName] == $colVal
2116 $rows[$key][$colName] = "";
2118 if (in_array($colName, $this->_noRepeats
)) {
2119 $checkList[$colName] = $colVal;
2126 * Fix subtotal display.
2129 * @param array $fields
2130 * @param bool $subtotal
2132 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2133 foreach ($row as $colName => $colVal) {
2134 if (in_array($colName, $fields)) {
2136 elseif (isset($this->_columnHeaders
[$colName])) {
2138 $row[$colName] = ts('Subtotal');
2142 unset($row[$colName]);
2149 * Calculate grant total.
2151 * @param array $rows
2155 public function grandTotal(&$rows) {
2156 if (!$this->_rollup ||
count($rows) == 1) {
2160 $this->moveSummaryColumnsToTheRightHandSide();
2162 if ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
) {
2166 $this->rollupRow
= array_pop($rows);
2168 foreach ($this->_columnHeaders
as $fld => $val) {
2169 if (!in_array($fld, $this->_statFields
)) {
2170 if (!$this->_grandFlag
) {
2171 $this->rollupRow
[$fld] = ts('Grand Total');
2172 $this->_grandFlag
= TRUE;
2175 $this->rollupRow
[$fld] = "";
2180 $this->assign('grandStat', $this->rollupRow
);
2185 * Format display output.
2187 * @param array $rows
2188 * @param bool $pager
2190 public function formatDisplay(&$rows, $pager = TRUE) {
2191 // set pager based on if any limit was applied in the query.
2196 // allow building charts if any
2197 if (!empty($this->_params
['charts']) && !empty($rows)) {
2198 $this->buildChart($rows);
2199 $this->assign('chartEnabled', TRUE);
2200 $this->_chartId
= "{$this->_params['charts']}_" .
2201 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2203 $this->assign('chartId', $this->_chartId
);
2206 // unset columns not to be displayed.
2207 foreach ($this->_columnHeaders
as $key => $value) {
2208 if (!empty($value['no_display'])) {
2209 unset($this->_columnHeaders
[$key]);
2213 // unset columns not to be displayed.
2214 if (!empty($rows)) {
2215 foreach ($this->_noDisplay
as $noDisplayField) {
2216 foreach ($rows as $rowNum => $row) {
2217 unset($this->_columnHeaders
[$noDisplayField]);
2222 // build array of section totals
2223 $this->sectionTotals();
2225 // process grand-total row
2226 $this->grandTotal($rows);
2228 // use this method for formatting rows for display purpose.
2229 $this->alterDisplay($rows);
2230 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2232 // use this method for formatting custom rows for display purpose.
2233 $this->alterCustomDataDisplay($rows);
2239 * @param array $rows
2241 public function buildChart(&$rows) {
2242 // override this method for building charts.
2245 // select() method below has been added recently (v3.3), and many of the report templates might
2246 // still be having their own select() method. We should fix them as and when encountered and move
2247 // towards generalizing the select() method below.
2250 * Generate the SELECT clause and set class variable $_select.
2252 public function select() {
2253 $select = $this->_selectAliases
= array();
2255 foreach ($this->_columns
as $tableName => $table) {
2256 if (array_key_exists('fields', $table)) {
2257 foreach ($table['fields'] as $fieldName => $field) {
2258 if ($tableName == 'civicrm_address') {
2259 $this->_addressField
= TRUE;
2261 if ($tableName == 'civicrm_email') {
2262 $this->_emailField
= TRUE;
2264 if ($tableName == 'civicrm_phone') {
2265 $this->_phoneField
= TRUE;
2268 if (!empty($field['required']) ||
2269 !empty($this->_params
['fields'][$fieldName])
2272 // 1. In many cases we want select clause to be built in slightly different way
2273 // for a particular field of a particular type.
2274 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2276 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2277 if ($selectClause) {
2278 $select[] = $selectClause;
2282 // include statistics columns only if set
2283 if (!empty($field['statistics'])) {
2284 foreach ($field['statistics'] as $stat => $label) {
2285 $alias = "{$tableName}_{$fieldName}_{$stat}";
2286 switch (strtolower($stat)) {
2289 $select[] = "$stat({$field['dbAlias']}) as $alias";
2290 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2291 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2292 $this->_statFields
[$label] = $alias;
2293 $this->_selectAliases
[] = $alias;
2297 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2298 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2299 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2300 $this->_statFields
[$label] = $alias;
2301 $this->_selectAliases
[] = $alias;
2304 case 'count_distinct':
2305 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2306 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2307 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2308 $this->_statFields
[$label] = $alias;
2309 $this->_selectAliases
[] = $alias;
2313 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2314 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2315 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2316 $this->_statFields
[$label] = $alias;
2317 $this->_selectAliases
[] = $alias;
2323 $alias = "{$tableName}_{$fieldName}";
2324 $select[] = "{$field['dbAlias']} as $alias";
2325 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2326 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2327 $this->_selectAliases
[] = $alias;
2333 // select for group bys
2334 if (array_key_exists('group_bys', $table)) {
2335 foreach ($table['group_bys'] as $fieldName => $field) {
2337 if ($tableName == 'civicrm_address') {
2338 $this->_addressField
= TRUE;
2340 if ($tableName == 'civicrm_email') {
2341 $this->_emailField
= TRUE;
2343 if ($tableName == 'civicrm_phone') {
2344 $this->_phoneField
= TRUE;
2346 // 1. In many cases we want select clause to be built in slightly different way
2347 // for a particular field of a particular type.
2348 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2350 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2351 if ($selectClause) {
2352 $select[] = $selectClause;
2356 if (!empty($this->_params
['group_bys']) &&
2357 !empty($this->_params
['group_bys'][$fieldName]) &&
2358 !empty($this->_params
['group_bys_freq'])
2360 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2362 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2363 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2364 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2365 $field['title'] = 'Week';
2369 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2370 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2371 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2372 $field['title'] = 'Year';
2376 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2377 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2378 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2379 $field['title'] = 'Month';
2383 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2384 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2385 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2386 $field['title'] = 'Quarter';
2389 // for graphs and charts -
2390 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2391 $this->_interval
= $field['title'];
2392 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2393 = $field['title'] . ' Beginning';
2394 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2395 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2397 // just to make sure these values are transferred to rows.
2398 // since we 'll need them for calculation purpose,
2399 // e.g making subtotals look nicer or graphs
2400 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2401 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2408 $this->_selectClauses
= $select;
2409 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2413 * Build select clause for a single field.
2415 * @param string $tableName
2416 * @param string $tableKey
2417 * @param string $fieldName
2418 * @param string $field
2422 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2427 * Build where clause.
2429 public function where() {
2430 $this->storeWhereHavingClauseArray();
2432 if (empty($this->_whereClauses
)) {
2433 $this->_where
= "WHERE ( 1 ) ";
2434 $this->_having
= "";
2437 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2440 if ($this->_aclWhere
) {
2441 $this->_where
.= " AND {$this->_aclWhere} ";
2444 if (!empty($this->_havingClauses
)) {
2445 // use this clause to construct group by clause.
2446 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2451 * Store Where clauses into an array.
2453 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2454 * temp table that may not be part of the final where clause or added
2455 * in other functions
2457 public function storeWhereHavingClauseArray() {
2458 foreach ($this->_columns
as $tableName => $table) {
2459 if (array_key_exists('filters', $table)) {
2460 foreach ($table['filters'] as $fieldName => $field) {
2461 // respect pseudofield to filter spec so fields can be marked as
2462 // not to be handled here
2463 if (!empty($field['pseudofield'])) {
2467 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2468 if (CRM_Utils_Array
::value('operatorType', $field) ==
2469 CRM_Report_Form
::OP_MONTH
2471 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2472 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2473 if (is_array($value) && !empty($value)) {
2475 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2480 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2481 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2482 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2483 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2484 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2485 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2489 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2491 $clause = $this->whereClause($field,
2493 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2494 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2495 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2500 if (!empty($clause)) {
2501 if (!empty($field['having'])) {
2502 $this->_havingClauses
[] = $clause;
2505 $this->_whereClauses
[] = $clause;
2517 public function processReportMode() {
2518 $this->setOutputMode();
2521 = CRM_Utils_Request
::retrieve(
2524 CRM_Core_DAO
::$_nullObject
2527 $this->_absoluteUrl
= FALSE;
2529 $this->assign('printOnly', FALSE);
2531 if ($this->_outputMode
== 'print' ||
2532 ($this->_sendmail
&& !$this->_outputMode
)
2534 $this->assign('printOnly', TRUE);
2536 $this->addPaging
= FALSE;
2537 $this->assign('outputMode', 'print');
2538 $this->_outputMode
= 'print';
2539 if ($this->_sendmail
) {
2540 $this->_absoluteUrl
= TRUE;
2543 elseif ($this->_outputMode
== 'pdf') {
2545 $this->addPaging
= FALSE;
2546 $this->_absoluteUrl
= TRUE;
2548 elseif ($this->_outputMode
== 'csv') {
2550 $this->_absoluteUrl
= TRUE;
2551 $this->addPaging
= FALSE;
2553 elseif ($this->_outputMode
== 'group') {
2554 $this->assign('outputMode', 'group');
2556 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2557 $this->assign('outputMode', 'create_report');
2559 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2560 $this->_createNew
= TRUE;
2562 $this->assign('outputMode', $this->_outputMode
);
2564 $this->assign('outputMode', $this->_outputMode
);
2565 $this->assign('printOnly', $printOnly);
2566 // Get today's date to include in printed reports
2568 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2569 $this->assign('reportDate', $reportDate);
2574 * Post Processing function for Form.
2576 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2577 * This function is not accessed when the api calls the report.
2579 public function beginPostProcess() {
2580 $this->setParams($this->controller
->exportValues($this->_name
));
2581 if (empty($this->_params
) &&
2584 $this->setParams($this->_formValues
);
2587 // hack to fix params when submitted from dashboard, CRM-8532
2588 // fields array is missing because form building etc is skipped
2589 // in dashboard mode for report
2590 //@todo - this could be done in the dashboard no we have a setter
2591 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2592 $this->setParams($this->_formValues
);
2595 $this->processReportMode();
2597 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2598 $this->_createNew
= ($this->_outputMode
== 'copy');
2599 CRM_Report_Form_Instance
::postProcess($this);
2601 if ($this->_outputMode
== 'delete') {
2602 CRM_Report_BAO_ReportInstance
::doFormDelete($this->_id
, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
2605 $this->beginPostProcessCommon();
2609 * BeginPostProcess function run in both report mode and non-report mode (api).
2611 public function beginPostProcessCommon() {
2615 * Build the report query.
2617 * @param bool $applyLimit
2621 public function buildQuery($applyLimit = TRUE) {
2624 $this->customDataFrom();
2626 if (array_key_exists('civicrm_contribution', $this->getVar('_columns'))) {
2627 $this->getPermissionedFTQuery($this);
2632 // order_by columns not selected for display need to be included in SELECT
2633 $unselectedSectionColumns = $this->unselectedSectionColumns();
2634 foreach ($unselectedSectionColumns as $alias => $section) {
2635 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2638 if ($applyLimit && empty($this->_params
['charts'])) {
2641 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2643 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2644 $this->addToDeveloperTab($sql);
2649 * Build group by clause.
2651 public function groupBy() {
2652 $groupBys = array();
2653 if (!empty($this->_params
['group_bys']) &&
2654 is_array($this->_params
['group_bys'])
2656 foreach ($this->_columns
as $tableName => $table) {
2657 if (array_key_exists('group_bys', $table)) {
2658 foreach ($table['group_bys'] as $fieldName => $field) {
2659 if (!empty($this->_params
['group_bys'][$fieldName])) {
2660 $groupBys[] = $field['dbAlias'];
2667 if (!empty($groupBys)) {
2668 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBys);
2673 * Build order by clause.
2675 public function orderBy() {
2676 $this->_orderBy
= "";
2677 $this->_sections
= array();
2678 $this->storeOrderByArray();
2679 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2680 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2682 $this->assign('sections', $this->_sections
);
2686 * Extract order by fields and store as an array.
2688 * In some cases other functions want to know which fields are selected for ordering by
2689 * Separating this into a separate function allows it to be called separately from constructing
2690 * the order by clause
2692 public function storeOrderByArray() {
2693 $orderBys = array();
2695 if (!empty($this->_params
['order_bys']) &&
2696 is_array($this->_params
['order_bys']) &&
2697 !empty($this->_params
['order_bys'])
2700 // Process order_bys in user-specified order
2701 foreach ($this->_params
['order_bys'] as $orderBy) {
2702 $orderByField = array();
2703 foreach ($this->_columns
as $tableName => $table) {
2704 if (array_key_exists('order_bys', $table)) {
2705 // For DAO columns defined in $this->_columns
2706 $fields = $table['order_bys'];
2708 elseif (array_key_exists('extends', $table)) {
2709 // For custom fields referenced in $this->_customGroupExtends
2710 $fields = CRM_Utils_Array
::value('fields', $table, array());
2715 if (!empty($fields) && is_array($fields)) {
2716 foreach ($fields as $fieldName => $field) {
2717 if ($fieldName == $orderBy['column']) {
2718 $orderByField = array_merge($field, $orderBy);
2719 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2726 if (!empty($orderByField)) {
2727 $this->_orderByFields
[$orderByField['tplField']] = $orderByField;
2728 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2730 // Record any section headers for assignment to the template
2731 if (!empty($orderBy['section'])) {
2732 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2733 $this->_sections
[$orderByField['tplField']] = $orderByField;
2739 $this->_orderByArray
= $orderBys;
2741 $this->assign('sections', $this->_sections
);
2745 * Determine unselected columns.
2749 public function unselectedSectionColumns() {
2750 if (is_array($this->_sections
)) {
2751 return array_diff_key($this->_sections
, $this->getSelectColumns());
2759 * Build output rows.
2761 * @param string $sql
2762 * @param array $rows
2764 public function buildRows($sql, &$rows) {
2765 $dao = CRM_Core_DAO
::executeQuery($sql);
2766 if (!is_array($rows)) {
2770 // use this method to modify $this->_columnHeaders
2771 $this->modifyColumnHeaders();
2773 $unselectedSectionColumns = $this->unselectedSectionColumns();
2775 while ($dao->fetch()) {
2777 foreach ($this->_columnHeaders
as $key => $value) {
2778 if (property_exists($dao, $key)) {
2779 $row[$key] = $dao->$key;
2783 // section headers not selected for display need to be added to row
2784 foreach ($unselectedSectionColumns as $key => $values) {
2785 if (property_exists($dao, $key)) {
2786 $row[$key] = $dao->$key;
2795 * Calculate section totals.
2797 * When "order by" fields are marked as sections, this assigns to the template
2798 * an array of total counts for each section. This data is used by the Smarty
2799 * plugin {sectionTotal}.
2801 public function sectionTotals() {
2803 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2804 if (empty($this->_selectAliases
)) {
2808 if (!empty($this->_sections
)) {
2809 // build the query with no LIMIT clause
2810 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2811 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2813 // pull section aliases out of $this->_sections
2814 $sectionAliases = array_keys($this->_sections
);
2817 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2818 $ifnulls[] = "ifnull($alias, '') as $alias";
2820 $this->_select
= "SELECT " . implode(", ", $ifnulls);
2821 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
2823 // Group (un-limited) report by all aliases and get counts. This might
2824 // be done more efficiently when the contents of $sql are known, ie. by
2825 // overriding this method in the report class.
2827 $query = $this->_select
.
2828 ", count(*) as ct from ($sql) as subquery group by " .
2829 implode(", ", $sectionAliases);
2831 // initialize array of total counts
2833 $dao = CRM_Core_DAO
::executeQuery($query);
2834 while ($dao->fetch()) {
2836 // let $this->_alterDisplay translate any integer ids to human-readable values.
2837 $rows[0] = $dao->toArray();
2838 $this->alterDisplay($rows);
2841 // add totals for all permutations of section values
2844 $aliasCount = count($sectionAliases);
2845 foreach ($sectionAliases as $alias) {
2846 $values[] = $row[$alias];
2847 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2848 if ($i == $aliasCount) {
2849 // the last alias is the lowest-level section header; use count as-is
2850 $totals[$key] = $dao->ct
;
2853 // other aliases are higher level; roll count into their total
2854 $totals[$key] +
= $dao->ct
;
2858 $this->assign('sectionTotals', $totals);
2863 * Modify column headers.
2865 public function modifyColumnHeaders() {
2866 // use this method to modify $this->_columnHeaders
2870 * Move totals columns to the right edge of the table.
2872 * It seems like a more logical layout to have any totals columns on the far right regardless of
2873 * the location of the rest of their table.
2875 public function moveSummaryColumnsToTheRightHandSide() {
2876 $statHeaders = (array_intersect_key($this->_columnHeaders
, array_flip($this->_statFields
)));
2877 $this->_columnHeaders
= array_merge(array_diff_key($this->_columnHeaders
, $statHeaders), $this->_columnHeaders
, $statHeaders);
2881 * Assign rows to the template.
2883 * @param array $rows
2885 public function doTemplateAssignment(&$rows) {
2886 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2887 $this->assign_by_ref('rows', $rows);
2888 $this->assign('statistics', $this->statistics($rows));
2892 * Build report statistics.
2894 * Override this method to build your own statistics.
2896 * @param array $rows
2900 public function statistics(&$rows) {
2901 $statistics = array();
2903 $count = count($rows);
2904 // Why do we increment the count for rollup seems to artificially inflate the count.
2905 // It seems perhaps intentional to include the summary row in the count of results - although
2906 // this just seems odd.
2907 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2911 $this->countStat($statistics, $count);
2913 $this->groupByStat($statistics);
2915 $this->filterStat($statistics);
2921 * Add count statistics.
2923 * @param array $statistics
2926 public function countStat(&$statistics, $count) {
2927 $statistics['counts']['rowCount'] = array(
2928 'title' => ts('Row(s) Listed'),
2932 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2933 $statistics['counts']['rowsFound'] = array(
2934 'title' => ts('Total Row(s)'),
2935 'value' => $this->_rowsFound
,
2941 * Add group by statistics.
2943 * @param array $statistics
2945 public function groupByStat(&$statistics) {
2946 if (!empty($this->_params
['group_bys']) &&
2947 is_array($this->_params
['group_bys']) &&
2948 !empty($this->_params
['group_bys'])
2950 foreach ($this->_columns
as $tableName => $table) {
2951 if (array_key_exists('group_bys', $table)) {
2952 foreach ($table['group_bys'] as $fieldName => $field) {
2953 if (!empty($this->_params
['group_bys'][$fieldName])) {
2954 $combinations[] = $field['title'];
2959 $statistics['groups'][] = array(
2960 'title' => ts('Grouping(s)'),
2961 'value' => implode(' & ', $combinations),
2967 * Filter statistics.
2969 * @param array $statistics
2971 public function filterStat(&$statistics) {
2972 foreach ($this->_columns
as $tableName => $table) {
2973 if (array_key_exists('filters', $table)) {
2974 foreach ($table['filters'] as $fieldName => $field) {
2975 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
2976 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
2977 CRM_Utils_Array
::value('operatorType', $field) !=
2978 CRM_Report_Form
::OP_MONTH
2982 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2983 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2984 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2985 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2986 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2988 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2989 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2991 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2992 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2995 $statistics['filters'][] = array(
2996 'title' => $field['title'],
2997 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3000 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3001 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3003 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3004 $statistics['filters'][] = array(
3005 'title' => $field['title'],
3006 'value' => $pair[$rel],
3011 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3014 $pair = $this->getOperationPair(
3015 CRM_Utils_Array
::value('operatorType', $field),
3018 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3019 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3020 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3021 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3022 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3024 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3025 $this->setEntityRefDefaults($field, $tableName);
3026 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3027 array('id' => $val) +
3028 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3030 foreach ($result['values'] as $v) {
3031 $values[] = $v['label'];
3033 $value = "{$pair[$op]} " . implode(', ', $values);
3035 elseif ($op == 'nll' ||
$op == 'nnll') {
3036 $value = $pair[$op];
3038 elseif (is_array($val) && (!empty($val))) {
3039 $options = CRM_Utils_Array
::value('options', $field, array());
3040 foreach ($val as $key => $valIds) {
3041 if (isset($options[$valIds])) {
3042 $val[$key] = $options[$valIds];
3045 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3046 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3047 $val = implode(', ', $val);
3048 $value = "{$pair[$op]} " . $val;
3050 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3051 isset($field['options']) &&
3052 is_array($field['options']) && !empty($field['options'])
3054 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3055 CRM_Utils_Array
::value($val, $field['options'], $val);
3058 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3062 $statistics['filters'][] = array(
3063 'title' => CRM_Utils_Array
::value('title', $field),
3074 * End post processing.
3076 * @param array|null $rows
3078 public function endPostProcess(&$rows = NULL) {
3079 if ($this->_storeResultSet
) {
3080 $this->_resultSet
= $rows;
3083 if ($this->_outputMode
== 'print' ||
3084 $this->_outputMode
== 'pdf' ||
3088 $content = $this->compileContent();
3089 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3093 if ($this->_sendmail
) {
3094 $config = CRM_Core_Config
::singleton();
3095 $attachments = array();
3097 if ($this->_outputMode
== 'csv') {
3099 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3100 ": {$url}</p>" . '<p>' .
3101 ts('The report is attached as a CSV file.') . '</p>' .
3102 $this->_formValues
['report_footer'];
3104 $csvFullFilename = $config->templateCompileDir
.
3105 CRM_Utils_File
::makeFileName('CiviReport.csv');
3106 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3107 file_put_contents($csvFullFilename, $csvContent);
3108 $attachments[] = array(
3109 'fullPath' => $csvFullFilename,
3110 'mime_type' => 'text/csv',
3111 'cleanName' => 'CiviReport.csv',
3114 if ($this->_outputMode
== 'pdf') {
3115 // generate PDF content
3116 $pdfFullFilename = $config->templateCompileDir
.
3117 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3118 file_put_contents($pdfFullFilename,
3119 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3120 TRUE, array('orientation' => 'landscape')
3123 // generate Email Content
3125 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3126 ": {$url}</p>" . '<p>' .
3127 ts('The report is attached as a PDF file.') . '</p>' .
3128 $this->_formValues
['report_footer'];
3130 $attachments[] = array(
3131 'fullPath' => $pdfFullFilename,
3132 'mime_type' => 'application/pdf',
3133 'cleanName' => 'CiviReport.pdf',
3137 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3138 $this->_outputMode
, $attachments
3141 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3144 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3148 elseif ($this->_outputMode
== 'print') {
3152 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3153 $config = CRM_Core_Config
::singleton();
3154 //get chart image name
3155 $chartImg = $this->_chartId
. '.png';
3156 //get image url path
3158 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3160 $uploadUrl .= $chartImg;
3161 //get image doc path to overwrite
3163 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3164 'openFlashChart/' . $chartImg;
3166 $chart = imagecreatefrompng($uploadUrl);
3167 //convert it into formatted png
3168 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3169 //overwrite with same image
3170 imagepng($chart, $uploadImg);
3172 imagedestroy($chart);
3174 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3176 CRM_Utils_System
::civiExit();
3178 elseif ($this->_outputMode
== 'csv') {
3179 CRM_Report_Utils_Report
::export2csv($this, $rows);
3181 elseif ($this->_outputMode
== 'group') {
3182 $group = $this->_params
['groups'];
3183 $this->add2group($group);
3188 * Set store result set indicator to TRUE.
3190 * @todo explain what this does
3192 public function storeResultSet() {
3193 $this->_storeResultSet
= TRUE;
3201 public function getResultSet() {
3202 return $this->_resultSet
;
3206 * Get the sql used to generate the report.
3210 public function getReportSql() {
3211 return $this->sqlArray
;
3215 * Use the form name to create the tpl file name.
3219 public function getTemplateFileName() {
3220 $defaultTpl = parent
::getTemplateFileName();
3221 $template = CRM_Core_Smarty
::singleton();
3222 if (!$template->template_exists($defaultTpl)) {
3223 $defaultTpl = 'CRM/Report/Form.tpl';
3229 * Compile the report content.
3231 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3235 public function compileContent() {
3236 $templateFile = $this->getHookedTemplateFileName();
3237 return CRM_Utils_Array
::value('report_header', $this->_formValues
) .
3238 CRM_Core_Form
::$_template->fetch($templateFile) .
3239 CRM_Utils_Array
::value('report_footer', $this->_formValues
);
3244 * Post process function.
3246 public function postProcess() {
3247 // get ready with post process params
3248 $this->beginPostProcess();
3251 $sql = $this->buildQuery();
3253 // build array of result based on column headers. This method also allows
3254 // modifying column headers before using it to build result set i.e $rows.
3256 $this->buildRows($sql, $rows);
3258 // format result set.
3259 $this->formatDisplay($rows);
3261 // assign variables to templates
3262 $this->doTemplateAssignment($rows);
3264 // do print / pdf / instance stuff if needed
3265 $this->endPostProcess($rows);
3271 * @param int $rowCount
3275 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3276 // lets do the pager if in html mode
3277 $this->_limit
= NULL;
3279 // CRM-14115, over-ride row count if rowCount is specified in URL
3280 if ($this->_dashBoardRowCount
) {
3281 $rowCount = $this->_dashBoardRowCount
;
3283 if ($this->addPaging
) {
3284 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3286 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3288 // @todo all http vars should be extracted in the preProcess
3289 // - not randomly in the class
3290 if (!$pageId && !empty($_POST)) {
3291 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3292 $pageId = max((int) $_POST['crmPID_B'], 1);
3294 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3295 $pageId = max((int) $_POST['crmPID'], 1);
3297 unset($_POST['crmPID_B'], $_POST['crmPID']);
3300 $pageId = $pageId ?
$pageId : 1;
3301 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3302 $offset = ($pageId - 1) * $rowCount;
3304 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3305 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3307 $this->_limit
= " LIMIT $offset, $rowCount";
3308 return array($offset, $rowCount);
3310 if ($this->_limitValue
) {
3311 if ($this->_offsetValue
) {
3312 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3315 $this->_limit
= " LIMIT " . $this->_limitValue
;
3323 * @param int $rowCount
3325 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3326 // CRM-14115, over-ride row count if rowCount is specified in URL
3327 if ($this->_dashBoardRowCount
) {
3328 $rowCount = $this->_dashBoardRowCount
;
3331 if ($this->_limit
&& ($this->_limit
!= '')) {
3332 if (!$this->_rowsFound
) {
3333 $sql = "SELECT FOUND_ROWS();";
3334 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3337 'total' => $this->_rowsFound
,
3338 'rowCount' => $rowCount,
3339 'status' => ts('Records') . ' %%StatusMessage%%',
3340 'buttonBottom' => 'PagerBottomButton',
3341 'buttonTop' => 'PagerTopButton',
3343 if (!empty($this->controller
)) {
3344 // This happens when being called from the api Really we want the api to be able to
3345 // pass paging parameters, but at this stage just preventing test crashes.
3346 $params['pageID'] = $this->get(CRM_Utils_Pager
::PAGE_ID
);
3349 $pager = new CRM_Utils_Pager($params);
3350 $this->assign_by_ref('pager', $pager);
3351 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3356 * Build where clause for groups.
3358 * @param string $field
3359 * @param mixed $value
3364 public function whereGroupClause($field, $value, $op) {
3366 $smartGroupQuery = "";
3368 $group = new CRM_Contact_DAO_Group();
3369 $group->is_active
= 1;
3371 $smartGroups = array();
3372 while ($group->fetch()) {
3373 if (in_array($group->id
, $this->_params
['gid_value']) &&
3374 $group->saved_search_id
3376 $smartGroups[] = $group->id
;
3380 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3382 $smartGroupQuery = '';
3383 if (!empty($smartGroups)) {
3384 $smartGroups = implode(',', $smartGroups);
3385 $smartGroupQuery = " UNION DISTINCT
3386 SELECT DISTINCT smartgroup_contact.contact_id
3387 FROM civicrm_group_contact_cache smartgroup_contact
3388 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3391 $sqlOp = $this->getSQLOperator($op);
3392 if (!is_array($value)) {
3393 $value = array($value);
3395 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3397 $contactAlias = $this->_aliases
['civicrm_contact'];
3398 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3399 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3401 return " {$contactAlias}.id {$sqlOp} (
3402 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3403 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3404 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3405 {$smartGroupQuery} ) ";
3409 * Build where clause for tags.
3411 * @param string $field
3412 * @param mixed $value
3417 public function whereTagClause($field, $value, $op) {
3418 // not using left join in query because if any contact
3419 // belongs to more than one tag, results duplicate
3421 $sqlOp = $this->getSQLOperator($op);
3422 if (!is_array($value)) {
3423 $value = array($value);
3425 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3426 $entity_table = $this->_tagFilterTable
;
3427 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3428 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3429 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3430 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3434 * Generate membership organization clause.
3436 * @param mixed $value
3437 * @param string $op SQL Operator
3441 public function whereMembershipOrgClause($value, $op) {
3442 $sqlOp = $this->getSQLOperator($op);
3443 if (!is_array($value)) {
3444 $value = array($value);
3447 $tmp_membership_org_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 mt.member_of_contact_id IN (" .
3454 $tmp_membership_org_sql_list . ")
3455 AND mt.is_active = '1'
3456 AND mem_status.is_current_member = '1'
3457 AND mem_status.is_active = '1' ) ";
3461 * Generate Membership Type SQL Clause.
3463 * @param mixed $value
3469 public function whereMembershipTypeClause($value, $op) {
3470 $sqlOp = $this->getSQLOperator($op);
3471 if (!is_array($value)) {
3472 $value = array($value);
3475 $tmp_membership_sql_list = implode(', ', $value);
3476 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3477 SELECT DISTINCT mem.contact_id
3478 FROM civicrm_membership mem
3479 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3480 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3481 WHERE mem.membership_type_id IN (" .
3482 $tmp_membership_sql_list . ")
3483 AND mt.is_active = '1'
3484 AND mem_status.is_current_member = '1'
3485 AND mem_status.is_active = '1' ) ";
3489 * Build acl clauses.
3491 * @param string $tableAlias
3493 public function buildACLClause($tableAlias = 'contact_a') {
3494 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3498 * Add custom data to the columns.
3500 * @param bool $addFields
3501 * @param array $permCustomGroupIds
3503 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3504 if (empty($this->_customGroupExtends
)) {
3507 if (!is_array($this->_customGroupExtends
)) {
3508 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3510 $customGroupWhere = '';
3511 if (!empty($permCustomGroupIds)) {
3512 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3516 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3517 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3518 FROM civicrm_custom_group cg
3519 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3520 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3522 cg.is_active = 1 AND
3523 cf.is_active = 1 AND
3524 cf.is_searchable = 1
3525 ORDER BY cg.weight, cf.weight";
3526 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3529 while ($customDAO->fetch()) {
3530 if ($customDAO->table_name
!= $curTable) {
3531 $curTable = $customDAO->table_name
;
3532 $curFields = $curFilters = array();
3535 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3536 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3537 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3538 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3540 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3541 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3542 $this->_columns
[$curTable][$colKey] = array();
3546 $fieldName = 'custom_' . $customDAO->cf_id
;
3549 // this makes aliasing work in favor
3550 $curFields[$fieldName] = array(
3551 'name' => $customDAO->column_name
,
3552 'title' => $customDAO->label
,
3553 'dataType' => $customDAO->data_type
,
3554 'htmlType' => $customDAO->html_type
,
3557 if ($this->_customGroupFilters
) {
3558 // this makes aliasing work in favor
3559 $curFilters[$fieldName] = array(
3560 'name' => $customDAO->column_name
,
3561 'title' => $customDAO->label
,
3562 'dataType' => $customDAO->data_type
,
3563 'htmlType' => $customDAO->html_type
,
3567 switch ($customDAO->data_type
) {
3570 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3571 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3572 // CRM-6946, show time part for datetime date fields
3573 if ($customDAO->time_format
) {
3574 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3579 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3580 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3581 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3585 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3586 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3590 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3591 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3592 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3596 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3597 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3601 case 'StateProvince':
3603 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3605 $options = CRM_Core_PseudoConstant
::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id
, array(), 'search');
3606 if ($options !== FALSE) {
3607 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField
::isSerialized($customDAO) ? CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
: CRM_Report_Form
::OP_MULTISELECT
;
3608 $curFilters[$fieldName]['options'] = $options;
3612 case 'ContactReference':
3613 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3614 $curFilters[$fieldName]['name'] = 'display_name';
3615 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3617 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3618 $curFields[$fieldName]['name'] = 'display_name';
3619 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3623 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3624 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3627 if (!array_key_exists('type', $curFields[$fieldName])) {
3628 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3632 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3634 if ($this->_customGroupFilters
) {
3635 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3637 if ($this->_customGroupGroupBy
) {
3638 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3644 * Build custom data from clause.
3646 * @param bool $joinsForFiltersOnly
3647 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3649 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3650 if (empty($this->_customGroupExtends
)) {
3653 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3654 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3655 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3656 $customTables = array();
3657 $customTablesDAO = CRM_Core_DAO
::executeQuery("SELECT table_name FROM civicrm_custom_group");
3658 while ($customTablesDAO->fetch()) {
3659 $customTables[] = $customTablesDAO->table_name
;
3662 foreach ($this->_columns
as $table => $prop) {
3663 if (in_array($table, $customTables)) {
3664 $extendsTable = $mapper[$prop['extends']];
3665 // Check field is required for rendering the report.
3666 if ((!$this->isFieldSelected($prop)) ||
($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3669 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3671 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3673 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3674 // handle for ContactReference
3675 if (array_key_exists('fields', $prop)) {
3676 foreach ($prop['fields'] as $fieldName => $field) {
3677 if (CRM_Utils_Array
::value('dataType', $field) ==
3680 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3682 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3691 * Check if the field is selected.
3693 * @param string $prop
3697 public function isFieldSelected($prop) {
3702 if (!empty($this->_params
['fields'])) {
3703 foreach (array_keys($prop['fields']) as $fieldAlias) {
3704 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3705 if ($customFieldId) {
3706 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3710 //might be survey response field.
3711 if (!empty($this->_params
['fields']['survey_response']) &&
3712 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3720 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3721 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3722 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3723 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3730 if (!empty($this->_params
['order_bys'])) {
3731 foreach (array_keys($prop['fields']) as $fieldAlias) {
3732 foreach ($this->_params
['order_bys'] as $orderBy) {
3733 if ($fieldAlias == $orderBy['column'] &&
3734 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3741 return $this->isFieldFiltered($prop);
3746 * Check if the field is used as a filter.
3748 * @param string $prop
3752 protected function isFieldFiltered($prop) {
3753 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3754 foreach ($prop['filters'] as $fieldAlias => $val) {
3763 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3764 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3765 ||
($attach != 'relative' &&
3766 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3772 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3773 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3784 * Check for empty order_by configurations and remove them.
3786 * Also set template to hide them.
3788 * @param array $formValues
3790 public function preProcessOrderBy(&$formValues) {
3791 // Object to show/hide form elements
3792 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3794 $_showHide->addShow('optionField_1');
3796 // Cycle through order_by options; skip any empty ones, and hide them as well
3799 if (!empty($formValues['order_bys'])) {
3800 foreach ($formValues['order_bys'] as $order_by) {
3801 if ($order_by['column'] && $order_by['column'] != '-') {
3802 $_showHide->addShow('optionField_' . $n);
3803 $orderBys[$n] = $order_by;
3808 for ($i = $n; $i <= 5; $i++
) {
3810 $_showHide->addHide('optionField_' . $i);
3814 // overwrite order_by options with modified values
3815 if (!empty($orderBys)) {
3816 $formValues['order_bys'] = $orderBys;
3819 $formValues['order_bys'] = array(1 => array('column' => '-'));
3822 // assign show/hide data to template
3823 $_showHide->addToTemplate();
3827 * Check if table name has columns in SELECT clause.
3829 * @param string $tableName
3830 * Name of table (index of $this->_columns array).
3834 public function isTableSelected($tableName) {
3835 return in_array($tableName, $this->selectedTables());
3839 * Check if table name has columns in WHERE or HAVING clause.
3841 * @param string $tableName
3842 * Name of table (index of $this->_columns array).
3846 public function isTableFiltered($tableName) {
3847 // Cause the array to be generated if not previously done.
3848 if (!$this->_selectedTables
&& !$this->filteredTables
) {
3849 $this->selectedTables();
3851 return in_array($tableName, $this->filteredTables
);
3855 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3857 * If the array is unset it will be built.
3862 public function selectedTables() {
3863 if (!$this->_selectedTables
) {
3864 $orderByColumns = array();
3865 if (array_key_exists('order_bys', $this->_params
) &&
3866 is_array($this->_params
['order_bys'])
3868 foreach ($this->_params
['order_bys'] as $orderBy) {
3869 $orderByColumns[] = $orderBy['column'];
3873 foreach ($this->_columns
as $tableName => $table) {
3874 if (array_key_exists('fields', $table)) {
3875 foreach ($table['fields'] as $fieldName => $field) {
3876 if (!empty($field['required']) ||
3877 !empty($this->_params
['fields'][$fieldName])
3879 $this->_selectedTables
[] = $tableName;
3884 if (array_key_exists('order_bys', $table)) {
3885 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3886 if (in_array($orderByName, $orderByColumns)) {
3887 $this->_selectedTables
[] = $tableName;
3892 if (array_key_exists('filters', $table)) {
3893 foreach ($table['filters'] as $filterName => $filter) {
3894 if (!empty($this->_params
["{$filterName}_value"]) ||
3895 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3897 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3900 $this->_selectedTables
[] = $tableName;
3901 $this->filteredTables
[] = $tableName;
3908 return $this->_selectedTables
;
3912 * Add address fields.
3914 * @deprecated - use getAddressColumns which is a more accurate description
3915 * and also accepts an array of options rather than a long list
3917 * adding address fields to construct function in reports
3919 * @param bool $groupBy
3920 * Add GroupBy? Not appropriate for detail report.
3921 * @param bool $orderBy
3922 * Add GroupBy? Not appropriate for detail report.
3923 * @param bool $filters
3924 * @param array $defaults
3927 * address fields for construct clause
3929 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3930 $addressFields = array(
3931 'civicrm_address' => array(
3932 'dao' => 'CRM_Core_DAO_Address',
3934 'address_name' => array(
3935 'title' => ts('Address Name'),
3936 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3939 'street_address' => array(
3940 'title' => ts('Street Address'),
3941 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3943 'supplemental_address_1' => array(
3944 'title' => ts('Supplementary Address Field 1'),
3945 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3947 'supplemental_address_2' => array(
3948 'title' => ts('Supplementary Address Field 2'),
3949 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3951 'street_number' => array(
3952 'name' => 'street_number',
3953 'title' => ts('Street Number'),
3955 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3957 'street_name' => array(
3958 'name' => 'street_name',
3959 'title' => ts('Street Name'),
3961 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3963 'street_unit' => array(
3964 'name' => 'street_unit',
3965 'title' => ts('Street Unit'),
3967 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3970 'title' => ts('City'),
3971 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3973 'postal_code' => array(
3974 'title' => ts('Postal Code'),
3975 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3977 'postal_code_suffix' => array(
3978 'title' => ts('Postal Code Suffix'),
3979 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3981 'country_id' => array(
3982 'title' => ts('Country'),
3983 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3985 'state_province_id' => array(
3986 'title' => ts('State/Province'),
3987 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3989 'county_id' => array(
3990 'title' => ts('County'),
3991 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3994 'grouping' => 'location-fields',
3999 // Address filter depends on whether street address parsing is enabled.
4001 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
4004 if ($addressOptions['street_address_parsing']) {
4005 $street_address_filters = array(
4006 'street_number' => array(
4007 'title' => ts('Street Number'),
4009 'name' => 'street_number',
4011 'street_name' => array(
4012 'title' => ts('Street Name'),
4013 'name' => 'street_name',
4014 'operator' => 'like',
4019 $street_address_filters = array(
4020 'street_address' => array(
4021 'title' => ts('Street Address'),
4022 'operator' => 'like',
4023 'name' => 'street_address',
4027 $general_address_filters = array(
4028 'postal_code' => array(
4029 'title' => ts('Postal Code'),
4031 'name' => 'postal_code',
4034 'title' => ts('City'),
4035 'operator' => 'like',
4038 'country_id' => array(
4039 'name' => 'country_id',
4040 'title' => ts('Country'),
4041 'type' => CRM_Utils_Type
::T_INT
,
4042 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4043 'options' => CRM_Core_PseudoConstant
::country(),
4045 'state_province_id' => array(
4046 'name' => 'state_province_id',
4047 'title' => ts('State/Province'),
4048 'type' => CRM_Utils_Type
::T_INT
,
4049 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4050 'options' => array(),
4052 'county_id' => array(
4053 'name' => 'county_id',
4054 'title' => ts('County'),
4055 'type' => CRM_Utils_Type
::T_INT
,
4056 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4057 'options' => array(),
4061 $addressFields['civicrm_address']['filters'] = array_merge(
4062 $street_address_filters,
4063 $general_address_filters);
4066 $addressFields['civicrm_address']['order_bys'] = array(
4067 'street_name' => array('title' => ts('Street Name')),
4068 'street_number' => array('title' => ts('Odd / Even Street Number')),
4069 'street_address' => NULL,
4071 'postal_code' => NULL,
4076 $addressFields['civicrm_address']['group_bys'] = array(
4077 'street_address' => NULL,
4079 'postal_code' => NULL,
4080 'state_province_id' => array(
4081 'title' => ts('State/Province'),
4083 'country_id' => array(
4084 'title' => ts('Country'),
4086 'county_id' => array(
4087 'title' => ts('County'),
4091 return $addressFields;
4095 * Do AlterDisplay processing on Address Fields.
4098 * @param array $rows
4099 * @param int $rowNum
4100 * @param string $baseUrl
4101 * @param string $linkText
4105 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4106 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4107 $entryFound = FALSE;
4109 if (array_key_exists('civicrm_address_country_id', $row)) {
4110 if ($value = $row['civicrm_address_country_id']) {
4111 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4113 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4114 "reset=1&force=1&{$criteriaQueryParams}&" .
4115 "country_id_op=in&country_id_value={$value}",
4116 $this->_absoluteUrl
, $this->_id
4118 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4119 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4120 array(1 => $linkText)
4127 if (array_key_exists('civicrm_address_county_id', $row)) {
4128 if ($value = $row['civicrm_address_county_id']) {
4129 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4131 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4132 "reset=1&force=1&{$criteriaQueryParams}&" .
4133 "county_id_op=in&county_id_value={$value}",
4134 $this->_absoluteUrl
, $this->_id
4136 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4137 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4138 array(1 => $linkText)
4144 // handle state province
4145 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4146 if ($value = $row['civicrm_address_state_province_id']) {
4147 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4149 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4150 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4151 $this->_absoluteUrl
, $this->_id
4153 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4154 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4155 array(1 => $linkText)
4166 * Do AlterDisplay processing on Address Fields.
4169 * @param array $rows
4170 * @param int $rowNum
4171 * @param string $baseUrl
4172 * @param string $linkText
4176 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4177 $entryFound = FALSE;
4178 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4179 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4180 $addLinks = array('gender_id' => 'Gender');
4181 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4182 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4183 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4184 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4185 if ($baseUrl && ($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4186 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4192 $yesNoFields = array(
4193 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4195 foreach ($yesNoFields as $fieldName) {
4196 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4197 // Since these are essentially 'negative fields' it feels like it
4198 // makes sense to only highlight the exceptions hence no 'No'.
4199 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ?
ts('Yes') : '';
4207 * Adjusts dates passed in to YEAR() for fiscal year.
4209 * @param string $fieldName
4213 public function fiscalYearOffset($fieldName) {
4214 $config = CRM_Core_Config
::singleton();
4215 $fy = $config->fiscalYearStart
;
4216 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4217 ($fy['d'] == 1 && $fy['M'] == 1)
4219 return "YEAR( $fieldName )";
4221 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4222 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4226 * Add Address into From Table if required.
4228 public function addAddressFromClause() {
4229 // include address field if address column is to be included
4230 if ((isset($this->_addressField
) &&
4231 $this->_addressField
4233 $this->isTableSelected('civicrm_address')
4236 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4237 ON ({$this->_aliases['civicrm_contact']}.id =
4238 {$this->_aliases['civicrm_address']}.contact_id) AND
4239 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4244 * Add Phone into From Table if required.
4246 public function addPhoneFromClause() {
4247 // include address field if address column is to be included
4248 if ($this->isTableSelected('civicrm_phone')
4251 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4252 ON ({$this->_aliases['civicrm_contact']}.id =
4253 {$this->_aliases['civicrm_phone']}.contact_id) AND
4254 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4259 * Get phone columns to add to array.
4261 * @param array $options
4262 * - prefix Prefix to add to table (in case of more than one instance of the table)
4263 * - prefix_label Label to give columns from this phone table instance
4266 * phone columns definition
4268 public function getPhoneColumns($options = array()) {
4269 $defaultOptions = array(
4271 'prefix_label' => '',
4274 $options = array_merge($defaultOptions, $options);
4277 $options['prefix'] . 'civicrm_phone' => array(
4278 'dao' => 'CRM_Core_DAO_Phone',
4280 $options['prefix'] . 'phone' => array(
4281 'title' => ts($options['prefix_label'] . 'Phone'),
4291 * Get address columns to add to array.
4293 * @param array $options
4294 * - prefix Prefix to add to table (in case of more than one instance of the table)
4295 * - prefix_label Label to give columns from this address table instance
4298 * address columns definition
4300 public function getAddressColumns($options = array()) {
4303 'prefix_label' => '',
4307 'defaults' => array(),
4309 return $this->addAddressFields(
4310 $options['group_by'],
4311 $options['order_by'],
4312 $options['filters'],
4313 $options['defaults']
4318 * Get a standard set of contact fields.
4322 public function getBasicContactFields() {
4324 'sort_name' => array(
4325 'title' => ts('Contact Name'),
4330 'no_display' => TRUE,
4333 'prefix_id' => array(
4334 'title' => ts('Contact Prefix'),
4336 'first_name' => array(
4337 'title' => ts('First Name'),
4339 'nick_name' => array(
4340 'title' => ts('Nick Name'),
4342 'middle_name' => array(
4343 'title' => ts('Middle Name'),
4345 'last_name' => array(
4346 'title' => ts('Last Name'),
4348 'suffix_id' => array(
4349 'title' => ts('Contact Suffix'),
4351 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4352 'email_greeting_display' => array('title' => ts('Email Greeting')),
4353 'addressee_display' => array('title' => ts('Addressee')),
4354 'contact_type' => array(
4355 'title' => ts('Contact Type'),
4357 'contact_sub_type' => array(
4358 'title' => ts('Contact Subtype'),
4360 'gender_id' => array(
4361 'title' => ts('Gender'),
4363 'birth_date' => array(
4364 'title' => ts('Birth Date'),
4367 'title' => ts('Age'),
4368 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4370 'job_title' => array(
4371 'title' => ts('Contact Job title'),
4373 'organization_name' => array(
4374 'title' => ts('Organization Name'),
4376 'external_identifier' => array(
4377 'title' => ts('Contact identifier from external system'),
4379 'do_not_email' => array(),
4380 'do_not_phone' => array(),
4381 'do_not_mail' => array(),
4382 'do_not_sms' => array(),
4383 'is_opt_out' => array(),
4384 'is_deceased' => array(),
4389 * Get a standard set of contact filters.
4393 public function getBasicContactFilters() {
4395 'sort_name' => array(
4396 'title' => ts('Contact Name'),
4399 'title' => ts('Contact Source'),
4400 'type' => CRM_Utils_Type
::T_STRING
,
4403 'title' => ts('Contact ID'),
4404 'no_display' => TRUE,
4406 'gender_id' => array(
4407 'title' => ts('Gender'),
4408 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4409 'options' => CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'),
4411 'birth_date' => array(
4412 'title' => ts('Birth Date'),
4413 'operatorType' => CRM_Report_Form
::OP_DATE
,
4415 'contact_type' => array(
4416 'title' => ts('Contact Type'),
4418 'contact_sub_type' => array(
4419 'title' => ts('Contact Subtype'),
4421 'modified_date' => array(
4422 'title' => ts('Contact Modified'),
4423 'operatorType' => CRM_Report_Form
::OP_DATE
,
4424 'type' => CRM_Utils_Type
::T_DATE
,
4426 'is_deceased' => array(
4427 'title' => ts('Deceased'),
4428 'type' => CRM_Utils_Type
::T_BOOLEAN
,
4435 * Add contact to group.
4437 * @param int $groupID
4439 public function add2group($groupID) {
4440 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4441 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4443 // here are we are prepending / adding contact id field that could be used for adding group
4444 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4445 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select
)) {
4446 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4449 $select = str_ireplace('SELECT ', $select, $this->_select
);
4452 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4453 $sql = str_replace('WITH ROLLUP', '', $sql);
4454 $dao = CRM_Core_DAO
::executeQuery($sql);
4456 $contact_ids = array();
4457 // Add resulting contacts to group
4458 while ($dao->fetch()) {
4459 if ($dao->addtogroup_contact_id
) {
4460 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4464 if (!empty($contact_ids)) {
4465 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4466 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4469 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4475 * Show charts on print screen.
4477 public static function uploadChartImage() {
4478 // upload strictly for '.png' images
4479 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4480 if (preg_match('/\.png$/', $name)) {
4482 // POST data is usually string data, but we are passing a RAW .png
4483 // so PHP is a bit confused and $_POST is empty. But it has saved
4484 // the raw bits into $HTTP_RAW_POST_DATA
4486 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4488 // prepare the directory
4489 $config = CRM_Core_Config
::singleton();
4491 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4493 if (!file_exists($defaultPath)) {
4494 mkdir($defaultPath, 0777, TRUE);
4497 // full path to the saved image including filename
4498 $destination = $defaultPath . $name;
4501 $jfh = fopen($destination, 'w') or die("can't open file");
4502 fwrite($jfh, $httpRawPostData);
4504 CRM_Utils_System
::civiExit();
4509 * Apply common settings to entityRef fields.
4511 * @param array $field
4512 * @param string $table
4514 private function setEntityRefDefaults(&$field, $table) {
4515 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4516 $field['attributes'] +
= array(
4517 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4519 'placeholder' => ts('- select -'),
4524 * Add link fields to the row.
4526 * Function adds the _link & _hover fields to the row.
4529 * @param string $baseUrl
4530 * @param string $linkText
4531 * @param string $value
4532 * @param string $fieldName
4533 * @param string $tablePrefix
4534 * @param string $fieldLabel
4538 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4539 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4540 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4541 "reset=1&force=1&{$criteriaQueryParams}&" .
4542 $fieldName . "_op=in&{$fieldName}_value={$value}",
4543 $this->_absoluteUrl
, $this->_id
4545 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4546 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4547 array(1 => $linkText, 2 => $fieldLabel)
4552 * Generate temporary table to hold all contributions with permissioned FTs.
4554 * @param object $query
4555 * @param string $alias
4556 * @param bool $return
4558 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4559 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4562 $financialTypes = NULL;
4563 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4564 if (empty($financialTypes)) {
4566 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4569 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4571 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4573 $query->_aliases
['civicrm_line_item'] = $alias;
4576 $query->_aliases
['civicrm_line_item'] = 'civicrm_line_item_civireport';
4578 if (empty($query->_where
)) {
4579 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4581 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4582 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4583 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4584 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4585 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4586 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4588 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4589 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4590 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4591 CRM_Core_DAO
::executeQuery($sql);
4593 $query->_aliases
['civicrm_line_item'] = $temp;
4595 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4599 $query->_from
.= $from;
4603 * Get label for show results buttons.
4607 public function getResultsLabel() {
4608 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4609 return $showResultsLabel;
4613 * Determine the output mode from the url or input.
4616 * - pdf : Render as pdf
4617 * - csv : Render as csv
4618 * - print : Render in print format
4619 * - save : save the report and display the new report
4620 * - copy : save the report as a new instance and display that.
4621 * - group : go to the add to group screen.
4623 * Potentially chart variations could also be included but the complexity
4624 * is that we might print a bar chart as a pdf.
4626 protected function setOutputMode() {
4627 $this->_outputMode
= str_replace('report_instance.', '', CRM_Utils_Request
::retrieve(
4630 CRM_Core_DAO
::$_nullObject,
4632 CRM_Utils_Array
::value('task', $this->_params
)
4634 // if contacts are added to group
4635 if (!empty($this->_params
['groups']) && empty($this->_outputMode
)) {
4636 $this->_outputMode
= 'group';
4638 if (isset($this->_params
['task'])) {
4639 unset($this->_params
['task']);
4644 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4647 * @param $columnName
4649 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4650 // add new column with date value for the datetime field
4651 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4652 CRM_Core_DAO
::executeQuery($tempQuery);
4653 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4654 CRM_Core_DAO
::executeQuery($updateQuery);
4655 $this->_selectClauses
[] = "{$columnName}_date";
4656 $this->_select
.= ", {$columnName}_date";
4657 $this->_sections
["{$columnName}_date"] = $this->_sections
["{$columnName}"];
4658 unset($this->_sections
["{$columnName}"]);
4659 $this->assign('sections', $this->_sections
);
4663 * Get an array of the columns that have been selected for display.
4667 public function getSelectColumns() {
4668 $selectColumns = array();
4669 foreach ($this->_columns
as $tableName => $table) {
4670 if (array_key_exists('fields', $table)) {
4671 foreach ($table['fields'] as $fieldName => $field) {
4672 if (!empty($field['required']) ||
4673 !empty($this->_params
['fields'][$fieldName])
4676 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4681 return $selectColumns;
4685 * Add location tables to the query if they are used for filtering.
4687 * This is for when we are running the query separately for filtering and retrieving display fields.
4689 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4690 if ($this->isTableFiltered('civicrm_email')) {
4692 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4693 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4694 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4696 if ($this->isTableFiltered('civicrm_phone')) {
4698 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4699 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4700 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4702 if ($this->isTableFiltered('civicrm_address')) {
4704 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4705 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4706 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";