3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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();
93 protected $_defaults = array();
96 * By default most reports hide contact id.
97 * Setting this to true makes it available
99 protected $_exposeContactID = TRUE;
102 * Set of statistic fields
106 protected $_statFields = array();
109 * Set of statistics data
113 protected $_statistics = array();
116 * List of fields not to be repeated during display
120 protected $_noRepeats = array();
123 * List of fields not to be displayed
127 protected $_noDisplay = array();
130 * Object type that a custom group extends
134 protected $_customGroupExtends = NULL;
135 protected $_customGroupExtendsJoin = array();
136 protected $_customGroupFilters = TRUE;
137 protected $_customGroupGroupBy = FALSE;
138 protected $_customGroupJoin = 'LEFT JOIN';
143 protected $_tagFilter = FALSE;
146 * specify entity table for tags filter
148 protected $_tagFilterTable = 'civicrm_contact';
151 * Build groups filter.
155 protected $_groupFilter = FALSE;
162 public $_navigation = array();
164 public $_drilldownReport = array();
167 * Array of tabs to display on report.
169 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
171 * $this->tabs['OrderBy'] = array(
172 * 'title' => ts('Sorting'),
173 * 'tpl' => 'OrderBy',
174 * 'div_label' => 'order-by',
179 protected $tabs = array();
182 * An attribute for checkbox/radio form field layout
186 protected $_fourColumnAttribute = array(
187 '</td><td width="25%">',
188 '</td><td width="25%">',
189 '</td><td width="25%">',
193 protected $_force = 1;
195 protected $_params = NULL;
196 protected $_formValues = NULL;
197 protected $_instanceValues = NULL;
199 protected $_instanceForm = FALSE;
200 protected $_criteriaForm = FALSE;
202 protected $_instanceButtonName = NULL;
203 protected $_createNewButtonName = NULL;
204 protected $_printButtonName = NULL;
205 protected $_pdfButtonName = NULL;
206 protected $_csvButtonName = NULL;
207 protected $_groupButtonName = NULL;
208 protected $_chartButtonName = NULL;
209 protected $_csvSupported = TRUE;
210 protected $_add2groupSupported = TRUE;
211 protected $_groups = NULL;
212 protected $_grandFlag = FALSE;
213 protected $_rowsFound = NULL;
214 protected $_selectAliases = array();
215 protected $_rollup = NULL;
220 protected $_aliases = array();
236 protected $_limit = NULL;
239 * This can be set to specify a limit to the number of rows
240 * Since it is currently envisaged as part of the api usage it is only being applied
241 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
242 * of the code (see limit() fn
245 protected $_limitValue = NULL;
248 * This can be set to specify row offset
249 * See notes on _limitValue
252 protected $_offsetValue = NULL;
256 protected $_sections = NULL;
257 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
258 protected $_absoluteUrl = FALSE;
261 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
265 protected $_storeResultSet = FALSE;
268 * When _storeResultSet Flag is set use this var to store result set in form of array
272 protected $_resultSet = array();
275 * To what frequency group-by a date column
279 protected $_groupByDateFreq = array(
281 'YEARWEEK' => 'Week',
282 'QUARTER' => 'Quarter',
287 * Variables to hold the acl inner join and where clause
289 protected $_aclFrom = NULL;
290 protected $_aclWhere = NULL;
293 * Array of DAO tables having columns included in SELECT or ORDER BY clause
297 protected $_selectedTables;
300 * Output mode e.g 'print', 'csv', 'pdf'
303 protected $_outputMode;
305 public $_having = NULL;
306 public $_select = NULL;
307 public $_selectClauses = array();
308 public $_columnHeaders = array();
309 public $_orderBy = NULL;
310 public $_orderByFields = array();
311 public $_orderByArray = array();
312 public $_groupBy = NULL;
313 public $_whereClauses = array();
314 public $_havingClauses = array();
317 * DashBoardRowCount Dashboard row count
320 public $_dashBoardRowCount;
323 * Is this being called without a form controller (ie. the report is being render outside the normal form
324 * - e.g the api is retrieving the rows
327 public $noController = FALSE;
330 * Variable to hold the currency alias
332 protected $_currencyColumn = NULL;
337 protected $_interval;
342 protected $_sendmail;
355 * @var string Report description.
357 public $_description;
360 * @var bool Is an address field selected.
361 * This was intended to determine if the address table should be joined in
362 * The isTableSelected function is now preferred for this purpose
364 protected $_addressField;
367 * @var bool Is an email field selected.
368 * This was intended to determine if the email table should be joined in
369 * The isTableSelected function is now preferred for this purpose
371 protected $_emailField;
374 * @var bool Is a phone field selected.
375 * This was intended to determine if the phone table should be joined in
376 * The isTableSelected function is now preferred for this purpose
378 protected $_phoneField;
381 * @var bool Create new report instance? (or update existing) on save.
383 protected $_createNew;
388 public function __construct() {
389 parent
::__construct();
391 $this->addClass('crm-report-form');
393 if ($this->_tagFilter
) {
394 $this->buildTagFilter();
396 if ($this->_exposeContactID
) {
397 if (array_key_exists('civicrm_contact', $this->_columns
)) {
398 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
400 'title' => 'Contact ID',
406 if ($this->_groupFilter
) {
407 $this->buildGroupFilter();
410 // Get all custom groups
411 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
413 // Get the custom groupIds for which the user has VIEW permission
414 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
415 // and addCustomDataToColumns() will allow access to all custom groups.
416 $permCustomGroupIds = array();
417 if (!CRM_Core_Permission
::check('access all custom data')) {
418 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
419 // do not allow custom data for reports if user doesn't have
420 // permission to access custom data.
421 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
422 $this->_customGroupExtends
= array();
426 // merge custom data columns to _columns list, if any
427 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
429 // add / modify display columns, filters ..etc
430 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
432 //assign currencyColumn variable to tpl
433 $this->assign('currencyColumn', $this->_currencyColumn
);
437 * Shared pre-process function.
439 * If overriding preProcess function this should still be called.
443 public function preProcessCommon() {
445 = CRM_Utils_Request
::retrieve(
448 CRM_Core_DAO
::$_nullObject
451 $this->_dashBoardRowCount
452 = CRM_Utils_Request
::retrieve(
455 CRM_Core_DAO
::$_nullObject
458 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
460 $this->assign('section', $this->_section
);
461 CRM_Core_Region
::instance('page-header')->add(array(
462 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
464 if (!$this->noController
) {
465 $this->setID($this->get('instanceId'));
468 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
470 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
474 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
475 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
476 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
480 $this->assign('instanceId', $this->_id
);
481 $params = array('id' => $this->_id
);
482 $this->_instanceValues
= array();
483 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
485 $this->_instanceValues
487 if (empty($this->_instanceValues
)) {
488 CRM_Core_Error
::fatal("Report could not be loaded.");
490 $this->_title
= $this->_instanceValues
['title'];
491 if (!empty($this->_instanceValues
['permission']) &&
492 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
493 CRM_Core_Permission
::check('administer Reports')
496 CRM_Utils_System
::permissionDenied();
497 CRM_Utils_System
::civiExit();
500 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
502 $this->_formValues
= unserialize($formValues);
505 $this->_formValues
= NULL;
508 // lets always do a force if reset is found in the url.
509 if (!empty($_REQUEST['reset'])) {
514 $this->assign('mode', 'instance');
516 elseif (!$this->noController
) {
517 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
518 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
519 if (($instanceCount > 0) && $optionValueID) {
520 $this->assign('instanceUrl',
521 CRM_Utils_System
::url('civicrm/report/list',
522 "reset=1&ovid=$optionValueID"
526 if ($optionValueID) {
527 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
531 $this->assign('mode', 'template');
534 // lets display the Report Settings section
535 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
537 // Do not display Report Settings section if administer Reports permission is absent OR
538 // if report instance is reserved and administer reserved reports absent
539 if (!CRM_Core_Permission
::check('administer Reports') ||
540 ($this->_instanceValues
['is_reserved'] &&
541 !CRM_Core_Permission
::check('administer reserved reports'))
543 $this->_instanceForm
= FALSE;
546 $this->assign('criteriaForm', FALSE);
547 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
548 if (CRM_Core_Permission
::check('administer Reports') ||
549 CRM_Core_Permission
::check('access Report Criteria')
551 if (!$this->_instanceValues
['is_reserved'] ||
552 CRM_Core_Permission
::check('administer reserved reports')
554 $this->assign('criteriaForm', TRUE);
555 $this->_criteriaForm
= TRUE;
559 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
560 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
561 $this->_printButtonName
= $this->getButtonName('submit', 'print');
562 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
563 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
564 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
565 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
571 public function addBreadCrumb() {
575 'title' => ts('Report Templates'),
576 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
580 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
584 * Pre process function.
586 * Called prior to build form.
588 public function preProcess() {
589 $this->preProcessCommon();
592 $this->addBreadCrumb();
595 foreach ($this->_columns
as $tableName => $table) {
597 if (!isset($table['alias'])) {
598 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
602 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
605 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
607 $daoOrBaoName = NULL;
608 // higher preference to bao object
609 if (array_key_exists('bao', $table)) {
610 $daoOrBaoName = $table['bao'];
611 $expFields = $daoOrBaoName::exportableFields();
613 elseif (array_key_exists('dao', $table)) {
614 $daoOrBaoName = $table['dao'];
615 $expFields = $daoOrBaoName::export();
618 $expFields = array();
621 $doNotCopy = array('required');
623 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
624 foreach ($fieldGroups as $fieldGrp) {
625 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
626 foreach ($table[$fieldGrp] as $fieldName => $field) {
627 // $name is the field name used to reference the BAO/DAO export fields array
628 $name = isset($field['name']) ?
$field['name'] : $fieldName;
630 // Sometimes the field name key in the BAO/DAO export fields array is
631 // different from the actual database field name.
632 // Unset $field['name'] so that actual database field name can be obtained
633 // from the BAO/DAO export fields array.
634 unset($field['name']);
636 if (array_key_exists($name, $expFields)) {
637 foreach ($doNotCopy as $dnc) {
638 // unset the values we don't want to be copied.
639 unset($expFields[$name][$dnc]);
642 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
645 foreach ($expFields[$name] as $property => $val) {
646 if (!array_key_exists($property, $field)) {
647 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
654 if (!empty($field['no_repeat'])) {
655 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
657 if (!empty($field['no_display'])) {
658 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
661 // set alias = table-name, unless already set
662 $alias = isset($field['alias']) ?
$field['alias'] : (
663 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
665 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
667 // set name = fieldName, unless already set
668 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
669 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
672 // set dbAlias = alias.name, unless already set
673 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
674 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
676 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
679 // a few auto fills for filters
680 if ($fieldGrp == 'filters') {
681 // fill operator types
682 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
683 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
684 case CRM_Utils_Type
::T_MONEY
:
685 case CRM_Utils_Type
::T_FLOAT
:
686 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
689 case CRM_Utils_Type
::T_INT
:
690 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
693 case CRM_Utils_Type
::T_DATE
:
694 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
697 case CRM_Utils_Type
::T_BOOLEAN
:
698 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
699 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
700 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
711 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
713 // with multiple options operator-type is generally multi-select
714 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
715 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
717 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
728 // copy filters to a separate handy variable
729 if (array_key_exists('filters', $table)) {
730 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
733 if (array_key_exists('group_bys', $table)) {
734 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
737 if (array_key_exists('fields', $table)) {
738 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
743 $this->setDefaultValues(FALSE);
746 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
747 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
748 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
749 CRM_Report_Utils_Get
::processChart($this->_defaults
);
752 $this->_formValues
= $this->_defaults
;
753 $this->postProcess();
758 * Set default values.
760 * @param bool $freeze
764 public function setDefaultValues($freeze = TRUE) {
765 $freezeGroup = array();
767 // FIXME: generalizing form field naming conventions would reduce
768 // Lots of lines below.
769 foreach ($this->_columns
as $tableName => $table) {
770 if (array_key_exists('fields', $table)) {
771 foreach ($table['fields'] as $fieldName => $field) {
772 if (empty($field['no_display'])) {
773 if (isset($field['required'])) {
775 $this->_defaults
['fields'][$fieldName] = 1;
778 // find element object, so that we could use quickform's freeze method
779 // for required elements
780 $obj = $this->getElementFromGroup("fields", $fieldName);
782 $freezeGroup[] = $obj;
786 elseif (isset($field['default'])) {
787 $this->_defaults
['fields'][$fieldName] = $field['default'];
793 if (array_key_exists('group_bys', $table)) {
794 foreach ($table['group_bys'] as $fieldName => $field) {
795 if (isset($field['default'])) {
796 if (!empty($field['frequency'])) {
797 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
799 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
803 if (array_key_exists('filters', $table)) {
804 foreach ($table['filters'] as $fieldName => $field) {
805 if (isset($field['default'])) {
806 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
808 if (is_array($field['default'])) {
809 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
810 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
811 $this->_defaults
["{$fieldName}_relative"] = 0;
814 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
818 $this->_defaults
["{$fieldName}_value"] = $field['default'];
821 //assign default value as "in" for multiselect
822 //operator, To freeze the select element
823 if (CRM_Utils_Array
::value('operatorType', $field) ==
824 CRM_Report_Form
::OP_MULTISELECT
826 $this->_defaults
["{$fieldName}_op"] = 'in';
828 if (CRM_Utils_Array
::value('operatorType', $field) ==
829 CRM_Report_Form
::OP_ENTITYREF
831 $this->_defaults
["{$fieldName}_op"] = 'in';
833 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
834 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
836 $this->_defaults
["{$fieldName}_op"] = 'mhas';
838 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
839 $this->_defaults
["{$fieldName}_op"] = $op;
845 empty($this->_formValues
['order_bys']) &&
846 (array_key_exists('order_bys', $table) &&
847 is_array($table['order_bys']))
849 if (!array_key_exists('order_bys', $this->_defaults
)) {
850 $this->_defaults
['order_bys'] = array();
852 foreach ($table['order_bys'] as $fieldName => $field) {
853 if (!empty($field['default']) ||
!empty($field['default_order']) ||
854 CRM_Utils_Array
::value('default_is_section', $field) ||
855 !empty($field['default_weight'])
858 'column' => $fieldName,
859 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
860 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
863 if (!empty($field['default_weight'])) {
864 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
867 array_unshift($this->_defaults
['order_bys'], $order_by);
873 foreach ($this->_options
as $fieldName => $field) {
874 if (isset($field['default'])) {
875 $this->_defaults
['options'][$fieldName] = $field['default'];
880 if (!empty($this->_submitValues
)) {
881 $this->preProcessOrderBy($this->_submitValues
);
884 $this->preProcessOrderBy($this->_defaults
);
887 // lets finish freezing task here itself
888 if (!empty($freezeGroup)) {
889 foreach ($freezeGroup as $elem) {
894 if ($this->_formValues
) {
895 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
898 if ($this->_instanceValues
) {
899 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
902 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
904 return $this->_defaults
;
908 * Get element from group.
910 * @param string $group
911 * @param string $grpFieldName
915 public function getElementFromGroup($group, $grpFieldName) {
916 $eleObj = $this->getElement($group);
917 foreach ($eleObj->_elements
as $index => $obj) {
918 if ($grpFieldName == $obj->_attributes
['name']) {
926 * Setter for $_params.
928 * @param array $params
930 public function setParams($params) {
931 $this->_params
= $params;
937 * @param int $instanceID
939 public function setID($instanceID) {
940 $this->_id
= $instanceID;
944 * Setter for $_force.
948 public function setForce($isForce) {
949 $this->_force
= $isForce;
953 * Setter for $_limitValue.
955 * @param int $_limitValue
957 public function setLimitValue($_limitValue) {
958 $this->_limitValue
= $_limitValue;
962 * Setter for $_offsetValue.
964 * @param int $_offsetValue
966 public function setOffsetValue($_offsetValue) {
967 $this->_offsetValue
= $_offsetValue;
971 * Getter for $_defaultValues.
975 public function getDefaultValues() {
976 return $this->_defaults
;
980 * Add columns to report.
982 public function addColumns() {
985 foreach ($this->_columns
as $tableName => $table) {
986 if (array_key_exists('fields', $table)) {
987 foreach ($table['fields'] as $fieldName => $field) {
989 if (empty($field['no_display'])) {
990 foreach (array('table', 'field') as $var) {
991 if (!empty($
{$var}['grouping'])) {
992 if (!is_array($
{$var}['grouping'])) {
993 $tableName = $
{$var}['grouping'];
996 $tableName = array_keys($
{$var}['grouping']);
997 $tableName = $tableName[0];
998 $groupTitle = array_values($
{$var}['grouping']);
999 $groupTitle = $groupTitle[0];
1004 if (!$groupTitle && isset($table['group_title'])) {
1005 $groupTitle = $table['group_title'];
1006 // Having a group_title is secret code for being a custom group
1007 // which cryptically translates to needing an accordion.
1008 // here we make that explicit.
1009 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1012 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1013 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1014 $colGroups[$tableName]['group_title'] = $groupTitle;
1016 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1022 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1023 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1025 if (!empty($colGroups)) {
1026 $this->tabs
['FieldSelection'] = array(
1027 'title' => ts('Columns'),
1028 'tpl' => 'FieldSelection',
1029 'div_label' => 'col-groups',
1032 // Note this assignment is only really required in buildForm. It is being 'over-called'
1033 // to reduce risk of being missed due to overridden functions.
1034 $this->assign('tabs', $this->tabs
);
1037 $this->assign('colGroups', $colGroups);
1041 * Add filters to report.
1043 public function addFilters() {
1044 $filters = $filterGroups = array();
1047 foreach ($this->_filters
as $table => $attributes) {
1048 if (isset($this->_columns
[$table]['group_title'])) {
1049 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1050 // which magically means to 'display in an accordian'
1051 // here we make this explicit.
1052 $filterGroups[$table] = array(
1053 'group_title' => $this->_columns
[$table]['group_title'],
1054 'use_accordian_for_field_selection' => TRUE,
1058 foreach ($attributes as $fieldName => $field) {
1059 // get ready with option value pair
1060 // @ 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
1062 $operations = $this->getOperationPair(
1063 CRM_Utils_Array
::value('operatorType', $field),
1066 $filters[$table][$fieldName] = $field;
1068 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1069 case CRM_Report_Form
::OP_MONTH
:
1070 if (!array_key_exists('options', $field) ||
1071 !is_array($field['options']) ||
empty($field['options'])
1073 // If there's no option list for this filter, define one.
1074 $field['options'] = array(
1076 2 => ts('February'),
1083 9 => ts('September'),
1084 10 => ts('October'),
1085 11 => ts('November'),
1086 12 => ts('December'),
1088 // Add this option list to this column _columns. This is
1089 // required so that filter statistics show properly.
1090 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1092 case CRM_Report_Form
::OP_MULTISELECT
:
1093 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1094 // assume a multi-select field
1095 if (!empty($field['options']) ||
1096 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1098 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1099 if (count($operations) <= 1) {
1102 if ($fieldName == 'state_province_id' ||
1103 $fieldName == 'county_id'
1105 $this->addChainSelect($fieldName . '_value', array(
1112 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1113 'style' => 'min-width:250px',
1114 'class' => 'crm-select2 huge',
1116 'placeholder' => ts('- select -'),
1122 case CRM_Report_Form
::OP_SELECT
:
1123 // assume a select field
1124 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1125 if (!empty($field['options'])) {
1126 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1130 case CRM_Report_Form
::OP_ENTITYREF
:
1131 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1132 $this->setEntityRefDefaults($field, $table);
1133 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1136 case CRM_Report_Form
::OP_DATE
:
1137 // build datetime fields
1138 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1142 case CRM_Report_Form
::OP_DATETIME
:
1143 // build datetime fields
1144 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1148 case CRM_Report_Form
::OP_INT
:
1149 case CRM_Report_Form
::OP_FLOAT
:
1150 // and a min value input box
1151 $this->add('text', "{$fieldName}_min", ts('Min'));
1152 // and a max value input box
1153 $this->add('text', "{$fieldName}_max", ts('Max'));
1155 // default type is string
1156 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1157 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1159 // we need text box for value input
1160 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1165 if (!empty($filters)) {
1166 $this->tabs
['Filters'] = array(
1167 'title' => ts('Filters'),
1169 'div_label' => 'set-filters',
1172 $this->assign('filters', $filters);
1173 $this->assign('filterGroups', $filterGroups);
1177 * Function to assign the tabs to the template in the correct order.
1179 * We want the tabs to wind up in this order (if not overridden).
1187 protected function assignTabs() {
1195 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1196 $order = array_merge($order, $this->tabs
);
1197 $this->assign('tabs', $order);
1201 * Add options defined in $this->_options to the report.
1203 public function addOptions() {
1204 if (!empty($this->_options
)) {
1205 // FIXME: For now lets build all elements as checkboxes.
1206 // Once we clear with the format we can build elements based on type
1208 foreach ($this->_options
as $fieldName => $field) {
1211 if ($field['type'] == 'select') {
1212 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1214 elseif ($field['type'] == 'checkbox') {
1215 $options[$field['title']] = $fieldName;
1216 $this->addCheckBox($fieldName, NULL,
1218 NULL, NULL, NULL, $this->_fourColumnAttribute
1223 if (!empty($this->_options
)) {
1224 $this->tabs
['ReportOptions'] = array(
1225 'title' => ts('Display Options'),
1226 'tpl' => 'ReportOptions',
1227 'div_label' => 'other-options',
1230 $this->assign('otherOptions', $this->_options
);
1234 * Add chart options to the report.
1236 public function addChartOptions() {
1237 if (!empty($this->_charts
)) {
1238 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1239 $this->assign('charts', $this->_charts
);
1240 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1245 * Add group by options to the report.
1247 public function addGroupBys() {
1248 $options = $freqElements = array();
1250 foreach ($this->_columns
as $tableName => $table) {
1251 if (array_key_exists('group_bys', $table)) {
1252 foreach ($table['group_bys'] as $fieldName => $field) {
1253 if (!empty($field)) {
1254 $options[$field['title']] = $fieldName;
1255 if (!empty($field['frequency'])) {
1256 $freqElements[$field['title']] = $fieldName;
1262 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1263 NULL, NULL, NULL, $this->_fourColumnAttribute
1265 $this->assign('groupByElements', $options);
1266 if (!empty($options)) {
1267 $this->tabs
['GroupBy'] = array(
1268 'title' => ts('Grouping'),
1270 'div_label' => 'group-by-elements',
1274 foreach ($freqElements as $name) {
1275 $this->addElement('select', "group_bys_freq[$name]",
1276 ts('Frequency'), $this->_groupByDateFreq
1282 * Add data for order by tab.
1284 public function addOrderBys() {
1286 foreach ($this->_columns
as $tableName => $table) {
1288 // Report developer may define any column to order by; include these as order-by options.
1289 if (array_key_exists('order_bys', $table)) {
1290 foreach ($table['order_bys'] as $fieldName => $field) {
1291 if (!empty($field)) {
1292 $options[$fieldName] = $field['title'];
1297 // Add searchable custom fields as order-by options, if so requested
1298 // (These are already indexed, so allowing to order on them is cheap.)
1300 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1301 array_key_exists('extends', $table) && !empty($table['extends'])
1303 foreach ($table['fields'] as $fieldName => $field) {
1304 if (empty($field['no_display'])) {
1305 $options[$fieldName] = $field['title'];
1313 $this->assign('orderByOptions', $options);
1314 if (!empty($options)) {
1315 $this->tabs
['OrderBy'] = array(
1316 'title' => ts('Sorting'),
1318 'div_label' => 'order-by-elements',
1322 if (!empty($options)) {
1324 '-' => ' - none - ',
1326 for ($i = 1; $i <= 5; $i++
) {
1327 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1328 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1329 'ASC' => 'Ascending',
1330 'DESC' => 'Descending',
1332 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1333 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1339 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1341 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1342 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1345 public function buildInstanceAndButtons() {
1346 CRM_Report_Form_Instance
::buildForm($this);
1348 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1350 $this->addElement('submit', $this->_instanceButtonName
, $label);
1351 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1352 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1355 $this->addElement('submit', $this->_createNewButtonName
,
1356 ts('Save a Copy') . '...');
1358 $this->assign('instanceForm', $this->_instanceForm
);
1360 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1361 $this->addElement('submit', $this->_printButtonName
, $label);
1363 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1364 $this->addElement('submit', $this->_pdfButtonName
, $label);
1366 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1368 if ($this->_csvSupported
) {
1369 $this->addElement('submit', $this->_csvButtonName
, $label);
1372 if (CRM_Core_Permission
::check('administer Reports') &&
1373 $this->_add2groupSupported
1375 $this->addElement('select', 'groups', ts('Group'),
1376 array('' => ts('Add Contacts to Group')) +
1377 CRM_Core_PseudoConstant
::nestedGroup(),
1378 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1380 $this->assign('group', TRUE);
1383 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1385 $this->addChartOptions();
1386 $this->addButtons(array(
1389 'name' => ts('Preview Report'),
1390 'isDefault' => TRUE,
1397 * Main build form function.
1399 public function buildQuickForm() {
1400 $this->addColumns();
1402 $this->addFilters();
1404 $this->addOptions();
1406 $this->addGroupBys();
1408 $this->addOrderBys();
1410 $this->buildInstanceAndButtons();
1412 // Add form rule for report.
1413 if (is_callable(array(
1417 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1419 $this->assignTabs();
1423 * A form rule function to ensure that fields selected in group_by
1424 * (if any) should only be the ones present in display/select fields criteria;
1425 * note: works if and only if any custom field selected in group_by.
1427 * @param array $fields
1428 * @param array $ignoreFields
1432 public function customDataFormRule($fields, $ignoreFields = array()) {
1434 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1435 !empty($fields['group_bys'])
1437 foreach ($this->_columns
as $tableName => $table) {
1438 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1439 substr($tableName, 0, 12) == 'custom_value') &&
1440 !empty($this->_columns
[$tableName]['fields'])
1442 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1443 if (array_key_exists($fieldName, $fields['group_bys']) &&
1444 !array_key_exists($fieldName, $fields['fields'])
1446 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1448 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1449 foreach ($fields['fields'] as $fld => $val) {
1450 if (!array_key_exists($fld, $fields['group_bys']) &&
1451 !in_array($fld, $ignoreFields)
1453 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1465 * Get operators to display on form.
1467 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1469 * @param string $type
1470 * @param string $fieldName
1474 public function getOperationPair($type = "string", $fieldName = NULL) {
1475 // FIXME: At some point we should move these key-val pairs
1476 // to option_group and option_value table.
1478 case CRM_Report_Form
::OP_INT
:
1479 case CRM_Report_Form
::OP_FLOAT
:
1482 'lte' => ts('Is less than or equal to'),
1483 'gte' => ts('Is greater than or equal to'),
1484 'bw' => ts('Is between'),
1485 'eq' => ts('Is equal to'),
1486 'lt' => ts('Is less than'),
1487 'gt' => ts('Is greater than'),
1488 'neq' => ts('Is not equal to'),
1489 'nbw' => ts('Is not between'),
1490 'nll' => ts('Is empty (Null)'),
1491 'nnll' => ts('Is not empty (Null)'),
1495 case CRM_Report_Form
::OP_SELECT
:
1497 'eq' => ts('Is equal to'),
1501 case CRM_Report_Form
::OP_MONTH
:
1502 case CRM_Report_Form
::OP_MULTISELECT
:
1503 case CRM_Report_Form
::OP_ENTITYREF
:
1506 'in' => ts('Is one of'),
1507 'notin' => ts('Is not one of'),
1511 case CRM_Report_Form
::OP_DATE
:
1514 'nll' => ts('Is empty (Null)'),
1515 'nnll' => ts('Is not empty (Null)'),
1519 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1520 // use this operator for the values, concatenated with separator. For e.g if
1521 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1523 'mhas' => ts('Is one of'),
1524 'mnot' => ts('Is not one of'),
1531 'has' => ts('Contains'),
1532 'sw' => ts('Starts with'),
1533 'ew' => ts('Ends with'),
1534 'nhas' => ts('Does not contain'),
1535 'eq' => ts('Is equal to'),
1536 'neq' => ts('Is not equal to'),
1537 'nll' => ts('Is empty (Null)'),
1538 'nnll' => ts('Is not empty (Null)'),
1545 * Build the tag filter field to display on the filters tab.
1547 public function buildTagFilter() {
1548 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1549 if (!empty($contactTags)) {
1550 $this->_columns
['civicrm_tag'] = array(
1551 'dao' => 'CRM_Core_DAO_Tag',
1555 'title' => ts('Tag'),
1557 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1558 'options' => $contactTags,
1566 * Adds group filters to _columns (called from _Construct).
1568 public function buildGroupFilter() {
1569 $this->_columns
['civicrm_group']['filters'] = array(
1571 'name' => 'group_id',
1572 'title' => ts('Group'),
1573 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1575 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1578 if (empty($this->_columns
['civicrm_group']['dao'])) {
1579 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1581 if (empty($this->_columns
['civicrm_group']['alias'])) {
1582 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1587 * Get SQL operator from form text version.
1589 * @param string $operator
1593 public function getSQLOperator($operator = "like") {
1594 switch ($operator) {
1627 return 'IS NOT NULL';
1636 * Generate where clause.
1638 * This can be overridden in reports for special treatment of a field
1640 * @param array $field Field specifications
1641 * @param string $op Query operator (not an exact match to sql)
1642 * @param mixed $value
1646 * @return null|string
1648 public function whereClause(&$field, $op, $value, $min, $max) {
1650 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1656 if (($min !== NULL && strlen($min) > 0) ||
1657 ($max !== NULL && strlen($max) > 0)
1659 $min = CRM_Utils_Type
::escape($min, $type);
1660 $max = CRM_Utils_Type
::escape($max, $type);
1664 $clauses[] = "( {$field['dbAlias']} >= $min )";
1667 $clauses[] = "( {$field['dbAlias']} < $min )";
1672 $clauses[] = "( {$field['dbAlias']} <= $max )";
1675 $clauses[] = "( {$field['dbAlias']} > $max )";
1679 if (!empty($clauses)) {
1681 $clause = implode(' AND ', $clauses);
1684 $clause = implode(' OR ', $clauses);
1692 if ($value !== NULL && strlen($value) > 0) {
1693 $value = CRM_Utils_Type
::escape($value, $type);
1694 if (strpos($value, '%') === FALSE) {
1695 $value = "'%{$value}%'";
1698 $value = "'{$value}'";
1700 $sqlOP = $this->getSQLOperator($op);
1701 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1707 if (is_string($value) && strlen($value)) {
1708 $value = explode(',', $value);
1710 if ($value !== NULL && is_array($value) && count($value) > 0) {
1711 $sqlOP = $this->getSQLOperator($op);
1712 if (CRM_Utils_Array
::value('type', $field) ==
1713 CRM_Utils_Type
::T_STRING
1715 //cycle through selections and escape values
1716 foreach ($value as $key => $selection) {
1717 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1720 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1724 // for numerical values
1725 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1728 if ($op == 'notin') {
1729 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1732 $clause = "( " . $clause . " )";
1738 // mhas == multiple has
1739 if ($value !== NULL && count($value) > 0) {
1740 $sqlOP = $this->getSQLOperator($op);
1742 = "{$field['dbAlias']} REGEXP '[[:cntrl:]]" . implode('|', $value) .
1748 // mnot == multiple is not one of
1749 if ($value !== NULL && count($value) > 0) {
1750 $sqlOP = $this->getSQLOperator($op);
1752 = "( {$field['dbAlias']} NOT REGEXP '[[:cntrl:]]" . implode('|', $value) .
1753 "[[:cntrl:]]' OR {$field['dbAlias']} IS NULL )";
1759 if ($value !== NULL && strlen($value) > 0) {
1760 $value = CRM_Utils_Type
::escape($value, $type);
1761 if (strpos($value, '%') === FALSE) {
1763 $value = "'{$value}%'";
1766 $value = "'%{$value}'";
1770 $value = "'{$value}'";
1772 $sqlOP = $this->getSQLOperator($op);
1773 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1779 $sqlOP = $this->getSQLOperator($op);
1780 $clause = "( {$field['dbAlias']} $sqlOP )";
1784 if ($value !== NULL && strlen($value) > 0) {
1785 if (isset($field['clause'])) {
1786 // FIXME: we not doing escape here. Better solution is to use two
1787 // different types - data-type and filter-type
1788 $clause = $field['clause'];
1791 $value = CRM_Utils_Type
::escape($value, $type);
1792 $sqlOP = $this->getSQLOperator($op);
1793 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1794 $value = "'{$value}'";
1796 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1802 if (!empty($field['group']) && $clause) {
1803 $clause = $this->whereGroupClause($field, $value, $op);
1805 elseif (!empty($field['tag']) && $clause) {
1806 // not using left join in query because if any contact
1807 // belongs to more than one tag, results duplicate
1809 $clause = $this->whereTagClause($field, $value, $op);
1811 elseif (!empty($field['membership_org']) && $clause) {
1812 $clause = $this->whereMembershipOrgClause($value, $op);
1814 elseif (!empty($field['membership_type']) && $clause) {
1815 $clause = $this->whereMembershipTypeClause($value, $op);
1821 * Get SQL where clause for a date field.
1823 * @param string $fieldName
1825 * @param string $from
1827 * @param string $type
1828 * @param string $fromTime
1829 * @param string $toTime
1831 * @return null|string
1833 public function dateClause(
1835 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1838 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1839 $sqlOP = $this->getSQLOperator($relative);
1840 return "( {$fieldName} {$sqlOP} )";
1843 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1846 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1847 $clauses[] = "( {$fieldName} >= $from )";
1851 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1852 $clauses[] = "( {$fieldName} <= {$to} )";
1855 if (!empty($clauses)) {
1856 return implode(' AND ', $clauses);
1863 * Possibly unused function.
1865 * @todo - could not find any instances where this is called
1867 * @param bool $relative
1868 * @param string $from
1871 * @return string|NULL
1873 public function dateDisplay($relative, $from, $to) {
1874 list($from, $to) = $this->getFromTo($relative, $from, $to);
1877 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1880 $clauses[] = 'Past';
1884 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1887 $clauses[] = 'Today';
1890 if (!empty($clauses)) {
1891 return implode(' - ', $clauses);
1898 * Get values for from and to for date ranges.
1900 * @param bool $relative
1901 * @param string $from
1903 * @param string $fromTime
1904 * @param string $toTime
1908 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1909 if (empty($toTime)) {
1912 //FIX ME not working for relative
1914 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1915 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1916 $from = substr($dateRange['from'], 0, 8);
1917 //Take only Date Part, Sometime Time part is also present in 'to'
1918 $to = substr($dateRange['to'], 0, 8);
1920 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1921 $to = CRM_Utils_Date
::processDate($to, $toTime);
1922 return array($from, $to);
1926 * Alter display of rows.
1928 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1929 * such as rendering contacts as links.
1931 * @param array $rows
1932 * Rows generated by SQL, with an array for each row.
1934 public function alterDisplay(&$rows) {
1938 * Alter the way in which custom data fields are displayed.
1940 * @param array $rows
1942 public function alterCustomDataDisplay(&$rows) {
1943 // custom code to alter rows having custom values
1944 if (empty($this->_customGroupExtends
)) {
1948 $customFieldIds = array();
1949 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1950 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1951 $customFieldIds[$fieldAlias] = $fieldId;
1954 if (empty($customFieldIds)) {
1958 $customFields = $fieldValueMap = array();
1959 $customFieldCols = array(
1967 // skip for type date and ContactReference since date format is already handled
1969 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1970 FROM civicrm_custom_field cf
1971 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1972 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1973 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1974 cg.is_active = 1 AND
1975 cf.is_active = 1 AND
1976 cf.is_searchable = 1 AND
1977 cf.data_type NOT IN ('ContactReference', 'Date') AND
1978 cf.id IN (" . implode(",", $customFieldIds) . ")";
1980 $dao = CRM_Core_DAO
::executeQuery($query);
1981 while ($dao->fetch()) {
1982 foreach ($customFieldCols as $key) {
1983 $customFields[$dao->table_name
. '_custom_' .
1984 $dao->id
][$key] = $dao->$key;
1986 if ($dao->option_group_id
) {
1987 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1992 $entryFound = FALSE;
1993 foreach ($rows as $rowNum => $row) {
1994 foreach ($row as $tableCol => $val) {
1995 if (array_key_exists($tableCol, $customFields)) {
1996 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
2001 // skip looking further in rows, if first row itself doesn't
2002 // have the column we need
2011 * @param $customField
2012 * @param $fieldValueMap
2014 * @return float|string|void
2016 public function formatCustomValues($value, $customField, $fieldValueMap) {
2017 if (CRM_Utils_System
::isNull($value)) {
2021 $htmlType = $customField['html_type'];
2023 switch ($customField['data_type']) {
2025 if ($value == '1') {
2026 $retValue = ts('Yes');
2029 $retValue = ts('No');
2034 $retValue = CRM_Utils_System
::formatWikiURL($value);
2046 if ($htmlType == 'Text') {
2047 $retValue = (float) $value;
2051 if ($htmlType == 'Text') {
2052 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2057 if (in_array($htmlType, array(
2064 case 'StateProvince':
2067 switch ($htmlType) {
2068 case 'Multi-Select Country':
2069 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2070 $customData = array();
2071 foreach ($value as $val) {
2073 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
2076 $retValue = implode(', ', $customData);
2079 case 'Select Country':
2080 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
2083 case 'Select State/Province':
2084 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2087 case 'Multi-Select State/Province':
2088 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2089 $customData = array();
2090 foreach ($value as $val) {
2092 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
2095 $retValue = implode(', ', $customData);
2100 case 'Autocomplete-Select':
2101 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2105 case 'AdvMulti-Select':
2106 case 'Multi-Select':
2107 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2108 $customData = array();
2109 foreach ($value as $val) {
2111 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2114 $retValue = implode(', ', $customData);
2132 public function removeDuplicates(&$rows) {
2133 if (empty($this->_noRepeats
)) {
2136 $checkList = array();
2138 foreach ($rows as $key => $list) {
2139 foreach ($list as $colName => $colVal) {
2140 if (array_key_exists($colName, $checkList) &&
2141 $checkList[$colName] == $colVal
2143 $rows[$key][$colName] = "";
2145 if (in_array($colName, $this->_noRepeats
)) {
2146 $checkList[$colName] = $colVal;
2155 * @param bool $subtotal
2157 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2158 foreach ($row as $colName => $colVal) {
2159 if (in_array($colName, $fields)) {
2161 elseif (isset($this->_columnHeaders
[$colName])) {
2163 $row[$colName] = "Subtotal";
2167 unset($row[$colName]);
2178 public function grandTotal(&$rows) {
2179 if (!$this->_rollup ||
($this->_rollup
== '') ||
2180 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2184 $lastRow = array_pop($rows);
2186 foreach ($this->_columnHeaders
as $fld => $val) {
2187 if (!in_array($fld, $this->_statFields
)) {
2188 if (!$this->_grandFlag
) {
2189 $lastRow[$fld] = "Grand Total";
2190 $this->_grandFlag
= TRUE;
2193 $lastRow[$fld] = "";
2198 $this->assign('grandStat', $lastRow);
2204 * @param bool $pager
2206 public function formatDisplay(&$rows, $pager = TRUE) {
2207 // set pager based on if any limit was applied in the query.
2212 // allow building charts if any
2213 if (!empty($this->_params
['charts']) && !empty($rows)) {
2214 $this->buildChart($rows);
2215 $this->assign('chartEnabled', TRUE);
2216 $this->_chartId
= "{$this->_params['charts']}_" .
2217 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2219 $this->assign('chartId', $this->_chartId
);
2222 // unset columns not to be displayed.
2223 foreach ($this->_columnHeaders
as $key => $value) {
2224 if (!empty($value['no_display'])) {
2225 unset($this->_columnHeaders
[$key]);
2229 // unset columns not to be displayed.
2230 if (!empty($rows)) {
2231 foreach ($this->_noDisplay
as $noDisplayField) {
2232 foreach ($rows as $rowNum => $row) {
2233 unset($this->_columnHeaders
[$noDisplayField]);
2238 // build array of section totals
2239 $this->sectionTotals();
2241 // process grand-total row
2242 $this->grandTotal($rows);
2244 // use this method for formatting rows for display purpose.
2245 $this->alterDisplay($rows);
2246 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2248 // use this method for formatting custom rows for display purpose.
2249 $this->alterCustomDataDisplay($rows);
2255 public function buildChart(&$rows) {
2256 // override this method for building charts.
2259 // select() method below has been added recently (v3.3), and many of the report templates might
2260 // still be having their own select() method. We should fix them as and when encountered and move
2261 // towards generalizing the select() method below.
2264 * Generate the SELECT clause and set class variable $_select
2266 public function select() {
2267 $select = $this->_selectAliases
= array();
2269 foreach ($this->_columns
as $tableName => $table) {
2270 if (array_key_exists('fields', $table)) {
2271 foreach ($table['fields'] as $fieldName => $field) {
2272 if ($tableName == 'civicrm_address') {
2273 $this->_addressField
= TRUE;
2275 if ($tableName == 'civicrm_email') {
2276 $this->_emailField
= TRUE;
2278 if ($tableName == 'civicrm_phone') {
2279 $this->_phoneField
= TRUE;
2282 if (!empty($field['required']) ||
2283 !empty($this->_params
['fields'][$fieldName])
2286 // 1. In many cases we want select clause to be built in slightly different way
2287 // for a particular field of a particular type.
2288 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2290 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2291 if ($selectClause) {
2292 $select[] = $selectClause;
2296 // include statistics columns only if set
2297 if (!empty($field['statistics'])) {
2298 foreach ($field['statistics'] as $stat => $label) {
2299 $alias = "{$tableName}_{$fieldName}_{$stat}";
2300 switch (strtolower($stat)) {
2303 $select[] = "$stat({$field['dbAlias']}) as $alias";
2304 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2305 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2306 $this->_statFields
[$label] = $alias;
2307 $this->_selectAliases
[] = $alias;
2311 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2312 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2313 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2314 $this->_statFields
[$label] = $alias;
2315 $this->_selectAliases
[] = $alias;
2318 case 'count_distinct':
2319 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2320 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2321 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2322 $this->_statFields
[$label] = $alias;
2323 $this->_selectAliases
[] = $alias;
2327 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2328 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2329 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2330 $this->_statFields
[$label] = $alias;
2331 $this->_selectAliases
[] = $alias;
2337 $alias = "{$tableName}_{$fieldName}";
2338 $select[] = "{$field['dbAlias']} as $alias";
2339 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2340 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2341 $this->_selectAliases
[] = $alias;
2347 // select for group bys
2348 if (array_key_exists('group_bys', $table)) {
2349 foreach ($table['group_bys'] as $fieldName => $field) {
2351 if ($tableName == 'civicrm_address') {
2352 $this->_addressField
= TRUE;
2354 if ($tableName == 'civicrm_email') {
2355 $this->_emailField
= TRUE;
2357 if ($tableName == 'civicrm_phone') {
2358 $this->_phoneField
= TRUE;
2360 // 1. In many cases we want select clause to be built in slightly different way
2361 // for a particular field of a particular type.
2362 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2364 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2365 if ($selectClause) {
2366 $select[] = $selectClause;
2370 if (!empty($this->_params
['group_bys']) &&
2371 !empty($this->_params
['group_bys'][$fieldName]) &&
2372 !empty($this->_params
['group_bys_freq'])
2374 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2376 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2377 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2378 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2379 $field['title'] = 'Week';
2383 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2384 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2385 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2386 $field['title'] = 'Year';
2390 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2391 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2392 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2393 $field['title'] = 'Month';
2397 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2398 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2399 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2400 $field['title'] = 'Quarter';
2403 // for graphs and charts -
2404 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2405 $this->_interval
= $field['title'];
2406 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2407 = $field['title'] . ' Beginning';
2408 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2409 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2411 // just to make sure these values are transferred to rows.
2412 // since we 'll need them for calculation purpose,
2413 // e.g making subtotals look nicer or graphs
2414 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2415 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2422 $this->_selectClauses
= $select;
2423 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2427 * @param string $tableName
2429 * @param string $fieldName
2434 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2438 public function where() {
2439 $this->storeWhereHavingClauseArray();
2441 if (empty($this->_whereClauses
)) {
2442 $this->_where
= "WHERE ( 1 ) ";
2443 $this->_having
= "";
2446 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2449 if ($this->_aclWhere
) {
2450 $this->_where
.= " AND {$this->_aclWhere} ";
2453 if (!empty($this->_havingClauses
)) {
2454 // use this clause to construct group by clause.
2455 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2460 * Store Where clauses into an array - breaking out this step makes
2461 * over-riding more flexible as the clauses can be used in constructing a
2462 * temp table that may not be part of the final where clause or added
2463 * in other functions
2465 public function storeWhereHavingClauseArray() {
2466 foreach ($this->_columns
as $tableName => $table) {
2467 if (array_key_exists('filters', $table)) {
2468 foreach ($table['filters'] as $fieldName => $field) {
2469 // respect pseudofield to filter spec so fields can be marked as
2470 // not to be handled here
2471 if (!empty($field['pseudofield'])) {
2475 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2476 if (CRM_Utils_Array
::value('operatorType', $field) ==
2477 CRM_Report_Form
::OP_MONTH
2479 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2480 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2481 if (is_array($value) && !empty($value)) {
2483 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2488 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2489 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2490 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2491 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2492 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2493 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2497 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2499 $clause = $this->whereClause($field,
2501 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2502 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2503 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2508 if (!empty($clause)) {
2509 if (!empty($field['having'])) {
2510 $this->_havingClauses
[] = $clause;
2513 $this->_whereClauses
[] = $clause;
2522 public function processReportMode() {
2523 $buttonName = $this->controller
->getButtonName();
2525 $output = CRM_Utils_Request
::retrieve(
2528 CRM_Core_DAO
::$_nullObject
2532 = CRM_Utils_Request
::retrieve(
2535 CRM_Core_DAO
::$_nullObject
2538 $this->_absoluteUrl
= FALSE;
2540 $this->assign('printOnly', FALSE);
2542 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2543 ($this->_sendmail
&& !$output)
2545 $this->assign('printOnly', TRUE);
2547 $this->assign('outputMode', 'print');
2548 $this->_outputMode
= 'print';
2549 if ($this->_sendmail
) {
2550 $this->_absoluteUrl
= TRUE;
2553 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2554 $this->assign('printOnly', TRUE);
2556 $this->assign('outputMode', 'pdf');
2557 $this->_outputMode
= 'pdf';
2558 $this->_absoluteUrl
= TRUE;
2560 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2561 $this->assign('printOnly', TRUE);
2563 $this->assign('outputMode', 'csv');
2564 $this->_outputMode
= 'csv';
2565 $this->_absoluteUrl
= TRUE;
2567 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2568 $this->assign('outputMode', 'group');
2569 $this->_outputMode
= 'group';
2571 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2572 $this->assign('outputMode', 'create_report');
2573 $this->_outputMode
= 'create_report';
2576 $this->assign('outputMode', 'html');
2577 $this->_outputMode
= 'html';
2580 // Get today's date to include in printed reports
2582 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2583 $this->assign('reportDate', $reportDate);
2588 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2590 public function beginPostProcess() {
2591 $this->setParams($this->controller
->exportValues($this->_name
));
2593 if (empty($this->_params
) &&
2596 $this->setParams($this->_formValues
);
2599 // hack to fix params when submitted from dashboard, CRM-8532
2600 // fields array is missing because form building etc is skipped
2601 // in dashboard mode for report
2602 //@todo - this could be done in the dashboard no we have a setter
2603 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2604 $this->setParams($this->_formValues
);
2607 $this->_formValues
= $this->_params
;
2608 if (CRM_Core_Permission
::check('administer Reports') &&
2609 isset($this->_id
) &&
2610 ($this->_instanceButtonName
==
2611 $this->controller
->getButtonName() . '_save' ||
2612 $this->_chartButtonName
== $this->controller
->getButtonName()
2615 $this->assign('updateReportButton', TRUE);
2617 $this->processReportMode();
2618 $this->beginPostProcessCommon();
2622 * BeginPostProcess function run in both report mode and non-report mode (api)
2624 public function beginPostProcessCommon() {
2629 * @param bool $applyLimit
2633 public function buildQuery($applyLimit = TRUE) {
2636 $this->customDataFrom();
2641 // order_by columns not selected for display need to be included in SELECT
2642 $unselectedSectionColumns = $this->unselectedSectionColumns();
2643 foreach ($unselectedSectionColumns as $alias => $section) {
2644 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2647 if ($applyLimit && empty($this->_params
['charts'])) {
2650 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2652 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2656 public function groupBy() {
2657 $groupBys = array();
2658 if (!empty($this->_params
['group_bys']) &&
2659 is_array($this->_params
['group_bys']) &&
2660 !empty($this->_params
['group_bys'])
2662 foreach ($this->_columns
as $tableName => $table) {
2663 if (array_key_exists('group_bys', $table)) {
2664 foreach ($table['group_bys'] as $fieldName => $field) {
2665 if (!empty($this->_params
['group_bys'][$fieldName])) {
2666 $groupBys[] = $field['dbAlias'];
2673 if (!empty($groupBys)) {
2674 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2678 public function orderBy() {
2679 $this->_orderBy
= "";
2680 $this->_sections
= array();
2681 $this->storeOrderByArray();
2682 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2683 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2685 $this->assign('sections', $this->_sections
);
2689 * In some cases other functions want to know which fields are selected for ordering by
2690 * Separating this into a separate function allows it to be called separately from constructing
2691 * the order by clause
2693 public function storeOrderByArray() {
2694 $orderBys = array();
2696 if (!empty($this->_params
['order_bys']) &&
2697 is_array($this->_params
['order_bys']) &&
2698 !empty($this->_params
['order_bys'])
2701 // Process order_bys in user-specified order
2702 foreach ($this->_params
['order_bys'] as $orderBy) {
2703 $orderByField = array();
2704 foreach ($this->_columns
as $tableName => $table) {
2705 if (array_key_exists('order_bys', $table)) {
2706 // For DAO columns defined in $this->_columns
2707 $fields = $table['order_bys'];
2709 elseif (array_key_exists('extends', $table)) {
2710 // For custom fields referenced in $this->_customGroupExtends
2711 $fields = CRM_Utils_Array
::value('fields', $table, array());
2716 if (!empty($fields) && is_array($fields)) {
2717 foreach ($fields as $fieldName => $field) {
2718 if ($fieldName == $orderBy['column']) {
2719 $orderByField = array_merge($field, $orderBy);
2720 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2727 if (!empty($orderByField)) {
2728 $this->_orderByFields
[] = $orderByField;
2729 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2731 // Record any section headers for assignment to the template
2732 if (!empty($orderBy['section'])) {
2733 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2734 $this->_sections
[$orderByField['tplField']] = $orderByField;
2740 $this->_orderByArray
= $orderBys;
2742 $this->assign('sections', $this->_sections
);
2748 public function unselectedSectionColumns() {
2749 $selectColumns = array();
2750 foreach ($this->_columns
as $tableName => $table) {
2751 if (array_key_exists('fields', $table)) {
2752 foreach ($table['fields'] as $fieldName => $field) {
2753 if (!empty($field['required']) ||
2754 !empty($this->_params
['fields'][$fieldName])
2757 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2763 if (is_array($this->_sections
)) {
2764 return array_diff_key($this->_sections
, $selectColumns);
2775 public function buildRows($sql, &$rows) {
2776 $dao = CRM_Core_DAO
::executeQuery($sql);
2777 if (!is_array($rows)) {
2781 // use this method to modify $this->_columnHeaders
2782 $this->modifyColumnHeaders();
2784 $unselectedSectionColumns = $this->unselectedSectionColumns();
2786 while ($dao->fetch()) {
2788 foreach ($this->_columnHeaders
as $key => $value) {
2789 if (property_exists($dao, $key)) {
2790 $row[$key] = $dao->$key;
2794 // section headers not selected for display need to be added to row
2795 foreach ($unselectedSectionColumns as $key => $values) {
2796 if (property_exists($dao, $key)) {
2797 $row[$key] = $dao->$key;
2806 * When "order by" fields are marked as sections, this assigns to the template
2807 * an array of total counts for each section. This data is used by the Smarty
2808 * plugin {sectionTotal}
2810 public function sectionTotals() {
2812 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2813 if (empty($this->_selectAliases
)) {
2817 if (!empty($this->_sections
)) {
2818 // build the query with no LIMIT clause
2819 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2820 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2822 // pull section aliases out of $this->_sections
2823 $sectionAliases = array_keys($this->_sections
);
2826 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2827 $ifnulls[] = "ifnull($alias, '') as $alias";
2830 // Group (un-limited) report by all aliases and get counts. This might
2831 // be done more efficiently when the contents of $sql are known, ie. by
2832 // overriding this method in the report class.
2834 $query = "select " . implode(", ", $ifnulls) .
2835 ", count(*) as ct from ($sql) as subquery group by " .
2836 implode(", ", $sectionAliases);
2838 // initialize array of total counts
2840 $dao = CRM_Core_DAO
::executeQuery($query);
2841 while ($dao->fetch()) {
2843 // let $this->_alterDisplay translate any integer ids to human-readable values.
2844 $rows[0] = $dao->toArray();
2845 $this->alterDisplay($rows);
2848 // add totals for all permutations of section values
2851 $aliasCount = count($sectionAliases);
2852 foreach ($sectionAliases as $alias) {
2853 $values[] = $row[$alias];
2854 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2855 if ($i == $aliasCount) {
2856 // the last alias is the lowest-level section header; use count as-is
2857 $totals[$key] = $dao->ct
;
2860 // other aliases are higher level; roll count into their total
2861 $totals[$key] +
= $dao->ct
;
2865 $this->assign('sectionTotals', $totals);
2869 public function modifyColumnHeaders() {
2870 // use this method to modify $this->_columnHeaders
2876 public function doTemplateAssignment(&$rows) {
2877 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2878 $this->assign_by_ref('rows', $rows);
2879 $this->assign('statistics', $this->statistics($rows));
2883 * override this method to build your own statistics
2888 public function statistics(&$rows) {
2889 $statistics = array();
2891 $count = count($rows);
2893 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2897 $this->countStat($statistics, $count);
2899 $this->groupByStat($statistics);
2901 $this->filterStat($statistics);
2907 * @param $statistics
2910 public function countStat(&$statistics, $count) {
2911 $statistics['counts']['rowCount'] = array(
2912 'title' => ts('Row(s) Listed'),
2916 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2917 $statistics['counts']['rowsFound'] = array(
2918 'title' => ts('Total Row(s)'),
2919 'value' => $this->_rowsFound
,
2925 * @param $statistics
2927 public function groupByStat(&$statistics) {
2928 if (!empty($this->_params
['group_bys']) &&
2929 is_array($this->_params
['group_bys']) &&
2930 !empty($this->_params
['group_bys'])
2932 foreach ($this->_columns
as $tableName => $table) {
2933 if (array_key_exists('group_bys', $table)) {
2934 foreach ($table['group_bys'] as $fieldName => $field) {
2935 if (!empty($this->_params
['group_bys'][$fieldName])) {
2936 $combinations[] = $field['title'];
2941 $statistics['groups'][] = array(
2942 'title' => ts('Grouping(s)'),
2943 'value' => implode(' & ', $combinations),
2949 * @param $statistics
2951 public function filterStat(&$statistics) {
2952 foreach ($this->_columns
as $tableName => $table) {
2953 if (array_key_exists('filters', $table)) {
2954 foreach ($table['filters'] as $fieldName => $field) {
2955 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
2956 CRM_Utils_Array
::value('operatorType', $field) !=
2957 CRM_Report_Form
::OP_MONTH
2961 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2962 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2963 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2964 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2965 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2967 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2968 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2970 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2971 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2974 $statistics['filters'][] = array(
2975 'title' => $field['title'],
2976 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2979 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2980 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2982 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2983 $statistics['filters'][] = array(
2984 'title' => $field['title'],
2985 'value' => $pair[$rel],
2990 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2993 $pair = $this->getOperationPair(
2994 CRM_Utils_Array
::value('operatorType', $field),
2997 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2998 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2999 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3000 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3001 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3003 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3004 $this->setEntityRefDefaults($field, $tableName);
3005 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3006 array('id' => $val) +
3007 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3009 foreach ($result['values'] as $v) {
3010 $values[] = $v['label'];
3012 $value = "{$pair[$op]} " . implode(', ', $values);
3014 elseif ($op == 'nll' ||
$op == 'nnll') {
3015 $value = $pair[$op];
3017 elseif (is_array($val) && (!empty($val))) {
3018 $options = CRM_Utils_Array
::value('options', $field, array());
3019 foreach ($val as $key => $valIds) {
3020 if (isset($options[$valIds])) {
3021 $val[$key] = $options[$valIds];
3024 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3025 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3026 $val = implode(', ', $val);
3027 $value = "{$pair[$op]} " . $val;
3029 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3030 isset($field['options']) &&
3031 is_array($field['options']) && !empty($field['options'])
3033 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3034 CRM_Utils_Array
::value($val, $field['options'], $val);
3037 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3041 $statistics['filters'][] = array(
3042 'title' => CRM_Utils_Array
::value('title', $field),
3053 * End post processing.
3055 * @param array|null $rows
3057 public function endPostProcess(&$rows = NULL) {
3058 if ($this->_storeResultSet
) {
3059 $this->_resultSet
= $rows;
3062 if ($this->_outputMode
== 'print' ||
3063 $this->_outputMode
== 'pdf' ||
3067 $content = $this->compileContent();
3068 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3072 if ($this->_sendmail
) {
3073 $config = CRM_Core_Config
::singleton();
3074 $attachments = array();
3076 if ($this->_outputMode
== 'csv') {
3078 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3079 ": {$url}</p>" . '<p>' .
3080 ts('The report is attached as a CSV file.') . '</p>' .
3081 $this->_formValues
['report_footer'];
3083 $csvFullFilename = $config->templateCompileDir
.
3084 CRM_Utils_File
::makeFileName('CiviReport.csv');
3085 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3086 file_put_contents($csvFullFilename, $csvContent);
3087 $attachments[] = array(
3088 'fullPath' => $csvFullFilename,
3089 'mime_type' => 'text/csv',
3090 'cleanName' => 'CiviReport.csv',
3093 if ($this->_outputMode
== 'pdf') {
3094 // generate PDF content
3095 $pdfFullFilename = $config->templateCompileDir
.
3096 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3097 file_put_contents($pdfFullFilename,
3098 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3099 TRUE, array('orientation' => 'landscape')
3102 // generate Email Content
3104 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3105 ": {$url}</p>" . '<p>' .
3106 ts('The report is attached as a PDF file.') . '</p>' .
3107 $this->_formValues
['report_footer'];
3109 $attachments[] = array(
3110 'fullPath' => $pdfFullFilename,
3111 'mime_type' => 'application/pdf',
3112 'cleanName' => 'CiviReport.pdf',
3116 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3117 $this->_outputMode
, $attachments
3120 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3123 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3127 elseif ($this->_outputMode
== 'print') {
3131 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3132 $config = CRM_Core_Config
::singleton();
3133 //get chart image name
3134 $chartImg = $this->_chartId
. '.png';
3135 //get image url path
3137 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3139 $uploadUrl .= $chartImg;
3140 //get image doc path to overwrite
3142 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3143 'openFlashChart/' . $chartImg;
3145 $chart = imagecreatefrompng($uploadUrl);
3146 //convert it into formatted png
3147 header('Content-type: image/png');
3148 //overwrite with same image
3149 imagepng($chart, $uploadImg);
3151 imagedestroy($chart);
3153 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3155 CRM_Utils_System
::civiExit();
3157 elseif ($this->_outputMode
== 'csv') {
3158 CRM_Report_Utils_Report
::export2csv($this, $rows);
3160 elseif ($this->_outputMode
== 'group') {
3161 $group = $this->_params
['groups'];
3162 $this->add2group($group);
3164 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3165 CRM_Report_Form_Instance
::postProcess($this);
3167 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3168 $this->_outputMode
== 'create_report'
3170 $this->_createNew
= TRUE;
3171 CRM_Report_Form_Instance
::postProcess($this);
3176 * Set store result set indicator to TRUE.
3178 * @todo explain what this does
3180 public function storeResultSet() {
3181 $this->_storeResultSet
= TRUE;
3189 public function getResultSet() {
3190 return $this->_resultSet
;
3194 * Use the form name to create the tpl file name.
3198 public function getTemplateFileName() {
3199 $defaultTpl = parent
::getTemplateFileName();
3200 $template = CRM_Core_Smarty
::singleton();
3201 if (!$template->template_exists($defaultTpl)) {
3202 $defaultTpl = 'CRM/Report/Form.tpl';
3208 * Compile the report content.
3209 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3213 public function compileContent() {
3214 $templateFile = $this->getHookedTemplateFileName();
3215 return $this->_formValues
['report_header'] .
3216 CRM_Core_Form
::$_template->fetch($templateFile) .
3217 $this->_formValues
['report_footer'];
3221 public function postProcess() {
3222 // get ready with post process params
3223 $this->beginPostProcess();
3226 $sql = $this->buildQuery();
3228 // build array of result based on column headers. This method also allows
3229 // modifying column headers before using it to build result set i.e $rows.
3231 $this->buildRows($sql, $rows);
3233 // format result set.
3234 $this->formatDisplay($rows);
3236 // assign variables to templates
3237 $this->doTemplateAssignment($rows);
3239 // do print / pdf / instance stuff if needed
3240 $this->endPostProcess($rows);
3244 * @param int $rowCount
3247 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3248 // lets do the pager if in html mode
3249 $this->_limit
= NULL;
3251 // CRM-14115, over-ride row count if rowCount is specified in URL
3252 if ($this->_dashBoardRowCount
) {
3253 $rowCount = $this->_dashBoardRowCount
;
3255 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3256 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3258 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3260 // @todo all http vars should be extracted in the preProcess
3261 // - not randomly in the class
3262 if (!$pageId && !empty($_POST)) {
3263 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3264 $pageId = max((int) $_POST['crmPID_B'], 1);
3266 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3267 $pageId = max((int) $_POST['crmPID'], 1);
3269 unset($_POST['crmPID_B'], $_POST['crmPID']);
3272 $pageId = $pageId ?
$pageId : 1;
3273 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3274 $offset = ($pageId - 1) * $rowCount;
3276 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3277 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3279 $this->_limit
= " LIMIT $offset, $rowCount";
3280 return array($offset, $rowCount);
3282 if ($this->_limitValue
) {
3283 if ($this->_offsetValue
) {
3284 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3287 $this->_limit
= " LIMIT " . $this->_limitValue
;
3293 * @param int $rowCount
3295 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3297 // CRM-14115, over-ride row count if rowCount is specified in URL
3298 if ($this->_dashBoardRowCount
) {
3299 $rowCount = $this->_dashBoardRowCount
;
3302 if ($this->_limit
&& ($this->_limit
!= '')) {
3303 $sql = "SELECT FOUND_ROWS();";
3304 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3306 'total' => $this->_rowsFound
,
3307 'rowCount' => $rowCount,
3308 'status' => ts('Records') . ' %%StatusMessage%%',
3309 'buttonBottom' => 'PagerBottomButton',
3310 'buttonTop' => 'PagerTopButton',
3311 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3314 $pager = new CRM_Utils_Pager($params);
3315 $this->assign_by_ref('pager', $pager);
3316 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3327 public function whereGroupClause($field, $value, $op) {
3329 $smartGroupQuery = "";
3331 $group = new CRM_Contact_DAO_Group();
3332 $group->is_active
= 1;
3334 $smartGroups = array();
3335 while ($group->fetch()) {
3336 if (in_array($group->id
, $this->_params
['gid_value']) &&
3337 $group->saved_search_id
3339 $smartGroups[] = $group->id
;
3343 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3345 $smartGroupQuery = '';
3346 if (!empty($smartGroups)) {
3347 $smartGroups = implode(',', $smartGroups);
3348 $smartGroupQuery = " UNION DISTINCT
3349 SELECT DISTINCT smartgroup_contact.contact_id
3350 FROM civicrm_group_contact_cache smartgroup_contact
3351 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3354 $sqlOp = $this->getSQLOperator($op);
3355 if (!is_array($value)) {
3356 $value = array($value);
3358 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3360 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3361 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3362 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3363 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3364 {$smartGroupQuery} ) ";
3374 public function whereTagClause($field, $value, $op) {
3375 // not using left join in query because if any contact
3376 // belongs to more than one tag, results duplicate
3378 $sqlOp = $this->getSQLOperator($op);
3379 if (!is_array($value)) {
3380 $value = array($value);
3382 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3383 $entity_table = $this->_tagFilterTable
;
3384 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3385 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3386 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3387 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3391 * Generate membership organization clause.
3393 * @param mixed $value
3394 * @param string $op SQL Operator
3398 public function whereMembershipOrgClause($value, $op) {
3399 $sqlOp = $this->getSQLOperator($op);
3400 if (!is_array($value)) {
3401 $value = array($value);
3404 $tmp_membership_org_sql_list = implode(', ', $value);
3405 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3406 SELECT DISTINCT mem.contact_id
3407 FROM civicrm_membership mem
3408 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3409 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3410 WHERE mt.member_of_contact_id IN (" .
3411 $tmp_membership_org_sql_list . ")
3412 AND mt.is_active = '1'
3413 AND mem_status.is_current_member = '1'
3414 AND mem_status.is_active = '1' ) ";
3418 * Generate Membership Type SQL Clause.
3419 * @param mixed $value
3425 public function whereMembershipTypeClause($value, $op) {
3426 $sqlOp = $this->getSQLOperator($op);
3427 if (!is_array($value)) {
3428 $value = array($value);
3431 $tmp_membership_sql_list = implode(', ', $value);
3432 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3433 SELECT DISTINCT mem.contact_id
3434 FROM civicrm_membership mem
3435 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3436 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3437 WHERE mem.membership_type_id IN (" .
3438 $tmp_membership_sql_list . ")
3439 AND mt.is_active = '1'
3440 AND mem_status.is_current_member = '1'
3441 AND mem_status.is_active = '1' ) ";
3445 * @param string $tableAlias
3447 public function buildACLClause($tableAlias = 'contact_a') {
3448 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3452 * @param bool $addFields
3453 * @param array $permCustomGroupIds
3455 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3456 if (empty($this->_customGroupExtends
)) {
3459 if (!is_array($this->_customGroupExtends
)) {
3460 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3462 $customGroupWhere = '';
3463 if (!empty($permCustomGroupIds)) {
3464 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3468 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3469 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3470 FROM civicrm_custom_group cg
3471 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3472 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3474 cg.is_active = 1 AND
3475 cf.is_active = 1 AND
3476 cf.is_searchable = 1
3477 ORDER BY cg.weight, cf.weight";
3478 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3481 while ($customDAO->fetch()) {
3482 if ($customDAO->table_name
!= $curTable) {
3483 $curTable = $customDAO->table_name
;
3484 $curFields = $curFilters = array();
3487 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3488 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3489 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3490 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3497 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3498 $this->_columns
[$curTable][$colKey] = array();
3502 $fieldName = 'custom_' . $customDAO->cf_id
;
3505 // this makes aliasing work in favor
3506 $curFields[$fieldName] = array(
3507 'name' => $customDAO->column_name
,
3508 'title' => $customDAO->label
,
3509 'dataType' => $customDAO->data_type
,
3510 'htmlType' => $customDAO->html_type
,
3513 if ($this->_customGroupFilters
) {
3514 // this makes aliasing work in favor
3515 $curFilters[$fieldName] = array(
3516 'name' => $customDAO->column_name
,
3517 'title' => $customDAO->label
,
3518 'dataType' => $customDAO->data_type
,
3519 'htmlType' => $customDAO->html_type
,
3523 switch ($customDAO->data_type
) {
3526 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3527 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3528 // CRM-6946, show time part for datetime date fields
3529 if ($customDAO->time_format
) {
3530 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3535 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3536 $curFilters[$fieldName]['options'] = array(
3537 '' => ts('- select -'),
3541 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3545 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3546 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3550 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3551 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3555 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3556 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3560 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3562 if (!empty($customDAO->option_group_id
)) {
3563 if (in_array($customDAO->html_type
, array(
3568 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3571 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3573 if ($this->_customGroupFilters
) {
3574 $curFilters[$fieldName]['options'] = array();
3575 $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(
3577 $customDAO->option_group_id
,
3581 while ($ogDAO->fetch()) {
3582 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3584 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3589 case 'StateProvince':
3590 if (in_array($customDAO->html_type
, array(
3591 'Multi-Select State/Province',
3593 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3596 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3598 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3602 if (in_array($customDAO->html_type
, array(
3603 'Multi-Select Country',
3605 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3608 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3610 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3613 case 'ContactReference':
3614 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3615 $curFilters[$fieldName]['name'] = 'display_name';
3616 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3618 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3619 $curFields[$fieldName]['name'] = 'display_name';
3620 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3624 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3625 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3628 if (!array_key_exists('type', $curFields[$fieldName])) {
3629 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3633 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3635 if ($this->_customGroupFilters
) {
3636 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3638 if ($this->_customGroupGroupBy
) {
3639 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3644 public function customDataFrom() {
3645 if (empty($this->_customGroupExtends
)) {
3648 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3650 foreach ($this->_columns
as $table => $prop) {
3651 if (substr($table, 0, 13) == 'civicrm_value' ||
3652 substr($table, 0, 12) == 'custom_value'
3654 $extendsTable = $mapper[$prop['extends']];
3656 // check field is in params
3657 if (!$this->isFieldSelected($prop)) {
3660 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3662 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3664 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3665 // handle for ContactReference
3666 if (array_key_exists('fields', $prop)) {
3667 foreach ($prop['fields'] as $fieldName => $field) {
3668 if (CRM_Utils_Array
::value('dataType', $field) ==
3671 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3673 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3686 public function isFieldSelected($prop) {
3691 if (!empty($this->_params
['fields'])) {
3692 foreach (array_keys($prop['fields']) as $fieldAlias) {
3693 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3694 if ($customFieldId) {
3695 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3699 //might be survey response field.
3700 if (!empty($this->_params
['fields']['survey_response']) &&
3701 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3709 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3710 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3711 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3712 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3719 if (!empty($this->_params
['order_bys'])) {
3720 foreach (array_keys($prop['fields']) as $fieldAlias) {
3721 foreach ($this->_params
['order_bys'] as $orderBy) {
3722 if ($fieldAlias == $orderBy['column'] &&
3723 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3731 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3732 foreach ($prop['filters'] as $fieldAlias => $val) {
3741 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3742 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3743 ||
($attach != 'relative' &&
3744 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3750 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3751 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3762 * Check for empty order_by configurations and remove them; also set
3763 * template to hide them.
3765 * @param array $formValues
3767 public function preProcessOrderBy(&$formValues) {
3768 // Object to show/hide form elements
3769 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3771 $_showHide->addShow('optionField_1');
3773 // Cycle through order_by options; skip any empty ones, and hide them as well
3776 if (!empty($formValues['order_bys'])) {
3777 foreach ($formValues['order_bys'] as $order_by) {
3778 if ($order_by['column'] && $order_by['column'] != '-') {
3779 $_showHide->addShow('optionField_' . $n);
3780 $orderBys[$n] = $order_by;
3785 for ($i = $n; $i <= 5; $i++
) {
3787 $_showHide->addHide('optionField_' . $i);
3791 // overwrite order_by options with modified values
3792 if (!empty($orderBys)) {
3793 $formValues['order_bys'] = $orderBys;
3796 $formValues['order_bys'] = array(1 => array('column' => '-'));
3799 // assign show/hide data to template
3800 $_showHide->addToTemplate();
3804 * Does table name have columns in SELECT clause?
3806 * @param string $tableName
3807 * Name of table (index of $this->_columns array).
3811 public function isTableSelected($tableName) {
3812 return in_array($tableName, $this->selectedTables());
3816 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3817 * (building the array if it's unset)
3822 public function selectedTables() {
3823 if (!$this->_selectedTables
) {
3824 $orderByColumns = array();
3825 if (array_key_exists('order_bys', $this->_params
) &&
3826 is_array($this->_params
['order_bys'])
3828 foreach ($this->_params
['order_bys'] as $orderBy) {
3829 $orderByColumns[] = $orderBy['column'];
3833 foreach ($this->_columns
as $tableName => $table) {
3834 if (array_key_exists('fields', $table)) {
3835 foreach ($table['fields'] as $fieldName => $field) {
3836 if (!empty($field['required']) ||
3837 !empty($this->_params
['fields'][$fieldName])
3839 $this->_selectedTables
[] = $tableName;
3844 if (array_key_exists('order_bys', $table)) {
3845 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3846 if (in_array($orderByName, $orderByColumns)) {
3847 $this->_selectedTables
[] = $tableName;
3852 if (array_key_exists('filters', $table)) {
3853 foreach ($table['filters'] as $filterName => $filter) {
3854 if (!empty($this->_params
["{$filterName}_value"]) ||
3855 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3857 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3860 $this->_selectedTables
[] = $tableName;
3867 return $this->_selectedTables
;
3871 * @deprecated - use getAddressColumns which is a more accurate description
3872 * and also accepts an array of options rather than a long list
3874 * adding address fields to construct function in reports
3876 * @param bool $groupBy
3877 * Add GroupBy? Not appropriate for detail report.
3878 * @param bool $orderBy
3879 * Add GroupBy? Not appropriate for detail report.
3880 * @param bool $filters
3881 * @param array $defaults
3884 * address fields for construct clause
3886 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3887 $addressFields = array(
3888 'civicrm_address' => array(
3889 'dao' => 'CRM_Core_DAO_Address',
3892 'title' => ts('Address Name'),
3893 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3895 'street_address' => array(
3896 'title' => ts('Street Address'),
3897 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3899 'supplemental_address_1' => array(
3900 'title' => ts('Supplementary Address Field 1'),
3901 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3903 'supplemental_address_2' => array(
3904 'title' => ts('Supplementary Address Field 2'),
3905 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3907 'street_number' => array(
3908 'name' => 'street_number',
3909 'title' => ts('Street Number'),
3911 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3913 'street_name' => array(
3914 'name' => 'street_name',
3915 'title' => ts('Street Name'),
3917 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3919 'street_unit' => array(
3920 'name' => 'street_unit',
3921 'title' => ts('Street Unit'),
3923 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3926 'title' => ts('City'),
3927 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3929 'postal_code' => array(
3930 'title' => ts('Postal Code'),
3931 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3933 'postal_code_suffix' => array(
3934 'title' => ts('Postal Code Suffix'),
3935 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3937 'country_id' => array(
3938 'title' => ts('Country'),
3939 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3941 'state_province_id' => array(
3942 'title' => ts('State/Province'),
3943 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3945 'county_id' => array(
3946 'title' => ts('County'),
3947 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3950 'grouping' => 'location-fields',
3955 $addressFields['civicrm_address']['filters'] = array(
3956 'street_number' => array(
3957 'title' => ts('Street Number'),
3959 'name' => 'street_number',
3961 'street_name' => array(
3962 'title' => ts('Street Name'),
3963 'name' => 'street_name',
3964 'operator' => 'like',
3966 'postal_code' => array(
3967 'title' => ts('Postal Code'),
3969 'name' => 'postal_code',
3972 'title' => ts('City'),
3973 'operator' => 'like',
3976 'country_id' => array(
3977 'name' => 'country_id',
3978 'title' => ts('Country'),
3979 'type' => CRM_Utils_Type
::T_INT
,
3980 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3981 'options' => CRM_Core_PseudoConstant
::country(),
3983 'state_province_id' => array(
3984 'name' => 'state_province_id',
3985 'title' => ts('State/Province'),
3986 'type' => CRM_Utils_Type
::T_INT
,
3987 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3988 'options' => array(),
3990 'county_id' => array(
3991 'name' => 'county_id',
3992 'title' => ts('County'),
3993 'type' => CRM_Utils_Type
::T_INT
,
3994 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3995 'options' => array(),
4001 $addressFields['civicrm_address']['order_bys'] = array(
4002 'street_name' => array('title' => ts('Street Name')),
4003 'street_number' => array('title' => 'Odd / Even Street Number'),
4004 'street_address' => NULL,
4006 'postal_code' => NULL,
4011 $addressFields['civicrm_address']['group_bys'] = array(
4012 'street_address' => NULL,
4014 'postal_code' => NULL,
4015 'state_province_id' => array(
4016 'title' => ts('State/Province'),
4018 'country_id' => array(
4019 'title' => ts('Country'),
4021 'county_id' => array(
4022 'title' => ts('County'),
4026 return $addressFields;
4030 * Do AlterDisplay processing on Address Fields.
4040 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
4041 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4042 $entryFound = FALSE;
4044 if (array_key_exists('civicrm_address_country_id', $row)) {
4045 if ($value = $row['civicrm_address_country_id']) {
4046 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4047 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4048 "reset=1&force=1&{$criteriaQueryParams}&" .
4049 "country_id_op=in&country_id_value={$value}",
4050 $this->_absoluteUrl
, $this->_id
4052 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4053 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4060 if (array_key_exists('civicrm_address_county_id', $row)) {
4061 if ($value = $row['civicrm_address_county_id']) {
4062 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4063 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4064 "reset=1&force=1&{$criteriaQueryParams}&" .
4065 "county_id_op=in&county_id_value={$value}",
4066 $this->_absoluteUrl
, $this->_id
4068 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4069 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4075 // handle state province
4076 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4077 if ($value = $row['civicrm_address_state_province_id']) {
4078 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4080 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4081 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4082 $this->_absoluteUrl
, $this->_id
4084 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4085 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4096 * Adjusts dates passed in to YEAR() for fiscal year.
4098 * @param string $fieldName
4102 public function fiscalYearOffset($fieldName) {
4103 $config = CRM_Core_Config
::singleton();
4104 $fy = $config->fiscalYearStart
;
4105 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4106 ($fy['d'] == 1 && $fy['M'] == 1)
4108 return "YEAR( $fieldName )";
4110 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4111 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4115 * Add Address into From Table if required.
4117 public function addAddressFromClause() {
4118 // include address field if address column is to be included
4119 if ((isset($this->_addressField
) &&
4120 $this->_addressField
4122 $this->isTableSelected('civicrm_address')
4125 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4126 ON ({$this->_aliases['civicrm_contact']}.id =
4127 {$this->_aliases['civicrm_address']}.contact_id) AND
4128 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4133 * Add Phone into From Table if required.
4135 public function addPhoneFromClause() {
4136 // include address field if address column is to be included
4137 if ($this->isTableSelected('civicrm_phone')
4140 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4141 ON ({$this->_aliases['civicrm_contact']}.id =
4142 {$this->_aliases['civicrm_phone']}.contact_id) AND
4143 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4148 * Get phone columns to add to array.
4150 * @param array $options
4151 * - prefix Prefix to add to table (in case of more than one instance of the table)
4152 * - prefix_label Label to give columns from this phone table instance
4155 * phone columns definition
4157 public function getPhoneColumns($options = array()) {
4158 $defaultOptions = array(
4160 'prefix_label' => '',
4163 $options = array_merge($defaultOptions, $options);
4166 $options['prefix'] . 'civicrm_phone' => array(
4167 'dao' => 'CRM_Core_DAO_Phone',
4169 $options['prefix'] . 'phone' => array(
4170 'title' => ts($options['prefix_label'] . 'Phone'),
4180 * Get address columns to add to array.
4182 * @param array $options
4183 * - prefix Prefix to add to table (in case of more than one instance of the table)
4184 * - prefix_label Label to give columns from this address table instance
4187 * address columns definition
4189 public function getAddressColumns($options = array()) {
4192 'prefix_label' => '',
4196 'defaults' => array(),
4198 return $this->addAddressFields(
4199 $options['group_by'],
4200 $options['order_by'],
4201 $options['filters'],
4202 $options['defaults']
4207 * @param int $groupID
4209 public function add2group($groupID) {
4210 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4211 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4212 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4214 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4215 $sql = str_replace('WITH ROLLUP', '', $sql);
4216 $dao = CRM_Core_DAO
::executeQuery($sql);
4218 $contact_ids = array();
4219 // Add resulting contacts to group
4220 while ($dao->fetch()) {
4221 if ($dao->addtogroup_contact_id
) {
4222 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4226 if (!empty($contact_ids)) {
4227 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4228 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4231 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4237 * function used for showing charts on print screen.
4239 public static function uploadChartImage() {
4240 // upload strictly for '.png' images
4241 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4242 if (preg_match('/\.png$/', $name)) {
4244 // POST data is usually string data, but we are passing a RAW .png
4245 // so PHP is a bit confused and $_POST is empty. But it has saved
4246 // the raw bits into $HTTP_RAW_POST_DATA
4248 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4250 // prepare the directory
4251 $config = CRM_Core_Config
::singleton();
4253 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4255 if (!file_exists($defaultPath)) {
4256 mkdir($defaultPath, 0777, TRUE);
4259 // full path to the saved image including filename
4260 $destination = $defaultPath . $name;
4263 $jfh = fopen($destination, 'w') or die("can't open file");
4264 fwrite($jfh, $httpRawPostData);
4266 CRM_Utils_System
::civiExit();
4271 * Apply common settings to entityRef fields.
4273 * @param array $field
4274 * @param string $table
4276 private function setEntityRefDefaults(&$field, $table) {
4277 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4278 $field['attributes'] +
= array(
4279 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4281 'placeholder' => ts('- select -'),