3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 protected $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * Array of tabs to display on report.
167 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
169 * $this->tabs['OrderBy'] = array(
170 * 'title' => ts('Sorting'),
171 * 'tpl' => 'OrderBy',
172 * 'div_label' => 'order-by',
177 protected $tabs = array();
180 * An attribute for checkbox/radio form field layout
184 protected $_fourColumnAttribute = array(
185 '</td><td width="25%">',
186 '</td><td width="25%">',
187 '</td><td width="25%">',
191 protected $_force = 1;
193 protected $_params = NULL;
194 protected $_formValues = NULL;
195 protected $_instanceValues = NULL;
197 protected $_instanceForm = FALSE;
198 protected $_criteriaForm = FALSE;
200 protected $_instanceButtonName = NULL;
201 protected $_createNewButtonName = NULL;
202 protected $_printButtonName = NULL;
203 protected $_pdfButtonName = NULL;
204 protected $_csvButtonName = NULL;
205 protected $_groupButtonName = NULL;
206 protected $_chartButtonName = NULL;
207 protected $_csvSupported = TRUE;
208 protected $_add2groupSupported = TRUE;
209 protected $_groups = NULL;
210 protected $_grandFlag = FALSE;
211 protected $_rowsFound = NULL;
212 protected $_selectAliases = array();
213 protected $_rollup = NULL;
218 protected $_aliases = array();
234 protected $_limit = NULL;
237 * This can be set to specify a limit to the number of rows
238 * Since it is currently envisaged as part of the api usage it is only being applied
239 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
240 * of the code (see limit() fn
243 protected $_limitValue = NULL;
246 * This can be set to specify row offset
247 * See notes on _limitValue
250 protected $_offsetValue = NULL;
254 protected $_sections = NULL;
255 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
256 protected $_absoluteUrl = FALSE;
259 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
263 protected $_storeResultSet = FALSE;
266 * When _storeResultSet Flag is set use this var to store result set in form of array
270 protected $_resultSet = array();
273 * To what frequency group-by a date column
277 protected $_groupByDateFreq = array(
279 'YEARWEEK' => 'Week',
280 'QUARTER' => 'Quarter',
285 * Variables to hold the acl inner join and where clause
287 protected $_aclFrom = NULL;
288 protected $_aclWhere = NULL;
291 * Array of DAO tables having columns included in SELECT or ORDER BY clause
295 protected $_selectedTables;
298 * Output mode e.g 'print', 'csv', 'pdf'.
302 protected $_outputMode;
305 * Format of any chart in use.
307 * (it's unclear if this could be merged with outputMode at this stage)
313 public $_having = NULL;
314 public $_select = NULL;
315 public $_selectClauses = array();
316 public $_columnHeaders = array();
317 public $_orderBy = NULL;
318 public $_orderByFields = array();
319 public $_orderByArray = array();
320 public $_groupBy = NULL;
321 public $_whereClauses = array();
322 public $_havingClauses = array();
325 * DashBoardRowCount Dashboard row count
328 public $_dashBoardRowCount;
331 * Is this being called without a form controller (ie. the report is being render outside the normal form
332 * - e.g the api is retrieving the rows
335 public $noController = FALSE;
338 * Variable to hold the currency alias
340 protected $_currencyColumn = NULL;
345 protected $_interval;
350 protected $_sendmail;
363 * @var string Report description.
365 public $_description;
368 * @var bool Is an address field selected.
369 * This was intended to determine if the address table should be joined in
370 * The isTableSelected function is now preferred for this purpose
372 protected $_addressField;
375 * @var bool Is an email field selected.
376 * This was intended to determine if the email table should be joined in
377 * The isTableSelected function is now preferred for this purpose
379 protected $_emailField;
382 * @var bool Is a phone field selected.
383 * This was intended to determine if the phone table should be joined in
384 * The isTableSelected function is now preferred for this purpose
386 protected $_phoneField;
389 * @var bool Create new report instance? (or update existing) on save.
391 protected $_createNew;
394 * SQL being run in this report.
396 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
405 public function __construct() {
406 parent
::__construct();
408 $this->addClass('crm-report-form');
410 if ($this->_tagFilter
) {
411 $this->buildTagFilter();
413 if ($this->_exposeContactID
) {
414 if (array_key_exists('civicrm_contact', $this->_columns
)) {
415 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
417 'title' => 'Contact ID',
423 if ($this->_groupFilter
) {
424 $this->buildGroupFilter();
427 // Get all custom groups
428 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
430 // Get the custom groupIds for which the user has VIEW permission
431 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
432 // and addCustomDataToColumns() will allow access to all custom groups.
433 $permCustomGroupIds = array();
434 if (!CRM_Core_Permission
::check('access all custom data')) {
435 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
436 // do not allow custom data for reports if user doesn't have
437 // permission to access custom data.
438 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
439 $this->_customGroupExtends
= array();
443 // merge custom data columns to _columns list, if any
444 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
446 // add / modify display columns, filters ..etc
447 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
449 //assign currencyColumn variable to tpl
450 $this->assign('currencyColumn', $this->_currencyColumn
);
454 * Shared pre-process function.
456 * If overriding preProcess function this should still be called.
460 public function preProcessCommon() {
462 = CRM_Utils_Request
::retrieve(
465 CRM_Core_DAO
::$_nullObject
468 $this->_dashBoardRowCount
469 = CRM_Utils_Request
::retrieve(
472 CRM_Core_DAO
::$_nullObject
475 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
477 $this->assign('section', $this->_section
);
478 CRM_Core_Region
::instance('page-header')->add(array(
479 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
481 if (!$this->noController
) {
482 $this->setID($this->get('instanceId'));
485 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
487 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
491 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
492 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
493 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
497 $this->assign('instanceId', $this->_id
);
498 $params = array('id' => $this->_id
);
499 $this->_instanceValues
= array();
500 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
502 $this->_instanceValues
504 if (empty($this->_instanceValues
)) {
505 CRM_Core_Error
::fatal("Report could not be loaded.");
507 $this->_title
= $this->_instanceValues
['title'];
508 if (!empty($this->_instanceValues
['permission']) &&
509 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
510 CRM_Core_Permission
::check('administer Reports')
513 CRM_Utils_System
::permissionDenied();
514 CRM_Utils_System
::civiExit();
517 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
519 $this->_formValues
= unserialize($formValues);
522 $this->_formValues
= NULL;
525 // lets always do a force if reset is found in the url.
526 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
527 // in the comment line above these 2.
528 if (!empty($_REQUEST['reset']) && CRM_Utils_Request
::retrieve('output', 'String') != 'criteria'
529 && CRM_Utils_Request
::retrieve('output', 'String') != 'save') {
534 $this->assign('mode', 'instance');
536 elseif (!$this->noController
) {
537 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
538 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
539 if (($instanceCount > 0) && $optionValueID) {
540 $this->assign('instanceUrl',
541 CRM_Utils_System
::url('civicrm/report/list',
542 "reset=1&ovid=$optionValueID"
546 if ($optionValueID) {
547 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
551 $this->assign('mode', 'template');
554 // lets display the Report Settings section
555 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
557 // Do not display Report Settings section if administer Reports permission is absent OR
558 // if report instance is reserved and administer reserved reports absent
559 if (!CRM_Core_Permission
::check('administer Reports') ||
560 ($this->_instanceValues
['is_reserved'] &&
561 !CRM_Core_Permission
::check('administer reserved reports'))
563 $this->_instanceForm
= FALSE;
566 $this->assign('criteriaForm', FALSE);
567 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
568 if (CRM_Core_Permission
::check('administer Reports') ||
569 CRM_Core_Permission
::check('access Report Criteria')
571 if (!$this->_instanceValues
['is_reserved'] ||
572 CRM_Core_Permission
::check('administer reserved reports')
574 $this->assign('criteriaForm', TRUE);
575 $this->_criteriaForm
= TRUE;
579 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
580 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
581 $this->_printButtonName
= $this->getButtonName('submit', 'print');
582 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
583 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
584 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
585 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
591 public function addBreadCrumb() {
595 'title' => ts('Report Templates'),
596 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
600 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
604 * Pre process function.
606 * Called prior to build form.
608 public function preProcess() {
609 $this->preProcessCommon();
612 $this->addBreadCrumb();
615 foreach ($this->_columns
as $tableName => $table) {
617 if (!isset($table['alias'])) {
618 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
622 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
625 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
627 $daoOrBaoName = NULL;
628 // higher preference to bao object
629 if (array_key_exists('bao', $table)) {
630 $daoOrBaoName = $table['bao'];
631 $expFields = $daoOrBaoName::exportableFields();
633 elseif (array_key_exists('dao', $table)) {
634 $daoOrBaoName = $table['dao'];
635 $expFields = $daoOrBaoName::export();
638 $expFields = array();
641 $doNotCopy = array('required');
643 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
644 foreach ($fieldGroups as $fieldGrp) {
645 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
646 foreach ($table[$fieldGrp] as $fieldName => $field) {
647 // $name is the field name used to reference the BAO/DAO export fields array
648 $name = isset($field['name']) ?
$field['name'] : $fieldName;
650 // Sometimes the field name key in the BAO/DAO export fields array is
651 // different from the actual database field name.
652 // Unset $field['name'] so that actual database field name can be obtained
653 // from the BAO/DAO export fields array.
654 unset($field['name']);
656 if (array_key_exists($name, $expFields)) {
657 foreach ($doNotCopy as $dnc) {
658 // unset the values we don't want to be copied.
659 unset($expFields[$name][$dnc]);
662 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
665 foreach ($expFields[$name] as $property => $val) {
666 if (!array_key_exists($property, $field)) {
667 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
674 if (!empty($field['no_repeat'])) {
675 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
677 if (!empty($field['no_display'])) {
678 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
681 // set alias = table-name, unless already set
682 $alias = isset($field['alias']) ?
$field['alias'] : (
683 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
685 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
687 // set name = fieldName, unless already set
688 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
689 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
692 // set dbAlias = alias.name, unless already set
693 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
694 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
696 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
699 // a few auto fills for filters
700 if ($fieldGrp == 'filters') {
701 // fill operator types
702 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
703 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
704 case CRM_Utils_Type
::T_MONEY
:
705 case CRM_Utils_Type
::T_FLOAT
:
706 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
709 case CRM_Utils_Type
::T_INT
:
710 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
713 case CRM_Utils_Type
::T_DATE
:
714 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
717 case CRM_Utils_Type
::T_BOOLEAN
:
718 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
719 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
720 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
731 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
733 // with multiple options operator-type is generally multi-select
734 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
735 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
737 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
748 // copy filters to a separate handy variable
749 if (array_key_exists('filters', $table)) {
750 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
753 if (array_key_exists('group_bys', $table)) {
754 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
757 if (array_key_exists('fields', $table)) {
758 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
763 $this->setDefaultValues(FALSE);
766 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
767 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
768 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
769 CRM_Report_Utils_Get
::processChart($this->_defaults
);
772 $this->_formValues
= $this->_defaults
;
773 $this->postProcess();
778 * Set default values.
780 * @param bool $freeze
784 public function setDefaultValues($freeze = TRUE) {
785 $freezeGroup = array();
787 // FIXME: generalizing form field naming conventions would reduce
788 // Lots of lines below.
789 foreach ($this->_columns
as $tableName => $table) {
790 if (array_key_exists('fields', $table)) {
791 foreach ($table['fields'] as $fieldName => $field) {
792 if (empty($field['no_display'])) {
793 if (isset($field['required'])) {
795 $this->_defaults
['fields'][$fieldName] = 1;
798 // find element object, so that we could use quickform's freeze method
799 // for required elements
800 $obj = $this->getElementFromGroup("fields", $fieldName);
802 $freezeGroup[] = $obj;
806 elseif (isset($field['default'])) {
807 $this->_defaults
['fields'][$fieldName] = $field['default'];
813 if (array_key_exists('group_bys', $table)) {
814 foreach ($table['group_bys'] as $fieldName => $field) {
815 if (isset($field['default'])) {
816 if (!empty($field['frequency'])) {
817 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
819 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
823 if (array_key_exists('filters', $table)) {
824 foreach ($table['filters'] as $fieldName => $field) {
825 if (isset($field['default'])) {
826 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
828 if (is_array($field['default'])) {
829 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
830 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
831 $this->_defaults
["{$fieldName}_relative"] = 0;
834 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
838 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
839 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
840 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
842 $this->_defaults
["{$fieldName}_value"] = $field['default'];
845 //assign default value as "in" for multiselect
846 //operator, To freeze the select element
847 if (CRM_Utils_Array
::value('operatorType', $field) ==
848 CRM_Report_Form
::OP_MULTISELECT
850 $this->_defaults
["{$fieldName}_op"] = 'in';
852 if (CRM_Utils_Array
::value('operatorType', $field) ==
853 CRM_Report_Form
::OP_ENTITYREF
855 $this->_defaults
["{$fieldName}_op"] = 'in';
857 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
858 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
860 $this->_defaults
["{$fieldName}_op"] = 'mhas';
862 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
863 $this->_defaults
["{$fieldName}_op"] = $op;
869 empty($this->_formValues
['order_bys']) &&
870 (array_key_exists('order_bys', $table) &&
871 is_array($table['order_bys']))
873 if (!array_key_exists('order_bys', $this->_defaults
)) {
874 $this->_defaults
['order_bys'] = array();
876 foreach ($table['order_bys'] as $fieldName => $field) {
877 if (!empty($field['default']) ||
!empty($field['default_order']) ||
878 CRM_Utils_Array
::value('default_is_section', $field) ||
879 !empty($field['default_weight'])
882 'column' => $fieldName,
883 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
884 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
887 if (!empty($field['default_weight'])) {
888 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
891 array_unshift($this->_defaults
['order_bys'], $order_by);
897 foreach ($this->_options
as $fieldName => $field) {
898 if (isset($field['default'])) {
899 $this->_defaults
['options'][$fieldName] = $field['default'];
904 if (!empty($this->_submitValues
)) {
905 $this->preProcessOrderBy($this->_submitValues
);
908 $this->preProcessOrderBy($this->_defaults
);
911 // lets finish freezing task here itself
912 if (!empty($freezeGroup)) {
913 foreach ($freezeGroup as $elem) {
918 if ($this->_formValues
) {
919 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
922 if ($this->_instanceValues
) {
923 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
926 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
928 return $this->_defaults
;
932 * Get element from group.
934 * @param string $group
935 * @param string $grpFieldName
939 public function getElementFromGroup($group, $grpFieldName) {
940 $eleObj = $this->getElement($group);
941 foreach ($eleObj->_elements
as $index => $obj) {
942 if ($grpFieldName == $obj->_attributes
['name']) {
950 * Setter for $_params.
952 * @param array $params
954 public function setParams($params) {
955 $this->_params
= $params;
961 * @param int $instanceID
963 public function setID($instanceID) {
964 $this->_id
= $instanceID;
968 * Setter for $_force.
970 * @param bool $isForce
972 public function setForce($isForce) {
973 $this->_force
= $isForce;
977 * Setter for $_limitValue.
979 * @param int $_limitValue
981 public function setLimitValue($_limitValue) {
982 $this->_limitValue
= $_limitValue;
986 * Setter for $_offsetValue.
988 * @param int $_offsetValue
990 public function setOffsetValue($_offsetValue) {
991 $this->_offsetValue
= $_offsetValue;
995 * Getter for $_defaultValues.
999 public function getDefaultValues() {
1000 return $this->_defaults
;
1004 * Add columns to report.
1006 public function addColumns() {
1009 foreach ($this->_columns
as $tableName => $table) {
1010 if (array_key_exists('fields', $table)) {
1011 foreach ($table['fields'] as $fieldName => $field) {
1013 if (empty($field['no_display'])) {
1014 foreach (array('table', 'field') as $var) {
1015 if (!empty($
{$var}['grouping'])) {
1016 if (!is_array($
{$var}['grouping'])) {
1017 $tableName = $
{$var}['grouping'];
1020 $tableName = array_keys($
{$var}['grouping']);
1021 $tableName = $tableName[0];
1022 $groupTitle = array_values($
{$var}['grouping']);
1023 $groupTitle = $groupTitle[0];
1028 if (!$groupTitle && isset($table['group_title'])) {
1029 $groupTitle = $table['group_title'];
1030 // Having a group_title is secret code for being a custom group
1031 // which cryptically translates to needing an accordion.
1032 // here we make that explicit.
1033 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1036 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1037 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1038 $colGroups[$tableName]['group_title'] = $groupTitle;
1040 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1046 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1047 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1049 if (!empty($colGroups)) {
1050 $this->tabs
['FieldSelection'] = array(
1051 'title' => ts('Columns'),
1052 'tpl' => 'FieldSelection',
1053 'div_label' => 'col-groups',
1056 // Note this assignment is only really required in buildForm. It is being 'over-called'
1057 // to reduce risk of being missed due to overridden functions.
1058 $this->assign('tabs', $this->tabs
);
1061 $this->assign('colGroups', $colGroups);
1065 * Add filters to report.
1067 public function addFilters() {
1068 $filters = $filterGroups = array();
1071 foreach ($this->_filters
as $table => $attributes) {
1072 if (isset($this->_columns
[$table]['group_title'])) {
1073 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1074 // which magically means to 'display in an accordian'
1075 // here we make this explicit.
1076 $filterGroups[$table] = array(
1077 'group_title' => $this->_columns
[$table]['group_title'],
1078 'use_accordian_for_field_selection' => TRUE,
1082 foreach ($attributes as $fieldName => $field) {
1083 // get ready with option value pair
1084 // @ 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
1086 $operations = $this->getOperationPair(
1087 CRM_Utils_Array
::value('operatorType', $field),
1090 $filters[$table][$fieldName] = $field;
1092 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1093 case CRM_Report_Form
::OP_MONTH
:
1094 if (!array_key_exists('options', $field) ||
1095 !is_array($field['options']) ||
empty($field['options'])
1097 // If there's no option list for this filter, define one.
1098 $field['options'] = array(
1100 2 => ts('February'),
1107 9 => ts('September'),
1108 10 => ts('October'),
1109 11 => ts('November'),
1110 12 => ts('December'),
1112 // Add this option list to this column _columns. This is
1113 // required so that filter statistics show properly.
1114 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1116 case CRM_Report_Form
::OP_MULTISELECT
:
1117 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1118 // assume a multi-select field
1119 if (!empty($field['options']) ||
1120 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1122 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1123 if (count($operations) <= 1) {
1126 if ($fieldName == 'state_province_id' ||
1127 $fieldName == 'county_id'
1129 $this->addChainSelect($fieldName . '_value', array(
1136 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1137 'style' => 'min-width:250px',
1138 'class' => 'crm-select2 huge',
1140 'placeholder' => ts('- select -'),
1146 case CRM_Report_Form
::OP_SELECT
:
1147 // assume a select field
1148 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1149 if (!empty($field['options'])) {
1150 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1154 case CRM_Report_Form
::OP_ENTITYREF
:
1155 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1156 $this->setEntityRefDefaults($field, $table);
1157 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1160 case CRM_Report_Form
::OP_DATE
:
1161 // build datetime fields
1162 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1166 case CRM_Report_Form
::OP_DATETIME
:
1167 // build datetime fields
1168 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1172 case CRM_Report_Form
::OP_INT
:
1173 case CRM_Report_Form
::OP_FLOAT
:
1174 // and a min value input box
1175 $this->add('text', "{$fieldName}_min", ts('Min'));
1176 // and a max value input box
1177 $this->add('text', "{$fieldName}_max", ts('Max'));
1179 // default type is string
1180 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1181 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1183 // we need text box for value input
1184 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1189 if (!empty($filters)) {
1190 $this->tabs
['Filters'] = array(
1191 'title' => ts('Filters'),
1193 'div_label' => 'set-filters',
1196 $this->assign('filters', $filters);
1197 $this->assign('filterGroups', $filterGroups);
1201 * Function to assign the tabs to the template in the correct order.
1203 * We want the tabs to wind up in this order (if not overridden).
1211 protected function assignTabs() {
1219 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1220 $order = array_merge($order, $this->tabs
);
1221 $this->assign('tabs', $order);
1225 * The intent is to add a tab for developers to view the sql.
1227 * Currently using dpm.
1229 * @param string $sql
1231 protected function addToDeveloperTab($sql) {
1232 if (!CRM_Core_Permission
::check('view report sql')) {
1235 $this->tabs
['Developer'] = array(
1236 'title' => ts('Developer'),
1237 'tpl' => 'Developer',
1238 'div_label' => 'set-developer',
1241 $this->assignTabs();
1242 foreach (array('LEFT JOIN') as $term) {
1243 $sql = str_replace($term, '<br>  ' . $term, $sql);
1245 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1246 $sql = str_replace($term, '<br><br>' . $term, $sql);
1248 $this->sql
.= $sql . "<br>";
1250 $this->assign('sql', $this->sql
);
1254 * Add options defined in $this->_options to the report.
1256 public function addOptions() {
1257 if (!empty($this->_options
)) {
1258 // FIXME: For now lets build all elements as checkboxes.
1259 // Once we clear with the format we can build elements based on type
1261 foreach ($this->_options
as $fieldName => $field) {
1264 if ($field['type'] == 'select') {
1265 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1267 elseif ($field['type'] == 'checkbox') {
1268 $options[$field['title']] = $fieldName;
1269 $this->addCheckBox($fieldName, NULL,
1271 NULL, NULL, NULL, $this->_fourColumnAttribute
1276 if (!empty($this->_options
)) {
1277 $this->tabs
['ReportOptions'] = array(
1278 'title' => ts('Display Options'),
1279 'tpl' => 'ReportOptions',
1280 'div_label' => 'other-options',
1283 $this->assign('otherOptions', $this->_options
);
1287 * Add chart options to the report.
1289 public function addChartOptions() {
1290 if (!empty($this->_charts
)) {
1291 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1292 $this->assign('charts', $this->_charts
);
1293 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1298 * Add group by options to the report.
1300 public function addGroupBys() {
1301 $options = $freqElements = array();
1303 foreach ($this->_columns
as $tableName => $table) {
1304 if (array_key_exists('group_bys', $table)) {
1305 foreach ($table['group_bys'] as $fieldName => $field) {
1306 if (!empty($field)) {
1307 $options[$field['title']] = $fieldName;
1308 if (!empty($field['frequency'])) {
1309 $freqElements[$field['title']] = $fieldName;
1315 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1316 NULL, NULL, NULL, $this->_fourColumnAttribute
1318 $this->assign('groupByElements', $options);
1319 if (!empty($options)) {
1320 $this->tabs
['GroupBy'] = array(
1321 'title' => ts('Grouping'),
1323 'div_label' => 'group-by-elements',
1327 foreach ($freqElements as $name) {
1328 $this->addElement('select', "group_bys_freq[$name]",
1329 ts('Frequency'), $this->_groupByDateFreq
1335 * Add data for order by tab.
1337 public function addOrderBys() {
1339 foreach ($this->_columns
as $tableName => $table) {
1341 // Report developer may define any column to order by; include these as order-by options.
1342 if (array_key_exists('order_bys', $table)) {
1343 foreach ($table['order_bys'] as $fieldName => $field) {
1344 if (!empty($field)) {
1345 $options[$fieldName] = $field['title'];
1350 // Add searchable custom fields as order-by options, if so requested
1351 // (These are already indexed, so allowing to order on them is cheap.)
1353 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1354 array_key_exists('extends', $table) && !empty($table['extends'])
1356 foreach ($table['fields'] as $fieldName => $field) {
1357 if (empty($field['no_display'])) {
1358 $options[$fieldName] = $field['title'];
1366 $this->assign('orderByOptions', $options);
1367 if (!empty($options)) {
1368 $this->tabs
['OrderBy'] = array(
1369 'title' => ts('Sorting'),
1371 'div_label' => 'order-by-elements',
1375 if (!empty($options)) {
1377 '-' => ' - none - ',
1379 for ($i = 1; $i <= 5; $i++
) {
1380 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1381 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1382 'ASC' => 'Ascending',
1383 'DESC' => 'Descending',
1385 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1386 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1392 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1394 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1395 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1398 public function buildInstanceAndButtons() {
1399 CRM_Report_Form_Instance
::buildForm($this);
1401 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1403 $this->addElement('submit', $this->_instanceButtonName
, $label);
1404 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1405 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1408 $this->addElement('submit', $this->_createNewButtonName
,
1409 ts('Save a Copy') . '...');
1411 $this->assign('instanceForm', $this->_instanceForm
);
1413 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1414 $this->addElement('submit', $this->_printButtonName
, $label);
1416 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1417 $this->addElement('submit', $this->_pdfButtonName
, $label);
1419 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1421 if ($this->_csvSupported
) {
1422 $this->addElement('submit', $this->_csvButtonName
, $label);
1425 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1426 $permission = CRM_Core_Permission
::getPermission();
1427 if ($permission == CRM_Core_Permission
::EDIT
&&
1428 $this->_add2groupSupported
1430 $this->addElement('select', 'groups', ts('Group'),
1431 array('' => ts('Add Contacts to Group')) +
1432 CRM_Core_PseudoConstant
::nestedGroup(),
1433 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1435 $this->assign('group', TRUE);
1438 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1440 $this->addChartOptions();
1441 $this->addButtons(array(
1444 'name' => ts('Preview Report'),
1445 'isDefault' => TRUE,
1452 * Main build form function.
1454 public function buildQuickForm() {
1455 $this->addColumns();
1457 $this->addFilters();
1459 $this->addOptions();
1461 $this->addGroupBys();
1463 $this->addOrderBys();
1465 $this->buildInstanceAndButtons();
1467 // Add form rule for report.
1468 if (is_callable(array(
1472 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1474 $this->assignTabs();
1478 * A form rule function for custom data.
1480 * The rule ensures that fields selected in group_by if any) should only be the ones
1481 * present in display/select fields criteria;
1482 * note: works if and only if any custom field selected in group_by.
1484 * @param array $fields
1485 * @param array $ignoreFields
1489 public function customDataFormRule($fields, $ignoreFields = array()) {
1491 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1492 !empty($fields['group_bys'])
1494 foreach ($this->_columns
as $tableName => $table) {
1495 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1496 substr($tableName, 0, 12) == 'custom_value') &&
1497 !empty($this->_columns
[$tableName]['fields'])
1499 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1500 if (array_key_exists($fieldName, $fields['group_bys']) &&
1501 !array_key_exists($fieldName, $fields['fields'])
1503 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1505 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1506 foreach ($fields['fields'] as $fld => $val) {
1507 if (!array_key_exists($fld, $fields['group_bys']) &&
1508 !in_array($fld, $ignoreFields)
1510 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1522 * Get operators to display on form.
1524 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1526 * @param string $type
1527 * @param string $fieldName
1531 public function getOperationPair($type = "string", $fieldName = NULL) {
1532 // FIXME: At some point we should move these key-val pairs
1533 // to option_group and option_value table.
1535 case CRM_Report_Form
::OP_INT
:
1536 case CRM_Report_Form
::OP_FLOAT
:
1539 'lte' => ts('Is less than or equal to'),
1540 'gte' => ts('Is greater than or equal to'),
1541 'bw' => ts('Is between'),
1542 'eq' => ts('Is equal to'),
1543 'lt' => ts('Is less than'),
1544 'gt' => ts('Is greater than'),
1545 'neq' => ts('Is not equal to'),
1546 'nbw' => ts('Is not between'),
1547 'nll' => ts('Is empty (Null)'),
1548 'nnll' => ts('Is not empty (Null)'),
1552 case CRM_Report_Form
::OP_SELECT
:
1554 'eq' => ts('Is equal to'),
1558 case CRM_Report_Form
::OP_MONTH
:
1559 case CRM_Report_Form
::OP_MULTISELECT
:
1560 case CRM_Report_Form
::OP_ENTITYREF
:
1563 'in' => ts('Is one of'),
1564 'notin' => ts('Is not one of'),
1568 case CRM_Report_Form
::OP_DATE
:
1571 'nll' => ts('Is empty (Null)'),
1572 'nnll' => ts('Is not empty (Null)'),
1576 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1577 // use this operator for the values, concatenated with separator. For e.g if
1578 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1580 'mhas' => ts('Is one of'),
1581 'mnot' => ts('Is not one of'),
1588 'has' => ts('Contains'),
1589 'sw' => ts('Starts with'),
1590 'ew' => ts('Ends with'),
1591 'nhas' => ts('Does not contain'),
1592 'eq' => ts('Is equal to'),
1593 'neq' => ts('Is not equal to'),
1594 'nll' => ts('Is empty (Null)'),
1595 'nnll' => ts('Is not empty (Null)'),
1602 * Build the tag filter field to display on the filters tab.
1604 public function buildTagFilter() {
1605 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1606 if (!empty($contactTags)) {
1607 $this->_columns
['civicrm_tag'] = array(
1608 'dao' => 'CRM_Core_DAO_Tag',
1612 'title' => ts('Tag'),
1614 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1615 'options' => $contactTags,
1623 * Adds group filters to _columns (called from _Construct).
1625 public function buildGroupFilter() {
1626 $this->_columns
['civicrm_group']['filters'] = array(
1628 'name' => 'group_id',
1629 'title' => ts('Group'),
1630 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1632 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1635 if (empty($this->_columns
['civicrm_group']['dao'])) {
1636 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1638 if (empty($this->_columns
['civicrm_group']['alias'])) {
1639 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1644 * Get SQL operator from form text version.
1646 * @param string $operator
1650 public function getSQLOperator($operator = "like") {
1651 switch ($operator) {
1684 return 'IS NOT NULL';
1693 * Generate where clause.
1695 * This can be overridden in reports for special treatment of a field
1697 * @param array $field Field specifications
1698 * @param string $op Query operator (not an exact match to sql)
1699 * @param mixed $value
1703 * @return null|string
1705 public function whereClause(&$field, $op, $value, $min, $max) {
1707 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1713 if (($min !== NULL && strlen($min) > 0) ||
1714 ($max !== NULL && strlen($max) > 0)
1716 $min = CRM_Utils_Type
::escape($min, $type);
1717 $max = CRM_Utils_Type
::escape($max, $type);
1721 $clauses[] = "( {$field['dbAlias']} >= $min )";
1724 $clauses[] = "( {$field['dbAlias']} < $min )";
1729 $clauses[] = "( {$field['dbAlias']} <= $max )";
1732 $clauses[] = "( {$field['dbAlias']} > $max )";
1736 if (!empty($clauses)) {
1738 $clause = implode(' AND ', $clauses);
1741 $clause = implode(' OR ', $clauses);
1749 if ($value !== NULL && strlen($value) > 0) {
1750 $value = CRM_Utils_Type
::escape($value, $type);
1751 if (strpos($value, '%') === FALSE) {
1752 $value = "'%{$value}%'";
1755 $value = "'{$value}'";
1757 $sqlOP = $this->getSQLOperator($op);
1758 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1764 if (is_string($value) && strlen($value)) {
1765 $value = explode(',', $value);
1767 if ($value !== NULL && is_array($value) && count($value) > 0) {
1768 $sqlOP = $this->getSQLOperator($op);
1769 if (CRM_Utils_Array
::value('type', $field) ==
1770 CRM_Utils_Type
::T_STRING
1772 //cycle through selections and escape values
1773 foreach ($value as $key => $selection) {
1774 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1777 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1781 // for numerical values
1782 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1785 if ($op == 'notin') {
1786 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1789 $clause = "( " . $clause . " )";
1795 // mhas == multiple has
1796 if ($value !== NULL && count($value) > 0) {
1797 $sqlOP = $this->getSQLOperator($op);
1798 foreach ($value as $key => $val) {
1799 $val = str_replace('(', '[[.left-parenthesis.]]', $val);
1800 $val = str_replace(')', '[[.right-parenthesis.]]', $val);
1801 $value[$key] = $val;
1803 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
1805 = "{$field['dbAlias']} REGEXP '$sp" . implode("$sp|$sp", $value) . "$sp'";
1810 // multiple has or multiple not
1811 if ($value !== NULL && count($value) > 0) {
1812 $sqlOP = $this->getSQLOperator($op);
1813 foreach ($value as $key => $val) {
1814 $val = str_replace('(', '[[.left-parenthesis.]]', $val);
1815 $val = str_replace(')', '[[.right-parenthesis.]]', $val);
1816 $value[$key] = $val;
1818 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
1820 = "( {$field['dbAlias']} NOT REGEXP '$sp" . implode("$sp|$sp", $value) .
1821 "$sp' OR {$field['dbAlias']} IS NULL )";
1827 if ($value !== NULL && strlen($value) > 0) {
1828 $value = CRM_Utils_Type
::escape($value, $type);
1829 if (strpos($value, '%') === FALSE) {
1831 $value = "'{$value}%'";
1834 $value = "'%{$value}'";
1838 $value = "'{$value}'";
1840 $sqlOP = $this->getSQLOperator($op);
1841 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1847 $sqlOP = $this->getSQLOperator($op);
1848 $clause = "( {$field['dbAlias']} $sqlOP )";
1852 if ($value !== NULL && strlen($value) > 0) {
1853 if (isset($field['clause'])) {
1854 // FIXME: we not doing escape here. Better solution is to use two
1855 // different types - data-type and filter-type
1856 $clause = $field['clause'];
1859 $value = CRM_Utils_Type
::escape($value, $type);
1860 $sqlOP = $this->getSQLOperator($op);
1861 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1862 $value = "'{$value}'";
1864 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1870 if (!empty($field['group']) && $clause) {
1871 $clause = $this->whereGroupClause($field, $value, $op);
1873 elseif (!empty($field['tag']) && $clause) {
1874 // not using left join in query because if any contact
1875 // belongs to more than one tag, results duplicate
1877 $clause = $this->whereTagClause($field, $value, $op);
1879 elseif (!empty($field['membership_org']) && $clause) {
1880 $clause = $this->whereMembershipOrgClause($value, $op);
1882 elseif (!empty($field['membership_type']) && $clause) {
1883 $clause = $this->whereMembershipTypeClause($value, $op);
1889 * Get SQL where clause for a date field.
1891 * @param string $fieldName
1892 * @param string $relative
1893 * @param string $from
1895 * @param string $type
1896 * @param string $fromTime
1897 * @param string $toTime
1899 * @return null|string
1901 public function dateClause(
1903 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1906 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1907 $sqlOP = $this->getSQLOperator($relative);
1908 return "( {$fieldName} {$sqlOP} )";
1911 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1914 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1915 $clauses[] = "( {$fieldName} >= $from )";
1919 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1920 $clauses[] = "( {$fieldName} <= {$to} )";
1923 if (!empty($clauses)) {
1924 return implode(' AND ', $clauses);
1931 * Possibly unused function.
1933 * @todo - could not find any instances where this is called
1935 * @param bool $relative
1936 * @param string $from
1939 * @return string|NULL
1941 public function dateDisplay($relative, $from, $to) {
1942 list($from, $to) = $this->getFromTo($relative, $from, $to);
1945 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1948 $clauses[] = 'Past';
1952 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1955 $clauses[] = 'Today';
1958 if (!empty($clauses)) {
1959 return implode(' - ', $clauses);
1966 * Get values for from and to for date ranges.
1968 * @param bool $relative
1969 * @param string $from
1971 * @param string $fromTime
1972 * @param string $toTime
1976 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1977 if (empty($toTime)) {
1980 //FIX ME not working for relative
1982 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1983 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1984 $from = substr($dateRange['from'], 0, 8);
1985 //Take only Date Part, Sometime Time part is also present in 'to'
1986 $to = substr($dateRange['to'], 0, 8);
1988 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1989 $to = CRM_Utils_Date
::processDate($to, $toTime);
1990 return array($from, $to);
1994 * Alter display of rows.
1996 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1997 * such as rendering contacts as links.
1999 * @param array $rows
2000 * Rows generated by SQL, with an array for each row.
2002 public function alterDisplay(&$rows) {
2006 * Alter the way in which custom data fields are displayed.
2008 * @param array $rows
2010 public function alterCustomDataDisplay(&$rows) {
2011 // custom code to alter rows having custom values
2012 if (empty($this->_customGroupExtends
)) {
2016 $customFieldIds = array();
2017 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2018 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2019 $customFieldIds[$fieldAlias] = $fieldId;
2022 if (empty($customFieldIds)) {
2026 $customFields = $fieldValueMap = array();
2027 $customFieldCols = array(
2035 // skip for type date and ContactReference since date format is already handled
2037 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
2038 FROM civicrm_custom_field cf
2039 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2040 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
2041 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2042 cg.is_active = 1 AND
2043 cf.is_active = 1 AND
2044 cf.is_searchable = 1 AND
2045 cf.data_type NOT IN ('ContactReference', 'Date') AND
2046 cf.id IN (" . implode(",", $customFieldIds) . ")";
2048 $dao = CRM_Core_DAO
::executeQuery($query);
2049 while ($dao->fetch()) {
2050 foreach ($customFieldCols as $key) {
2051 $customFields[$dao->table_name
. '_custom_' .
2052 $dao->id
][$key] = $dao->$key;
2054 if ($dao->option_group_id
) {
2055 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
2060 $entryFound = FALSE;
2061 foreach ($rows as $rowNum => $row) {
2062 foreach ($row as $tableCol => $val) {
2063 if (array_key_exists($tableCol, $customFields)) {
2064 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
2069 // skip looking further in rows, if first row itself doesn't
2070 // have the column we need
2078 * Format custom values.
2080 * @param mixed $value
2081 * @param array $customField
2082 * @param array $fieldValueMap
2084 * @return float|string|void
2086 public function formatCustomValues($value, $customField, $fieldValueMap) {
2087 if (CRM_Utils_System
::isNull($value)) {
2091 $htmlType = $customField['html_type'];
2093 switch ($customField['data_type']) {
2095 if ($value == '1') {
2096 $retValue = ts('Yes');
2099 $retValue = ts('No');
2104 $retValue = CRM_Utils_System
::formatWikiURL($value);
2116 if ($htmlType == 'Text') {
2117 $retValue = (float) $value;
2121 if ($htmlType == 'Text') {
2122 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2127 if (in_array($htmlType, array(
2134 case 'StateProvince':
2137 switch ($htmlType) {
2138 case 'Multi-Select Country':
2139 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2140 $customData = array();
2141 foreach ($value as $val) {
2143 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
2146 $retValue = implode(', ', $customData);
2149 case 'Select Country':
2150 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
2153 case 'Select State/Province':
2154 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2157 case 'Multi-Select State/Province':
2158 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2159 $customData = array();
2160 foreach ($value as $val) {
2162 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
2165 $retValue = implode(', ', $customData);
2170 case 'Autocomplete-Select':
2171 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2175 case 'AdvMulti-Select':
2176 case 'Multi-Select':
2177 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2178 $customData = array();
2179 foreach ($value as $val) {
2181 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2184 $retValue = implode(', ', $customData);
2200 * Remove duplicate rows.
2202 * @param array $rows
2204 public function removeDuplicates(&$rows) {
2205 if (empty($this->_noRepeats
)) {
2208 $checkList = array();
2210 foreach ($rows as $key => $list) {
2211 foreach ($list as $colName => $colVal) {
2212 if (array_key_exists($colName, $checkList) &&
2213 $checkList[$colName] == $colVal
2215 $rows[$key][$colName] = "";
2217 if (in_array($colName, $this->_noRepeats
)) {
2218 $checkList[$colName] = $colVal;
2225 * Fix subtotal display.
2228 * @param array $fields
2229 * @param bool $subtotal
2231 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2232 foreach ($row as $colName => $colVal) {
2233 if (in_array($colName, $fields)) {
2235 elseif (isset($this->_columnHeaders
[$colName])) {
2237 $row[$colName] = "Subtotal";
2241 unset($row[$colName]);
2248 * Calculate grant total.
2250 * @param array $rows
2254 public function grandTotal(&$rows) {
2255 if (!$this->_rollup ||
($this->_rollup
== '') ||
2256 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2260 $lastRow = array_pop($rows);
2262 foreach ($this->_columnHeaders
as $fld => $val) {
2263 if (!in_array($fld, $this->_statFields
)) {
2264 if (!$this->_grandFlag
) {
2265 $lastRow[$fld] = "Grand Total";
2266 $this->_grandFlag
= TRUE;
2269 $lastRow[$fld] = "";
2274 $this->assign('grandStat', $lastRow);
2279 * Format display output.
2281 * @param array $rows
2282 * @param bool $pager
2284 public function formatDisplay(&$rows, $pager = TRUE) {
2285 // set pager based on if any limit was applied in the query.
2290 // allow building charts if any
2291 if (!empty($this->_params
['charts']) && !empty($rows)) {
2292 $this->buildChart($rows);
2293 $this->assign('chartEnabled', TRUE);
2294 $this->_chartId
= "{$this->_params['charts']}_" .
2295 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2297 $this->assign('chartId', $this->_chartId
);
2300 // unset columns not to be displayed.
2301 foreach ($this->_columnHeaders
as $key => $value) {
2302 if (!empty($value['no_display'])) {
2303 unset($this->_columnHeaders
[$key]);
2307 // unset columns not to be displayed.
2308 if (!empty($rows)) {
2309 foreach ($this->_noDisplay
as $noDisplayField) {
2310 foreach ($rows as $rowNum => $row) {
2311 unset($this->_columnHeaders
[$noDisplayField]);
2316 // build array of section totals
2317 $this->sectionTotals();
2319 // process grand-total row
2320 $this->grandTotal($rows);
2322 // use this method for formatting rows for display purpose.
2323 $this->alterDisplay($rows);
2324 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2326 // use this method for formatting custom rows for display purpose.
2327 $this->alterCustomDataDisplay($rows);
2333 * @param array $rows
2335 public function buildChart(&$rows) {
2336 // override this method for building charts.
2339 // select() method below has been added recently (v3.3), and many of the report templates might
2340 // still be having their own select() method. We should fix them as and when encountered and move
2341 // towards generalizing the select() method below.
2344 * Generate the SELECT clause and set class variable $_select.
2346 public function select() {
2347 $select = $this->_selectAliases
= array();
2349 foreach ($this->_columns
as $tableName => $table) {
2350 if (array_key_exists('fields', $table)) {
2351 foreach ($table['fields'] as $fieldName => $field) {
2352 if ($tableName == 'civicrm_address') {
2353 $this->_addressField
= TRUE;
2355 if ($tableName == 'civicrm_email') {
2356 $this->_emailField
= TRUE;
2358 if ($tableName == 'civicrm_phone') {
2359 $this->_phoneField
= TRUE;
2362 if (!empty($field['required']) ||
2363 !empty($this->_params
['fields'][$fieldName])
2366 // 1. In many cases we want select clause to be built in slightly different way
2367 // for a particular field of a particular type.
2368 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2370 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2371 if ($selectClause) {
2372 $select[] = $selectClause;
2376 // include statistics columns only if set
2377 if (!empty($field['statistics'])) {
2378 foreach ($field['statistics'] as $stat => $label) {
2379 $alias = "{$tableName}_{$fieldName}_{$stat}";
2380 switch (strtolower($stat)) {
2383 $select[] = "$stat({$field['dbAlias']}) as $alias";
2384 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2385 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2386 $this->_statFields
[$label] = $alias;
2387 $this->_selectAliases
[] = $alias;
2391 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2392 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2393 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2394 $this->_statFields
[$label] = $alias;
2395 $this->_selectAliases
[] = $alias;
2398 case 'count_distinct':
2399 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2400 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2401 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2402 $this->_statFields
[$label] = $alias;
2403 $this->_selectAliases
[] = $alias;
2407 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2408 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2409 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2410 $this->_statFields
[$label] = $alias;
2411 $this->_selectAliases
[] = $alias;
2417 $alias = "{$tableName}_{$fieldName}";
2418 $select[] = "{$field['dbAlias']} as $alias";
2419 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2420 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2421 $this->_selectAliases
[] = $alias;
2427 // select for group bys
2428 if (array_key_exists('group_bys', $table)) {
2429 foreach ($table['group_bys'] as $fieldName => $field) {
2431 if ($tableName == 'civicrm_address') {
2432 $this->_addressField
= TRUE;
2434 if ($tableName == 'civicrm_email') {
2435 $this->_emailField
= TRUE;
2437 if ($tableName == 'civicrm_phone') {
2438 $this->_phoneField
= TRUE;
2440 // 1. In many cases we want select clause to be built in slightly different way
2441 // for a particular field of a particular type.
2442 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2444 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2445 if ($selectClause) {
2446 $select[] = $selectClause;
2450 if (!empty($this->_params
['group_bys']) &&
2451 !empty($this->_params
['group_bys'][$fieldName]) &&
2452 !empty($this->_params
['group_bys_freq'])
2454 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2456 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2457 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2458 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2459 $field['title'] = 'Week';
2463 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2464 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2465 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2466 $field['title'] = 'Year';
2470 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2471 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2472 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2473 $field['title'] = 'Month';
2477 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2478 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2479 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2480 $field['title'] = 'Quarter';
2483 // for graphs and charts -
2484 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2485 $this->_interval
= $field['title'];
2486 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2487 = $field['title'] . ' Beginning';
2488 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2489 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2491 // just to make sure these values are transferred to rows.
2492 // since we 'll need them for calculation purpose,
2493 // e.g making subtotals look nicer or graphs
2494 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2495 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2502 $this->_selectClauses
= $select;
2503 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2507 * Build select clause for a single field.
2509 * @param string $tableName
2510 * @param string $tableKey
2511 * @param string $fieldName
2512 * @param string $field
2516 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2521 * Build where clause.
2523 public function where() {
2524 $this->storeWhereHavingClauseArray();
2526 if (empty($this->_whereClauses
)) {
2527 $this->_where
= "WHERE ( 1 ) ";
2528 $this->_having
= "";
2531 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2534 if ($this->_aclWhere
) {
2535 $this->_where
.= " AND {$this->_aclWhere} ";
2538 if (!empty($this->_havingClauses
)) {
2539 // use this clause to construct group by clause.
2540 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2545 * Store Where clauses into an array.
2547 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2548 * temp table that may not be part of the final where clause or added
2549 * in other functions
2551 public function storeWhereHavingClauseArray() {
2552 foreach ($this->_columns
as $tableName => $table) {
2553 if (array_key_exists('filters', $table)) {
2554 foreach ($table['filters'] as $fieldName => $field) {
2555 // respect pseudofield to filter spec so fields can be marked as
2556 // not to be handled here
2557 if (!empty($field['pseudofield'])) {
2561 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2562 if (CRM_Utils_Array
::value('operatorType', $field) ==
2563 CRM_Report_Form
::OP_MONTH
2565 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2566 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2567 if (is_array($value) && !empty($value)) {
2569 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2574 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2575 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2576 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2577 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2578 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2579 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2583 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2585 $clause = $this->whereClause($field,
2587 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2588 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2589 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2594 if (!empty($clause)) {
2595 if (!empty($field['having'])) {
2596 $this->_havingClauses
[] = $clause;
2599 $this->_whereClauses
[] = $clause;
2611 public function processReportMode() {
2612 $buttonName = $this->controller
->getButtonName();
2614 $output = CRM_Utils_Request
::retrieve(
2617 CRM_Core_DAO
::$_nullObject
2621 = CRM_Utils_Request
::retrieve(
2624 CRM_Core_DAO
::$_nullObject
2627 $this->_absoluteUrl
= FALSE;
2629 $this->assign('printOnly', FALSE);
2631 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2632 ($this->_sendmail
&& !$output)
2634 $this->assign('printOnly', TRUE);
2636 $this->assign('outputMode', 'print');
2637 $this->_outputMode
= 'print';
2638 if ($this->_sendmail
) {
2639 $this->_absoluteUrl
= TRUE;
2642 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2643 $this->assign('printOnly', TRUE);
2645 $this->assign('outputMode', 'pdf');
2646 $this->_outputMode
= 'pdf';
2647 $this->_absoluteUrl
= TRUE;
2649 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2650 $this->assign('printOnly', TRUE);
2652 $this->assign('outputMode', 'csv');
2653 $this->_outputMode
= 'csv';
2654 $this->_absoluteUrl
= TRUE;
2656 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2657 $this->assign('outputMode', 'group');
2658 $this->_outputMode
= 'group';
2660 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2661 $this->assign('outputMode', 'create_report');
2662 $this->_outputMode
= 'create_report';
2665 $this->assign('outputMode', 'html');
2666 $this->_outputMode
= 'html';
2669 // Get today's date to include in printed reports
2671 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2672 $this->assign('reportDate', $reportDate);
2677 * Post Processing function for Form.
2679 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2681 public function beginPostProcess() {
2682 $this->setParams($this->controller
->exportValues($this->_name
));
2684 if (empty($this->_params
) &&
2687 $this->setParams($this->_formValues
);
2690 // hack to fix params when submitted from dashboard, CRM-8532
2691 // fields array is missing because form building etc is skipped
2692 // in dashboard mode for report
2693 //@todo - this could be done in the dashboard no we have a setter
2694 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2695 $this->setParams($this->_formValues
);
2698 $this->_formValues
= $this->_params
;
2699 if (CRM_Core_Permission
::check('administer Reports') &&
2700 isset($this->_id
) &&
2701 ($this->_instanceButtonName
==
2702 $this->controller
->getButtonName() . '_save' ||
2703 $this->_chartButtonName
== $this->controller
->getButtonName()
2706 $this->assign('updateReportButton', TRUE);
2708 $this->processReportMode();
2709 $this->beginPostProcessCommon();
2713 * BeginPostProcess function run in both report mode and non-report mode (api).
2715 public function beginPostProcessCommon() {}
2718 * Build the report query.
2720 * @param bool $applyLimit
2724 public function buildQuery($applyLimit = TRUE) {
2727 $this->customDataFrom();
2732 // order_by columns not selected for display need to be included in SELECT
2733 $unselectedSectionColumns = $this->unselectedSectionColumns();
2734 foreach ($unselectedSectionColumns as $alias => $section) {
2735 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2738 if ($applyLimit && empty($this->_params
['charts'])) {
2741 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2743 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2744 $this->addToDeveloperTab($sql);
2749 * Build group by clause.
2751 public function groupBy() {
2752 $groupBys = array();
2753 if (!empty($this->_params
['group_bys']) &&
2754 is_array($this->_params
['group_bys'])
2756 foreach ($this->_columns
as $tableName => $table) {
2757 if (array_key_exists('group_bys', $table)) {
2758 foreach ($table['group_bys'] as $fieldName => $field) {
2759 if (!empty($this->_params
['group_bys'][$fieldName])) {
2760 $groupBys[] = $field['dbAlias'];
2767 if (!empty($groupBys)) {
2768 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2773 * Build order by clause.
2775 public function orderBy() {
2776 $this->_orderBy
= "";
2777 $this->_sections
= array();
2778 $this->storeOrderByArray();
2779 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2780 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2782 $this->assign('sections', $this->_sections
);
2786 * Extract order by fields and store as an array.
2788 * In some cases other functions want to know which fields are selected for ordering by
2789 * Separating this into a separate function allows it to be called separately from constructing
2790 * the order by clause
2792 public function storeOrderByArray() {
2793 $orderBys = array();
2795 if (!empty($this->_params
['order_bys']) &&
2796 is_array($this->_params
['order_bys']) &&
2797 !empty($this->_params
['order_bys'])
2800 // Process order_bys in user-specified order
2801 foreach ($this->_params
['order_bys'] as $orderBy) {
2802 $orderByField = array();
2803 foreach ($this->_columns
as $tableName => $table) {
2804 if (array_key_exists('order_bys', $table)) {
2805 // For DAO columns defined in $this->_columns
2806 $fields = $table['order_bys'];
2808 elseif (array_key_exists('extends', $table)) {
2809 // For custom fields referenced in $this->_customGroupExtends
2810 $fields = CRM_Utils_Array
::value('fields', $table, array());
2815 if (!empty($fields) && is_array($fields)) {
2816 foreach ($fields as $fieldName => $field) {
2817 if ($fieldName == $orderBy['column']) {
2818 $orderByField = array_merge($field, $orderBy);
2819 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2826 if (!empty($orderByField)) {
2827 $this->_orderByFields
[] = $orderByField;
2828 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2830 // Record any section headers for assignment to the template
2831 if (!empty($orderBy['section'])) {
2832 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2833 $this->_sections
[$orderByField['tplField']] = $orderByField;
2839 $this->_orderByArray
= $orderBys;
2841 $this->assign('sections', $this->_sections
);
2845 * Determine unselected columns.
2849 public function unselectedSectionColumns() {
2850 $selectColumns = array();
2851 foreach ($this->_columns
as $tableName => $table) {
2852 if (array_key_exists('fields', $table)) {
2853 foreach ($table['fields'] as $fieldName => $field) {
2854 if (!empty($field['required']) ||
2855 !empty($this->_params
['fields'][$fieldName])
2858 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2864 if (is_array($this->_sections
)) {
2865 return array_diff_key($this->_sections
, $selectColumns);
2873 * Build output rows.
2875 * @param string $sql
2876 * @param array $rows
2878 public function buildRows($sql, &$rows) {
2879 $dao = CRM_Core_DAO
::executeQuery($sql);
2880 if (!is_array($rows)) {
2884 // use this method to modify $this->_columnHeaders
2885 $this->modifyColumnHeaders();
2887 $unselectedSectionColumns = $this->unselectedSectionColumns();
2889 while ($dao->fetch()) {
2891 foreach ($this->_columnHeaders
as $key => $value) {
2892 if (property_exists($dao, $key)) {
2893 $row[$key] = $dao->$key;
2897 // section headers not selected for display need to be added to row
2898 foreach ($unselectedSectionColumns as $key => $values) {
2899 if (property_exists($dao, $key)) {
2900 $row[$key] = $dao->$key;
2909 * Calculate section totals.
2911 * When "order by" fields are marked as sections, this assigns to the template
2912 * an array of total counts for each section. This data is used by the Smarty
2913 * plugin {sectionTotal}.
2915 public function sectionTotals() {
2917 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2918 if (empty($this->_selectAliases
)) {
2922 if (!empty($this->_sections
)) {
2923 // build the query with no LIMIT clause
2924 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2925 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2927 // pull section aliases out of $this->_sections
2928 $sectionAliases = array_keys($this->_sections
);
2931 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2932 $ifnulls[] = "ifnull($alias, '') as $alias";
2935 // Group (un-limited) report by all aliases and get counts. This might
2936 // be done more efficiently when the contents of $sql are known, ie. by
2937 // overriding this method in the report class.
2939 $query = "select " . implode(", ", $ifnulls) .
2940 ", count(*) as ct from ($sql) as subquery group by " .
2941 implode(", ", $sectionAliases);
2943 // initialize array of total counts
2945 $dao = CRM_Core_DAO
::executeQuery($query);
2946 while ($dao->fetch()) {
2948 // let $this->_alterDisplay translate any integer ids to human-readable values.
2949 $rows[0] = $dao->toArray();
2950 $this->alterDisplay($rows);
2953 // add totals for all permutations of section values
2956 $aliasCount = count($sectionAliases);
2957 foreach ($sectionAliases as $alias) {
2958 $values[] = $row[$alias];
2959 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2960 if ($i == $aliasCount) {
2961 // the last alias is the lowest-level section header; use count as-is
2962 $totals[$key] = $dao->ct
;
2965 // other aliases are higher level; roll count into their total
2966 $totals[$key] +
= $dao->ct
;
2970 $this->assign('sectionTotals', $totals);
2975 * Modify column headers.
2977 public function modifyColumnHeaders() {
2978 // use this method to modify $this->_columnHeaders
2982 * Assign rows to the template.
2984 * @param array $rows
2986 public function doTemplateAssignment(&$rows) {
2987 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2988 $this->assign_by_ref('rows', $rows);
2989 $this->assign('statistics', $this->statistics($rows));
2993 * Build report statistics.
2995 * Override this method to build your own statistics.
2997 * @param array $rows
3001 public function statistics(&$rows) {
3002 $statistics = array();
3004 $count = count($rows);
3006 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3010 $this->countStat($statistics, $count);
3012 $this->groupByStat($statistics);
3014 $this->filterStat($statistics);
3020 * Add count statistics.
3022 * @param array $statistics
3025 public function countStat(&$statistics, $count) {
3026 $statistics['counts']['rowCount'] = array(
3027 'title' => ts('Row(s) Listed'),
3031 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3032 $statistics['counts']['rowsFound'] = array(
3033 'title' => ts('Total Row(s)'),
3034 'value' => $this->_rowsFound
,
3040 * Add group by statistics.
3042 * @param array $statistics
3044 public function groupByStat(&$statistics) {
3045 if (!empty($this->_params
['group_bys']) &&
3046 is_array($this->_params
['group_bys']) &&
3047 !empty($this->_params
['group_bys'])
3049 foreach ($this->_columns
as $tableName => $table) {
3050 if (array_key_exists('group_bys', $table)) {
3051 foreach ($table['group_bys'] as $fieldName => $field) {
3052 if (!empty($this->_params
['group_bys'][$fieldName])) {
3053 $combinations[] = $field['title'];
3058 $statistics['groups'][] = array(
3059 'title' => ts('Grouping(s)'),
3060 'value' => implode(' & ', $combinations),
3066 * Filter statistics.
3068 * @param array $statistics
3070 public function filterStat(&$statistics) {
3071 foreach ($this->_columns
as $tableName => $table) {
3072 if (array_key_exists('filters', $table)) {
3073 foreach ($table['filters'] as $fieldName => $field) {
3074 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
3075 CRM_Utils_Array
::value('operatorType', $field) !=
3076 CRM_Report_Form
::OP_MONTH
3080 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3081 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3082 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3083 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3084 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3086 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3087 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3089 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3090 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3093 $statistics['filters'][] = array(
3094 'title' => $field['title'],
3095 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3098 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3099 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3101 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3102 $statistics['filters'][] = array(
3103 'title' => $field['title'],
3104 'value' => $pair[$rel],
3109 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3112 $pair = $this->getOperationPair(
3113 CRM_Utils_Array
::value('operatorType', $field),
3116 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3117 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3118 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3119 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3120 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3122 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3123 $this->setEntityRefDefaults($field, $tableName);
3124 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3125 array('id' => $val) +
3126 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3128 foreach ($result['values'] as $v) {
3129 $values[] = $v['label'];
3131 $value = "{$pair[$op]} " . implode(', ', $values);
3133 elseif ($op == 'nll' ||
$op == 'nnll') {
3134 $value = $pair[$op];
3136 elseif (is_array($val) && (!empty($val))) {
3137 $options = CRM_Utils_Array
::value('options', $field, array());
3138 foreach ($val as $key => $valIds) {
3139 if (isset($options[$valIds])) {
3140 $val[$key] = $options[$valIds];
3143 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3144 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3145 $val = implode(', ', $val);
3146 $value = "{$pair[$op]} " . $val;
3148 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3149 isset($field['options']) &&
3150 is_array($field['options']) && !empty($field['options'])
3152 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3153 CRM_Utils_Array
::value($val, $field['options'], $val);
3156 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3160 $statistics['filters'][] = array(
3161 'title' => CRM_Utils_Array
::value('title', $field),
3172 * End post processing.
3174 * @param array|null $rows
3176 public function endPostProcess(&$rows = NULL) {
3177 if ($this->_storeResultSet
) {
3178 $this->_resultSet
= $rows;
3181 if ($this->_outputMode
== 'print' ||
3182 $this->_outputMode
== 'pdf' ||
3186 $content = $this->compileContent();
3187 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3191 if ($this->_sendmail
) {
3192 $config = CRM_Core_Config
::singleton();
3193 $attachments = array();
3195 if ($this->_outputMode
== 'csv') {
3197 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3198 ": {$url}</p>" . '<p>' .
3199 ts('The report is attached as a CSV file.') . '</p>' .
3200 $this->_formValues
['report_footer'];
3202 $csvFullFilename = $config->templateCompileDir
.
3203 CRM_Utils_File
::makeFileName('CiviReport.csv');
3204 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3205 file_put_contents($csvFullFilename, $csvContent);
3206 $attachments[] = array(
3207 'fullPath' => $csvFullFilename,
3208 'mime_type' => 'text/csv',
3209 'cleanName' => 'CiviReport.csv',
3212 if ($this->_outputMode
== 'pdf') {
3213 // generate PDF content
3214 $pdfFullFilename = $config->templateCompileDir
.
3215 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3216 file_put_contents($pdfFullFilename,
3217 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3218 TRUE, array('orientation' => 'landscape')
3221 // generate Email Content
3223 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3224 ": {$url}</p>" . '<p>' .
3225 ts('The report is attached as a PDF file.') . '</p>' .
3226 $this->_formValues
['report_footer'];
3228 $attachments[] = array(
3229 'fullPath' => $pdfFullFilename,
3230 'mime_type' => 'application/pdf',
3231 'cleanName' => 'CiviReport.pdf',
3235 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3236 $this->_outputMode
, $attachments
3239 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3242 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3246 elseif ($this->_outputMode
== 'print') {
3250 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3251 $config = CRM_Core_Config
::singleton();
3252 //get chart image name
3253 $chartImg = $this->_chartId
. '.png';
3254 //get image url path
3256 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3258 $uploadUrl .= $chartImg;
3259 //get image doc path to overwrite
3261 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3262 'openFlashChart/' . $chartImg;
3264 $chart = imagecreatefrompng($uploadUrl);
3265 //convert it into formatted png
3266 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3267 //overwrite with same image
3268 imagepng($chart, $uploadImg);
3270 imagedestroy($chart);
3272 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3274 CRM_Utils_System
::civiExit();
3276 elseif ($this->_outputMode
== 'csv') {
3277 CRM_Report_Utils_Report
::export2csv($this, $rows);
3279 elseif ($this->_outputMode
== 'group') {
3280 $group = $this->_params
['groups'];
3281 $this->add2group($group);
3283 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3284 CRM_Report_Form_Instance
::postProcess($this);
3286 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3287 $this->_outputMode
== 'create_report'
3289 $this->_createNew
= TRUE;
3290 CRM_Report_Form_Instance
::postProcess($this);
3295 * Set store result set indicator to TRUE.
3297 * @todo explain what this does
3299 public function storeResultSet() {
3300 $this->_storeResultSet
= TRUE;
3308 public function getResultSet() {
3309 return $this->_resultSet
;
3313 * Use the form name to create the tpl file name.
3317 public function getTemplateFileName() {
3318 $defaultTpl = parent
::getTemplateFileName();
3319 $template = CRM_Core_Smarty
::singleton();
3320 if (!$template->template_exists($defaultTpl)) {
3321 $defaultTpl = 'CRM/Report/Form.tpl';
3327 * Compile the report content.
3329 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3333 public function compileContent() {
3334 $templateFile = $this->getHookedTemplateFileName();
3335 return $this->_formValues
['report_header'] .
3336 CRM_Core_Form
::$_template->fetch($templateFile) .
3337 $this->_formValues
['report_footer'];
3342 * Post process function.
3344 public function postProcess() {
3345 // get ready with post process params
3346 $this->beginPostProcess();
3349 $sql = $this->buildQuery();
3351 // build array of result based on column headers. This method also allows
3352 // modifying column headers before using it to build result set i.e $rows.
3354 $this->buildRows($sql, $rows);
3356 // format result set.
3357 $this->formatDisplay($rows);
3359 // assign variables to templates
3360 $this->doTemplateAssignment($rows);
3362 // do print / pdf / instance stuff if needed
3363 $this->endPostProcess($rows);
3369 * @param int $rowCount
3373 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3374 // lets do the pager if in html mode
3375 $this->_limit
= NULL;
3377 // CRM-14115, over-ride row count if rowCount is specified in URL
3378 if ($this->_dashBoardRowCount
) {
3379 $rowCount = $this->_dashBoardRowCount
;
3381 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3382 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3384 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3386 // @todo all http vars should be extracted in the preProcess
3387 // - not randomly in the class
3388 if (!$pageId && !empty($_POST)) {
3389 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3390 $pageId = max((int) $_POST['crmPID_B'], 1);
3392 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3393 $pageId = max((int) $_POST['crmPID'], 1);
3395 unset($_POST['crmPID_B'], $_POST['crmPID']);
3398 $pageId = $pageId ?
$pageId : 1;
3399 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3400 $offset = ($pageId - 1) * $rowCount;
3402 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3403 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3405 $this->_limit
= " LIMIT $offset, $rowCount";
3406 return array($offset, $rowCount);
3408 if ($this->_limitValue
) {
3409 if ($this->_offsetValue
) {
3410 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3413 $this->_limit
= " LIMIT " . $this->_limitValue
;
3421 * @param int $rowCount
3423 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3425 // CRM-14115, over-ride row count if rowCount is specified in URL
3426 if ($this->_dashBoardRowCount
) {
3427 $rowCount = $this->_dashBoardRowCount
;
3430 if ($this->_limit
&& ($this->_limit
!= '')) {
3431 $sql = "SELECT FOUND_ROWS();";
3432 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3434 'total' => $this->_rowsFound
,
3435 'rowCount' => $rowCount,
3436 'status' => ts('Records') . ' %%StatusMessage%%',
3437 'buttonBottom' => 'PagerBottomButton',
3438 'buttonTop' => 'PagerTopButton',
3439 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3442 $pager = new CRM_Utils_Pager($params);
3443 $this->assign_by_ref('pager', $pager);
3444 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3449 * Build where clause for groups.
3451 * @param string $field
3452 * @param mixed $value
3457 public function whereGroupClause($field, $value, $op) {
3459 $smartGroupQuery = "";
3461 $group = new CRM_Contact_DAO_Group();
3462 $group->is_active
= 1;
3464 $smartGroups = array();
3465 while ($group->fetch()) {
3466 if (in_array($group->id
, $this->_params
['gid_value']) &&
3467 $group->saved_search_id
3469 $smartGroups[] = $group->id
;
3473 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3475 $smartGroupQuery = '';
3476 if (!empty($smartGroups)) {
3477 $smartGroups = implode(',', $smartGroups);
3478 $smartGroupQuery = " UNION DISTINCT
3479 SELECT DISTINCT smartgroup_contact.contact_id
3480 FROM civicrm_group_contact_cache smartgroup_contact
3481 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3484 $sqlOp = $this->getSQLOperator($op);
3485 if (!is_array($value)) {
3486 $value = array($value);
3488 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3490 $contactAlias = $this->_aliases
['civicrm_contact'];
3491 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3492 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3494 return " {$contactAlias}.id {$sqlOp} (
3495 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3496 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3497 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3498 {$smartGroupQuery} ) ";
3502 * Build where clause for tags.
3504 * @param string $field
3505 * @param mixed $value
3510 public function whereTagClause($field, $value, $op) {
3511 // not using left join in query because if any contact
3512 // belongs to more than one tag, results duplicate
3514 $sqlOp = $this->getSQLOperator($op);
3515 if (!is_array($value)) {
3516 $value = array($value);
3518 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3519 $entity_table = $this->_tagFilterTable
;
3520 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3521 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3522 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3523 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3527 * Generate membership organization clause.
3529 * @param mixed $value
3530 * @param string $op SQL Operator
3534 public function whereMembershipOrgClause($value, $op) {
3535 $sqlOp = $this->getSQLOperator($op);
3536 if (!is_array($value)) {
3537 $value = array($value);
3540 $tmp_membership_org_sql_list = implode(', ', $value);
3541 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3542 SELECT DISTINCT mem.contact_id
3543 FROM civicrm_membership mem
3544 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3545 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3546 WHERE mt.member_of_contact_id IN (" .
3547 $tmp_membership_org_sql_list . ")
3548 AND mt.is_active = '1'
3549 AND mem_status.is_current_member = '1'
3550 AND mem_status.is_active = '1' ) ";
3554 * Generate Membership Type SQL Clause.
3556 * @param mixed $value
3562 public function whereMembershipTypeClause($value, $op) {
3563 $sqlOp = $this->getSQLOperator($op);
3564 if (!is_array($value)) {
3565 $value = array($value);
3568 $tmp_membership_sql_list = implode(', ', $value);
3569 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3570 SELECT DISTINCT mem.contact_id
3571 FROM civicrm_membership mem
3572 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3573 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3574 WHERE mem.membership_type_id IN (" .
3575 $tmp_membership_sql_list . ")
3576 AND mt.is_active = '1'
3577 AND mem_status.is_current_member = '1'
3578 AND mem_status.is_active = '1' ) ";
3582 * Build acl clauses.
3584 * @param string $tableAlias
3586 public function buildACLClause($tableAlias = 'contact_a') {
3587 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3591 * Add custom data to the columns.
3593 * @param bool $addFields
3594 * @param array $permCustomGroupIds
3596 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3597 if (empty($this->_customGroupExtends
)) {
3600 if (!is_array($this->_customGroupExtends
)) {
3601 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3603 $customGroupWhere = '';
3604 if (!empty($permCustomGroupIds)) {
3605 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3609 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3610 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3611 FROM civicrm_custom_group cg
3612 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3613 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3615 cg.is_active = 1 AND
3616 cf.is_active = 1 AND
3617 cf.is_searchable = 1
3618 ORDER BY cg.weight, cf.weight";
3619 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3622 while ($customDAO->fetch()) {
3623 if ($customDAO->table_name
!= $curTable) {
3624 $curTable = $customDAO->table_name
;
3625 $curFields = $curFilters = array();
3628 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3629 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3630 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3631 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3638 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3639 $this->_columns
[$curTable][$colKey] = array();
3643 $fieldName = 'custom_' . $customDAO->cf_id
;
3646 // this makes aliasing work in favor
3647 $curFields[$fieldName] = array(
3648 'name' => $customDAO->column_name
,
3649 'title' => $customDAO->label
,
3650 'dataType' => $customDAO->data_type
,
3651 'htmlType' => $customDAO->html_type
,
3654 if ($this->_customGroupFilters
) {
3655 // this makes aliasing work in favor
3656 $curFilters[$fieldName] = array(
3657 'name' => $customDAO->column_name
,
3658 'title' => $customDAO->label
,
3659 'dataType' => $customDAO->data_type
,
3660 'htmlType' => $customDAO->html_type
,
3664 switch ($customDAO->data_type
) {
3667 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3668 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3669 // CRM-6946, show time part for datetime date fields
3670 if ($customDAO->time_format
) {
3671 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3676 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3677 $curFilters[$fieldName]['options'] = array(
3678 '' => ts('- select -'),
3682 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3686 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3687 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3691 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3692 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3696 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3697 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3701 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3703 if (!empty($customDAO->option_group_id
)) {
3704 if (in_array($customDAO->html_type
, array(
3709 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3712 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3714 if ($this->_customGroupFilters
) {
3715 $curFilters[$fieldName]['options'] = array();
3716 $ogDAO = CRM_Core_DAO
::executeQuery("SELECT ov.value, ov.label FROM civicrm_option_value ov WHERE ov.option_group_id = %1 ORDER BY ov.weight", array(
3718 $customDAO->option_group_id
,
3722 while ($ogDAO->fetch()) {
3723 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3725 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3730 case 'StateProvince':
3731 if (in_array($customDAO->html_type
, array(
3732 'Multi-Select State/Province',
3734 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3737 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3739 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3743 if (in_array($customDAO->html_type
, array(
3744 'Multi-Select Country',
3746 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3749 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3751 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3754 case 'ContactReference':
3755 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3756 $curFilters[$fieldName]['name'] = 'display_name';
3757 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3759 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3760 $curFields[$fieldName]['name'] = 'display_name';
3761 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3765 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3766 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3769 if (!array_key_exists('type', $curFields[$fieldName])) {
3770 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3774 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3776 if ($this->_customGroupFilters
) {
3777 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3779 if ($this->_customGroupGroupBy
) {
3780 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3786 * Build custom data from clause.
3788 public function customDataFrom() {
3789 if (empty($this->_customGroupExtends
)) {
3792 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3794 foreach ($this->_columns
as $table => $prop) {
3795 if (substr($table, 0, 13) == 'civicrm_value' ||
3796 substr($table, 0, 12) == 'custom_value'
3798 $extendsTable = $mapper[$prop['extends']];
3800 // check field is in params
3801 if (!$this->isFieldSelected($prop)) {
3804 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3806 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3808 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3809 // handle for ContactReference
3810 if (array_key_exists('fields', $prop)) {
3811 foreach ($prop['fields'] as $fieldName => $field) {
3812 if (CRM_Utils_Array
::value('dataType', $field) ==
3815 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3817 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3826 * Check if the field is selected.
3828 * @param string $prop
3832 public function isFieldSelected($prop) {
3837 if (!empty($this->_params
['fields'])) {
3838 foreach (array_keys($prop['fields']) as $fieldAlias) {
3839 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3840 if ($customFieldId) {
3841 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3845 //might be survey response field.
3846 if (!empty($this->_params
['fields']['survey_response']) &&
3847 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3855 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3856 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3857 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3858 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3865 if (!empty($this->_params
['order_bys'])) {
3866 foreach (array_keys($prop['fields']) as $fieldAlias) {
3867 foreach ($this->_params
['order_bys'] as $orderBy) {
3868 if ($fieldAlias == $orderBy['column'] &&
3869 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3877 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3878 foreach ($prop['filters'] as $fieldAlias => $val) {
3887 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3888 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3889 ||
($attach != 'relative' &&
3890 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3896 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3897 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3908 * Check for empty order_by configurations and remove them.
3910 * Also set template to hide them.
3912 * @param array $formValues
3914 public function preProcessOrderBy(&$formValues) {
3915 // Object to show/hide form elements
3916 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3918 $_showHide->addShow('optionField_1');
3920 // Cycle through order_by options; skip any empty ones, and hide them as well
3923 if (!empty($formValues['order_bys'])) {
3924 foreach ($formValues['order_bys'] as $order_by) {
3925 if ($order_by['column'] && $order_by['column'] != '-') {
3926 $_showHide->addShow('optionField_' . $n);
3927 $orderBys[$n] = $order_by;
3932 for ($i = $n; $i <= 5; $i++
) {
3934 $_showHide->addHide('optionField_' . $i);
3938 // overwrite order_by options with modified values
3939 if (!empty($orderBys)) {
3940 $formValues['order_bys'] = $orderBys;
3943 $formValues['order_bys'] = array(1 => array('column' => '-'));
3946 // assign show/hide data to template
3947 $_showHide->addToTemplate();
3951 * Check if table name has columns in SELECT clause.
3953 * @param string $tableName
3954 * Name of table (index of $this->_columns array).
3958 public function isTableSelected($tableName) {
3959 return in_array($tableName, $this->selectedTables());
3963 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3965 * If the array is unset it will be built.
3970 public function selectedTables() {
3971 if (!$this->_selectedTables
) {
3972 $orderByColumns = array();
3973 if (array_key_exists('order_bys', $this->_params
) &&
3974 is_array($this->_params
['order_bys'])
3976 foreach ($this->_params
['order_bys'] as $orderBy) {
3977 $orderByColumns[] = $orderBy['column'];
3981 foreach ($this->_columns
as $tableName => $table) {
3982 if (array_key_exists('fields', $table)) {
3983 foreach ($table['fields'] as $fieldName => $field) {
3984 if (!empty($field['required']) ||
3985 !empty($this->_params
['fields'][$fieldName])
3987 $this->_selectedTables
[] = $tableName;
3992 if (array_key_exists('order_bys', $table)) {
3993 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3994 if (in_array($orderByName, $orderByColumns)) {
3995 $this->_selectedTables
[] = $tableName;
4000 if (array_key_exists('filters', $table)) {
4001 foreach ($table['filters'] as $filterName => $filter) {
4002 if (!empty($this->_params
["{$filterName}_value"]) ||
4003 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4005 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4008 $this->_selectedTables
[] = $tableName;
4015 return $this->_selectedTables
;
4019 * Add address fields.
4021 * @deprecated - use getAddressColumns which is a more accurate description
4022 * and also accepts an array of options rather than a long list
4024 * adding address fields to construct function in reports
4026 * @param bool $groupBy
4027 * Add GroupBy? Not appropriate for detail report.
4028 * @param bool $orderBy
4029 * Add GroupBy? Not appropriate for detail report.
4030 * @param bool $filters
4031 * @param array $defaults
4034 * address fields for construct clause
4036 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4037 $addressFields = array(
4038 'civicrm_address' => array(
4039 'dao' => 'CRM_Core_DAO_Address',
4041 'address_name' => array(
4042 'title' => ts('Address Name'),
4043 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4046 'street_address' => array(
4047 'title' => ts('Street Address'),
4048 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
4050 'supplemental_address_1' => array(
4051 'title' => ts('Supplementary Address Field 1'),
4052 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
4054 'supplemental_address_2' => array(
4055 'title' => ts('Supplementary Address Field 2'),
4056 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
4058 'street_number' => array(
4059 'name' => 'street_number',
4060 'title' => ts('Street Number'),
4062 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
4064 'street_name' => array(
4065 'name' => 'street_name',
4066 'title' => ts('Street Name'),
4068 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
4070 'street_unit' => array(
4071 'name' => 'street_unit',
4072 'title' => ts('Street Unit'),
4074 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
4077 'title' => ts('City'),
4078 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
4080 'postal_code' => array(
4081 'title' => ts('Postal Code'),
4082 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
4084 'postal_code_suffix' => array(
4085 'title' => ts('Postal Code Suffix'),
4086 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
4088 'country_id' => array(
4089 'title' => ts('Country'),
4090 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
4092 'state_province_id' => array(
4093 'title' => ts('State/Province'),
4094 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
4096 'county_id' => array(
4097 'title' => ts('County'),
4098 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
4101 'grouping' => 'location-fields',
4106 $addressFields['civicrm_address']['filters'] = array(
4107 'street_number' => array(
4108 'title' => ts('Street Number'),
4110 'name' => 'street_number',
4112 'street_name' => array(
4113 'title' => ts('Street Name'),
4114 'name' => 'street_name',
4115 'operator' => 'like',
4117 'postal_code' => array(
4118 'title' => ts('Postal Code'),
4120 'name' => 'postal_code',
4123 'title' => ts('City'),
4124 'operator' => 'like',
4127 'country_id' => array(
4128 'name' => 'country_id',
4129 'title' => ts('Country'),
4130 'type' => CRM_Utils_Type
::T_INT
,
4131 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4132 'options' => CRM_Core_PseudoConstant
::country(),
4134 'state_province_id' => array(
4135 'name' => 'state_province_id',
4136 'title' => ts('State/Province'),
4137 'type' => CRM_Utils_Type
::T_INT
,
4138 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4139 'options' => array(),
4141 'county_id' => array(
4142 'name' => 'county_id',
4143 'title' => ts('County'),
4144 'type' => CRM_Utils_Type
::T_INT
,
4145 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4146 'options' => array(),
4152 $addressFields['civicrm_address']['order_bys'] = array(
4153 'street_name' => array('title' => ts('Street Name')),
4154 'street_number' => array('title' => 'Odd / Even Street Number'),
4155 'street_address' => NULL,
4157 'postal_code' => NULL,
4162 $addressFields['civicrm_address']['group_bys'] = array(
4163 'street_address' => NULL,
4165 'postal_code' => NULL,
4166 'state_province_id' => array(
4167 'title' => ts('State/Province'),
4169 'country_id' => array(
4170 'title' => ts('Country'),
4172 'county_id' => array(
4173 'title' => ts('County'),
4177 return $addressFields;
4181 * Do AlterDisplay processing on Address Fields.
4184 * @param array $rows
4185 * @param int $rowNum
4186 * @param string $baseUrl
4187 * @param string $linkText
4191 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4192 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4193 $entryFound = FALSE;
4195 if (array_key_exists('civicrm_address_country_id', $row)) {
4196 if ($value = $row['civicrm_address_country_id']) {
4197 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4198 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4199 "reset=1&force=1&{$criteriaQueryParams}&" .
4200 "country_id_op=in&country_id_value={$value}",
4201 $this->_absoluteUrl
, $this->_id
4203 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4204 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4205 array(1 => $linkText)
4211 if (array_key_exists('civicrm_address_county_id', $row)) {
4212 if ($value = $row['civicrm_address_county_id']) {
4213 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4214 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4215 "reset=1&force=1&{$criteriaQueryParams}&" .
4216 "county_id_op=in&county_id_value={$value}",
4217 $this->_absoluteUrl
, $this->_id
4219 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4220 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4221 array(1 => $linkText)
4226 // handle state province
4227 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4228 if ($value = $row['civicrm_address_state_province_id']) {
4229 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4231 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4232 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4233 $this->_absoluteUrl
, $this->_id
4235 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4236 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4237 array(1 => $linkText)
4247 * Do AlterDisplay processing on Address Fields.
4250 * @param array $rows
4251 * @param int $rowNum
4252 * @param string $baseUrl
4253 * @param string $linkText
4257 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4258 $entryFound = FALSE;
4259 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4260 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4261 $addLinks = array('gender_id' => 'Gender');
4262 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4263 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4264 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4265 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4266 if (($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4267 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4277 * Adjusts dates passed in to YEAR() for fiscal year.
4279 * @param string $fieldName
4283 public function fiscalYearOffset($fieldName) {
4284 $config = CRM_Core_Config
::singleton();
4285 $fy = $config->fiscalYearStart
;
4286 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4287 ($fy['d'] == 1 && $fy['M'] == 1)
4289 return "YEAR( $fieldName )";
4291 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4292 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4296 * Add Address into From Table if required.
4298 public function addAddressFromClause() {
4299 // include address field if address column is to be included
4300 if ((isset($this->_addressField
) &&
4301 $this->_addressField
4303 $this->isTableSelected('civicrm_address')
4306 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4307 ON ({$this->_aliases['civicrm_contact']}.id =
4308 {$this->_aliases['civicrm_address']}.contact_id) AND
4309 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4314 * Add Phone into From Table if required.
4316 public function addPhoneFromClause() {
4317 // include address field if address column is to be included
4318 if ($this->isTableSelected('civicrm_phone')
4321 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4322 ON ({$this->_aliases['civicrm_contact']}.id =
4323 {$this->_aliases['civicrm_phone']}.contact_id) AND
4324 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4329 * Get phone columns to add to array.
4331 * @param array $options
4332 * - prefix Prefix to add to table (in case of more than one instance of the table)
4333 * - prefix_label Label to give columns from this phone table instance
4336 * phone columns definition
4338 public function getPhoneColumns($options = array()) {
4339 $defaultOptions = array(
4341 'prefix_label' => '',
4344 $options = array_merge($defaultOptions, $options);
4347 $options['prefix'] . 'civicrm_phone' => array(
4348 'dao' => 'CRM_Core_DAO_Phone',
4350 $options['prefix'] . 'phone' => array(
4351 'title' => ts($options['prefix_label'] . 'Phone'),
4361 * Get address columns to add to array.
4363 * @param array $options
4364 * - prefix Prefix to add to table (in case of more than one instance of the table)
4365 * - prefix_label Label to give columns from this address table instance
4368 * address columns definition
4370 public function getAddressColumns($options = array()) {
4373 'prefix_label' => '',
4377 'defaults' => array(),
4379 return $this->addAddressFields(
4380 $options['group_by'],
4381 $options['order_by'],
4382 $options['filters'],
4383 $options['defaults']
4388 * Get a standard set of contact fields.
4392 public function getBasicContactFields() {
4394 'sort_name' => array(
4395 'title' => ts('Contact Name'),
4400 'no_display' => TRUE,
4403 'prefix_id' => array(
4404 'title' => ts('Contact Prefix'),
4406 'first_name' => array(
4407 'title' => ts('First Name'),
4409 'nick_name' => array(
4410 'title' => ts('Nick Name'),
4412 'middle_name' => array(
4413 'title' => ts('Middle Name'),
4415 'last_name' => array(
4416 'title' => ts('Last Name'),
4418 'suffix_id' => array(
4419 'title' => ts('Contact Suffix'),
4421 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4422 'email_greeting_display' => array('title' => ts('Email Greeting')),
4423 'addressee_display' => array('title' => ts('Address Greeting')),
4424 'contact_type' => array(
4425 'title' => ts('Contact Type'),
4427 'contact_sub_type' => array(
4428 'title' => ts('Contact Subtype'),
4430 'gender_id' => array(
4431 'title' => ts('Gender'),
4433 'birth_date' => array(
4434 'title' => ts('Birth Date'),
4437 'title' => ts('Age'),
4438 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4440 'job_title' => array(
4441 'title' => ts('Contact Job title'),
4443 'organization_name' => array(
4444 'title' => ts('Organization Name'),
4446 'external_identifier' => array(
4447 'title' => ts('Contact identifier from external system'),
4453 * Add contact to group.
4455 * @param int $groupID
4457 public function add2group($groupID) {
4458 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4459 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4461 // here are we are prepending / adding contact id field that could be used for adding group
4462 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4463 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select
)) {
4464 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4467 $select = str_ireplace('SELECT ', $select, $this->_select
);
4470 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4471 $sql = str_replace('WITH ROLLUP', '', $sql);
4472 $dao = CRM_Core_DAO
::executeQuery($sql);
4474 $contact_ids = array();
4475 // Add resulting contacts to group
4476 while ($dao->fetch()) {
4477 if ($dao->addtogroup_contact_id
) {
4478 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4482 if (!empty($contact_ids)) {
4483 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4484 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4487 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4493 * Show charts on print screen.
4495 public static function uploadChartImage() {
4496 // upload strictly for '.png' images
4497 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4498 if (preg_match('/\.png$/', $name)) {
4500 // POST data is usually string data, but we are passing a RAW .png
4501 // so PHP is a bit confused and $_POST is empty. But it has saved
4502 // the raw bits into $HTTP_RAW_POST_DATA
4504 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4506 // prepare the directory
4507 $config = CRM_Core_Config
::singleton();
4509 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4511 if (!file_exists($defaultPath)) {
4512 mkdir($defaultPath, 0777, TRUE);
4515 // full path to the saved image including filename
4516 $destination = $defaultPath . $name;
4519 $jfh = fopen($destination, 'w') or die("can't open file");
4520 fwrite($jfh, $httpRawPostData);
4522 CRM_Utils_System
::civiExit();
4527 * Apply common settings to entityRef fields.
4529 * @param array $field
4530 * @param string $table
4532 private function setEntityRefDefaults(&$field, $table) {
4533 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4534 $field['attributes'] +
= array(
4535 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4537 'placeholder' => ts('- select -'),
4542 * Add link fields to the row.
4544 * Function adds the _link & _hover fields to the row.
4547 * @param string $baseUrl
4548 * @param string $linkText
4549 * @param string $value
4550 * @param string $fieldName
4551 * @param string $tablePrefix
4552 * @param string $fieldLabel
4556 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4557 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4558 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4559 "reset=1&force=1&{$criteriaQueryParams}&" .
4560 $fieldName . "_op=in&{$fieldName}_value={$value}",
4561 $this->_absoluteUrl
, $this->_id
4563 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4564 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4565 array(1 => $linkText, 2 => $fieldLabel)
4570 * Generate temporary table to hold all contributions with permissioned FTs.
4572 * @param object $query
4573 * @param string $alias
4574 * @param bool $return
4576 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4577 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4580 $financialTypes = NULL;
4581 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4582 if (empty($financialTypes)) {
4584 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4587 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4590 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4591 $query->_aliases
['civicrm_line_item'] = $alias;
4593 if (empty($query->_where
)) {
4594 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4596 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4597 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4598 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4599 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4600 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4601 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4603 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4604 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4605 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4606 CRM_Core_DAO
::executeQuery($sql);
4608 $query->_aliases
['civicrm_line_item'] = $temp;
4610 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4614 $query->_from
.= $from;