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 accordian.
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
1209 foreach ($this->_options
as $fieldName => $field) {
1210 if ($field['type'] == 'select') {
1211 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1213 elseif ($field['type'] == 'checkbox') {
1214 $options[$field['title']] = $fieldName;
1215 $this->addCheckBox($fieldName, NULL,
1217 NULL, NULL, NULL, $this->_fourColumnAttribute
1222 if (!empty($this->_options
)) {
1223 $this->tabs
['ReportOptions'] = array(
1224 'title' => ts('Display Options'),
1225 'tpl' => 'ReportOptions',
1226 'div_label' => 'other-options',
1229 $this->assign('otherOptions', $this->_options
);
1233 * Add chart options to the report.
1235 public function addChartOptions() {
1236 if (!empty($this->_charts
)) {
1237 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1238 $this->assign('charts', $this->_charts
);
1239 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1244 * Add group by options to the report.
1246 public function addGroupBys() {
1247 $options = $freqElements = array();
1249 foreach ($this->_columns
as $tableName => $table) {
1250 if (array_key_exists('group_bys', $table)) {
1251 foreach ($table['group_bys'] as $fieldName => $field) {
1252 if (!empty($field)) {
1253 $options[$field['title']] = $fieldName;
1254 if (!empty($field['frequency'])) {
1255 $freqElements[$field['title']] = $fieldName;
1261 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1262 NULL, NULL, NULL, $this->_fourColumnAttribute
1264 $this->assign('groupByElements', $options);
1265 if (!empty($options)) {
1266 $this->tabs
['GroupBy'] = array(
1267 'title' => ts('Grouping'),
1269 'div_label' => 'group-by-elements',
1273 foreach ($freqElements as $name) {
1274 $this->addElement('select', "group_bys_freq[$name]",
1275 ts('Frequency'), $this->_groupByDateFreq
1281 * Add data for order by tab.
1283 public function addOrderBys() {
1285 foreach ($this->_columns
as $tableName => $table) {
1287 // Report developer may define any column to order by; include these as order-by options.
1288 if (array_key_exists('order_bys', $table)) {
1289 foreach ($table['order_bys'] as $fieldName => $field) {
1290 if (!empty($field)) {
1291 $options[$fieldName] = $field['title'];
1296 // Add searchable custom fields as order-by options, if so requested
1297 // (These are already indexed, so allowing to order on them is cheap.)
1299 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1300 array_key_exists('extends', $table) && !empty($table['extends'])
1302 foreach ($table['fields'] as $fieldName => $field) {
1303 if (empty($field['no_display'])) {
1304 $options[$fieldName] = $field['title'];
1312 $this->assign('orderByOptions', $options);
1313 if (!empty($options)) {
1314 $this->tabs
['OrderBy'] = array(
1315 'title' => ts('Sorting'),
1317 'div_label' => 'order-by-elements',
1321 if (!empty($options)) {
1323 '-' => ' - none - ',
1325 for ($i = 1; $i <= 5; $i++
) {
1326 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1327 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1328 'ASC' => 'Ascending',
1329 'DESC' => 'Descending',
1331 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1332 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1338 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1340 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1341 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1344 public function buildInstanceAndButtons() {
1345 CRM_Report_Form_Instance
::buildForm($this);
1347 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1349 $this->addElement('submit', $this->_instanceButtonName
, $label);
1350 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1351 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1354 $this->addElement('submit', $this->_createNewButtonName
,
1355 ts('Save a Copy') . '...');
1357 $this->assign('instanceForm', $this->_instanceForm
);
1359 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1360 $this->addElement('submit', $this->_printButtonName
, $label);
1362 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1363 $this->addElement('submit', $this->_pdfButtonName
, $label);
1365 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1367 if ($this->_csvSupported
) {
1368 $this->addElement('submit', $this->_csvButtonName
, $label);
1371 if (CRM_Core_Permission
::check('administer Reports') &&
1372 $this->_add2groupSupported
1374 $this->addElement('select', 'groups', ts('Group'),
1375 array('' => ts('Add Contacts to Group')) +
1376 CRM_Core_PseudoConstant
::nestedGroup(),
1377 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1379 $this->assign('group', TRUE);
1382 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1384 $this->addChartOptions();
1385 $this->addButtons(array(
1388 'name' => ts('Preview Report'),
1389 'isDefault' => TRUE,
1396 * Main build form function.
1398 public function buildQuickForm() {
1399 $this->addColumns();
1401 $this->addFilters();
1403 $this->addOptions();
1405 $this->addGroupBys();
1407 $this->addOrderBys();
1409 $this->buildInstanceAndButtons();
1411 // Add form rule for report.
1412 if (is_callable(array(
1416 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1418 $this->assignTabs();
1422 * A form rule function to ensure that fields selected in group_by
1423 * (if any) should only be the ones present in display/select fields criteria;
1424 * note: works if and only if any custom field selected in group_by.
1426 * @param array $fields
1427 * @param array $ignoreFields
1431 public function customDataFormRule($fields, $ignoreFields = array()) {
1433 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1434 !empty($fields['group_bys'])
1436 foreach ($this->_columns
as $tableName => $table) {
1437 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1438 substr($tableName, 0, 12) == 'custom_value') &&
1439 !empty($this->_columns
[$tableName]['fields'])
1441 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1442 if (array_key_exists($fieldName, $fields['group_bys']) &&
1443 !array_key_exists($fieldName, $fields['fields'])
1445 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1447 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1448 foreach ($fields['fields'] as $fld => $val) {
1449 if (!array_key_exists($fld, $fields['group_bys']) &&
1450 !in_array($fld, $ignoreFields)
1452 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1464 * Get operators to display on form.
1466 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1468 * @param string $type
1469 * @param string $fieldName
1473 public function getOperationPair($type = "string", $fieldName = NULL) {
1474 // FIXME: At some point we should move these key-val pairs
1475 // to option_group and option_value table.
1477 case CRM_Report_Form
::OP_INT
:
1478 case CRM_Report_Form
::OP_FLOAT
:
1481 'lte' => ts('Is less than or equal to'),
1482 'gte' => ts('Is greater than or equal to'),
1483 'bw' => ts('Is between'),
1484 'eq' => ts('Is equal to'),
1485 'lt' => ts('Is less than'),
1486 'gt' => ts('Is greater than'),
1487 'neq' => ts('Is not equal to'),
1488 'nbw' => ts('Is not between'),
1489 'nll' => ts('Is empty (Null)'),
1490 'nnll' => ts('Is not empty (Null)'),
1494 case CRM_Report_Form
::OP_SELECT
:
1496 'eq' => ts('Is equal to'),
1500 case CRM_Report_Form
::OP_MONTH
:
1501 case CRM_Report_Form
::OP_MULTISELECT
:
1502 case CRM_Report_Form
::OP_ENTITYREF
:
1505 'in' => ts('Is one of'),
1506 'notin' => ts('Is not one of'),
1510 case CRM_Report_Form
::OP_DATE
:
1513 'nll' => ts('Is empty (Null)'),
1514 'nnll' => ts('Is not empty (Null)'),
1518 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1519 // use this operator for the values, concatenated with separator. For e.g if
1520 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1522 'mhas' => ts('Is one of'),
1523 'mnot' => ts('Is not one of'),
1530 'has' => ts('Contains'),
1531 'sw' => ts('Starts with'),
1532 'ew' => ts('Ends with'),
1533 'nhas' => ts('Does not contain'),
1534 'eq' => ts('Is equal to'),
1535 'neq' => ts('Is not equal to'),
1536 'nll' => ts('Is empty (Null)'),
1537 'nnll' => ts('Is not empty (Null)'),
1544 * Build the tag filter field to display on the filters tab.
1546 public function buildTagFilter() {
1547 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1548 if (!empty($contactTags)) {
1549 $this->_columns
['civicrm_tag'] = array(
1550 'dao' => 'CRM_Core_DAO_Tag',
1554 'title' => ts('Tag'),
1556 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1557 'options' => $contactTags,
1565 * Adds group filters to _columns (called from _Construct).
1567 public function buildGroupFilter() {
1568 $this->_columns
['civicrm_group']['filters'] = array(
1570 'name' => 'group_id',
1571 'title' => ts('Group'),
1572 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1574 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1577 if (empty($this->_columns
['civicrm_group']['dao'])) {
1578 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1580 if (empty($this->_columns
['civicrm_group']['alias'])) {
1581 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1586 * Get SQL operator from form text version.
1588 * @param string $operator
1592 public function getSQLOperator($operator = "like") {
1593 switch ($operator) {
1626 return 'IS NOT NULL';
1635 * Generate where clause.
1637 * This can be overridden in reports for special treatment of a field
1639 * @param array $field Field specifications
1640 * @param string $op Query operator (not an exact match to sql)
1641 * @param mixed $value
1645 * @return null|string
1647 public function whereClause(&$field, $op, $value, $min, $max) {
1649 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1655 if (($min !== NULL && strlen($min) > 0) ||
1656 ($max !== NULL && strlen($max) > 0)
1658 $min = CRM_Utils_Type
::escape($min, $type);
1659 $max = CRM_Utils_Type
::escape($max, $type);
1663 $clauses[] = "( {$field['dbAlias']} >= $min )";
1666 $clauses[] = "( {$field['dbAlias']} < $min )";
1671 $clauses[] = "( {$field['dbAlias']} <= $max )";
1674 $clauses[] = "( {$field['dbAlias']} > $max )";
1678 if (!empty($clauses)) {
1680 $clause = implode(' AND ', $clauses);
1683 $clause = implode(' OR ', $clauses);
1691 if ($value !== NULL && strlen($value) > 0) {
1692 $value = CRM_Utils_Type
::escape($value, $type);
1693 if (strpos($value, '%') === FALSE) {
1694 $value = "'%{$value}%'";
1697 $value = "'{$value}'";
1699 $sqlOP = $this->getSQLOperator($op);
1700 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1706 if (is_string($value) && strlen($value)) {
1707 $value = explode(',', $value);
1709 if ($value !== NULL && is_array($value) && count($value) > 0) {
1710 $sqlOP = $this->getSQLOperator($op);
1711 if (CRM_Utils_Array
::value('type', $field) ==
1712 CRM_Utils_Type
::T_STRING
1714 //cycle through selections and escape values
1715 foreach ($value as $key => $selection) {
1716 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1719 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1723 // for numerical values
1724 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1727 if ($op == 'notin') {
1728 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1731 $clause = "( " . $clause . " )";
1737 // mhas == multiple has
1738 if ($value !== NULL && count($value) > 0) {
1739 $sqlOP = $this->getSQLOperator($op);
1741 = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) .
1747 // mnot == multiple is not one of
1748 if ($value !== NULL && count($value) > 0) {
1749 $sqlOP = $this->getSQLOperator($op);
1751 = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) .
1752 "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
1758 if ($value !== NULL && strlen($value) > 0) {
1759 $value = CRM_Utils_Type
::escape($value, $type);
1760 if (strpos($value, '%') === FALSE) {
1762 $value = "'{$value}%'";
1765 $value = "'%{$value}'";
1769 $value = "'{$value}'";
1771 $sqlOP = $this->getSQLOperator($op);
1772 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1778 $sqlOP = $this->getSQLOperator($op);
1779 $clause = "( {$field['dbAlias']} $sqlOP )";
1783 if ($value !== NULL && strlen($value) > 0) {
1784 if (isset($field['clause'])) {
1785 // FIXME: we not doing escape here. Better solution is to use two
1786 // different types - data-type and filter-type
1787 $clause = $field['clause'];
1790 $value = CRM_Utils_Type
::escape($value, $type);
1791 $sqlOP = $this->getSQLOperator($op);
1792 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1793 $value = "'{$value}'";
1795 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1801 if (!empty($field['group']) && $clause) {
1802 $clause = $this->whereGroupClause($field, $value, $op);
1804 elseif (!empty($field['tag']) && $clause) {
1805 // not using left join in query because if any contact
1806 // belongs to more than one tag, results duplicate
1808 $clause = $this->whereTagClause($field, $value, $op);
1810 elseif (!empty($field['membership_org']) && $clause) {
1811 $clause = $this->whereMembershipOrgClause($value, $op);
1813 elseif (!empty($field['membership_type']) && $clause) {
1814 $clause = $this->whereMembershipTypeClause($value, $op);
1820 * Get SQL where clause for a date field.
1822 * @param string $fieldName
1824 * @param string $from
1826 * @param string $type
1827 * @param string $fromTime
1828 * @param string $toTime
1830 * @return null|string
1832 public function dateClause(
1834 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1837 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1838 $sqlOP = $this->getSQLOperator($relative);
1839 return "( {$fieldName} {$sqlOP} )";
1842 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1845 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1846 $clauses[] = "( {$fieldName} >= $from )";
1850 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1851 $clauses[] = "( {$fieldName} <= {$to} )";
1854 if (!empty($clauses)) {
1855 return implode(' AND ', $clauses);
1862 * Possibly unused function.
1864 * @todo - could not find any instances where this is called
1866 * @param bool $relative
1867 * @param string $from
1870 * @return string|NULL
1872 public function dateDisplay($relative, $from, $to) {
1873 list($from, $to) = $this->getFromTo($relative, $from, $to);
1876 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1879 $clauses[] = 'Past';
1883 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1886 $clauses[] = 'Today';
1889 if (!empty($clauses)) {
1890 return implode(' - ', $clauses);
1897 * Get values for from and to for date ranges.
1899 * @param bool $relative
1900 * @param string $from
1902 * @param string $fromTime
1903 * @param string $toTime
1907 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1908 if (empty($toTime)) {
1911 //FIX ME not working for relative
1913 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1914 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1915 $from = substr($dateRange['from'], 0, 8);
1916 //Take only Date Part, Sometime Time part is also present in 'to'
1917 $to = substr($dateRange['to'], 0, 8);
1919 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1920 $to = CRM_Utils_Date
::processDate($to, $toTime);
1921 return array($from, $to);
1925 * Alter display of rows.
1927 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1928 * such as rendering contacts as links.
1930 * @param array $rows
1931 * Rows generated by SQL, with an array for each row.
1933 public function alterDisplay(&$rows) {
1937 * Alter the way in which custom data fields are displayed.
1939 * @param array $rows
1941 public function alterCustomDataDisplay(&$rows) {
1942 // custom code to alter rows having custom values
1943 if (empty($this->_customGroupExtends
)) {
1947 $customFieldIds = array();
1948 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1949 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1950 $customFieldIds[$fieldAlias] = $fieldId;
1953 if (empty($customFieldIds)) {
1957 $customFields = $fieldValueMap = array();
1958 $customFieldCols = array(
1966 // skip for type date and ContactReference since date format is already handled
1968 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1969 FROM civicrm_custom_field cf
1970 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1971 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1972 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1973 cg.is_active = 1 AND
1974 cf.is_active = 1 AND
1975 cf.is_searchable = 1 AND
1976 cf.data_type NOT IN ('ContactReference', 'Date') AND
1977 cf.id IN (" . implode(",", $customFieldIds) . ")";
1979 $dao = CRM_Core_DAO
::executeQuery($query);
1980 while ($dao->fetch()) {
1981 foreach ($customFieldCols as $key) {
1982 $customFields[$dao->table_name
. '_custom_' .
1983 $dao->id
][$key] = $dao->$key;
1985 if ($dao->option_group_id
) {
1986 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1991 $entryFound = FALSE;
1992 foreach ($rows as $rowNum => $row) {
1993 foreach ($row as $tableCol => $val) {
1994 if (array_key_exists($tableCol, $customFields)) {
1995 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
2000 // skip looking further in rows, if first row itself doesn't
2001 // have the column we need
2010 * @param $customField
2011 * @param $fieldValueMap
2013 * @return float|string|void
2015 public function formatCustomValues($value, $customField, $fieldValueMap) {
2016 if (CRM_Utils_System
::isNull($value)) {
2020 $htmlType = $customField['html_type'];
2022 switch ($customField['data_type']) {
2024 if ($value == '1') {
2025 $retValue = ts('Yes');
2028 $retValue = ts('No');
2033 $retValue = CRM_Utils_System
::formatWikiURL($value);
2045 if ($htmlType == 'Text') {
2046 $retValue = (float) $value;
2050 if ($htmlType == 'Text') {
2051 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2056 if (in_array($htmlType, array(
2063 case 'StateProvince':
2066 switch ($htmlType) {
2067 case 'Multi-Select Country':
2068 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2069 $customData = array();
2070 foreach ($value as $val) {
2072 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
2075 $retValue = implode(', ', $customData);
2078 case 'Select Country':
2079 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
2082 case 'Select State/Province':
2083 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2086 case 'Multi-Select State/Province':
2087 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2088 $customData = array();
2089 foreach ($value as $val) {
2091 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
2094 $retValue = implode(', ', $customData);
2099 case 'Autocomplete-Select':
2100 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2104 case 'AdvMulti-Select':
2105 case 'Multi-Select':
2106 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2107 $customData = array();
2108 foreach ($value as $val) {
2110 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2113 $retValue = implode(', ', $customData);
2131 public function removeDuplicates(&$rows) {
2132 if (empty($this->_noRepeats
)) {
2135 $checkList = array();
2137 foreach ($rows as $key => $list) {
2138 foreach ($list as $colName => $colVal) {
2139 if (array_key_exists($colName, $checkList) &&
2140 $checkList[$colName] == $colVal
2142 $rows[$key][$colName] = "";
2144 if (in_array($colName, $this->_noRepeats
)) {
2145 $checkList[$colName] = $colVal;
2154 * @param bool $subtotal
2156 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2157 foreach ($row as $colName => $colVal) {
2158 if (in_array($colName, $fields)) {
2160 elseif (isset($this->_columnHeaders
[$colName])) {
2162 $row[$colName] = "Subtotal";
2166 unset($row[$colName]);
2177 public function grandTotal(&$rows) {
2178 if (!$this->_rollup ||
($this->_rollup
== '') ||
2179 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2183 $lastRow = array_pop($rows);
2185 foreach ($this->_columnHeaders
as $fld => $val) {
2186 if (!in_array($fld, $this->_statFields
)) {
2187 if (!$this->_grandFlag
) {
2188 $lastRow[$fld] = "Grand Total";
2189 $this->_grandFlag
= TRUE;
2192 $lastRow[$fld] = "";
2197 $this->assign('grandStat', $lastRow);
2203 * @param bool $pager
2205 public function formatDisplay(&$rows, $pager = TRUE) {
2206 // set pager based on if any limit was applied in the query.
2211 // allow building charts if any
2212 if (!empty($this->_params
['charts']) && !empty($rows)) {
2213 $this->buildChart($rows);
2214 $this->assign('chartEnabled', TRUE);
2215 $this->_chartId
= "{$this->_params['charts']}_" .
2216 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2218 $this->assign('chartId', $this->_chartId
);
2221 // unset columns not to be displayed.
2222 foreach ($this->_columnHeaders
as $key => $value) {
2223 if (!empty($value['no_display'])) {
2224 unset($this->_columnHeaders
[$key]);
2228 // unset columns not to be displayed.
2229 if (!empty($rows)) {
2230 foreach ($this->_noDisplay
as $noDisplayField) {
2231 foreach ($rows as $rowNum => $row) {
2232 unset($this->_columnHeaders
[$noDisplayField]);
2237 // build array of section totals
2238 $this->sectionTotals();
2240 // process grand-total row
2241 $this->grandTotal($rows);
2243 // use this method for formatting rows for display purpose.
2244 $this->alterDisplay($rows);
2245 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2247 // use this method for formatting custom rows for display purpose.
2248 $this->alterCustomDataDisplay($rows);
2254 public function buildChart(&$rows) {
2255 // override this method for building charts.
2258 // select() method below has been added recently (v3.3), and many of the report templates might
2259 // still be having their own select() method. We should fix them as and when encountered and move
2260 // towards generalizing the select() method below.
2263 * Generate the SELECT clause and set class variable $_select
2265 public function select() {
2266 $select = $this->_selectAliases
= array();
2268 foreach ($this->_columns
as $tableName => $table) {
2269 if (array_key_exists('fields', $table)) {
2270 foreach ($table['fields'] as $fieldName => $field) {
2271 if ($tableName == 'civicrm_address') {
2272 $this->_addressField
= TRUE;
2274 if ($tableName == 'civicrm_email') {
2275 $this->_emailField
= TRUE;
2277 if ($tableName == 'civicrm_phone') {
2278 $this->_phoneField
= TRUE;
2281 if (!empty($field['required']) ||
2282 !empty($this->_params
['fields'][$fieldName])
2285 // 1. In many cases we want select clause to be built in slightly different way
2286 // for a particular field of a particular type.
2287 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2289 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2290 if ($selectClause) {
2291 $select[] = $selectClause;
2295 // include statistics columns only if set
2296 if (!empty($field['statistics'])) {
2297 foreach ($field['statistics'] as $stat => $label) {
2298 $alias = "{$tableName}_{$fieldName}_{$stat}";
2299 switch (strtolower($stat)) {
2302 $select[] = "$stat({$field['dbAlias']}) as $alias";
2303 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2304 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2305 $this->_statFields
[$label] = $alias;
2306 $this->_selectAliases
[] = $alias;
2310 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2311 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2312 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2313 $this->_statFields
[$label] = $alias;
2314 $this->_selectAliases
[] = $alias;
2317 case 'count_distinct':
2318 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2319 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2320 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2321 $this->_statFields
[$label] = $alias;
2322 $this->_selectAliases
[] = $alias;
2326 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2327 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2328 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2329 $this->_statFields
[$label] = $alias;
2330 $this->_selectAliases
[] = $alias;
2336 $alias = "{$tableName}_{$fieldName}";
2337 $select[] = "{$field['dbAlias']} as $alias";
2338 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2339 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2340 $this->_selectAliases
[] = $alias;
2346 // select for group bys
2347 if (array_key_exists('group_bys', $table)) {
2348 foreach ($table['group_bys'] as $fieldName => $field) {
2350 if ($tableName == 'civicrm_address') {
2351 $this->_addressField
= TRUE;
2353 if ($tableName == 'civicrm_email') {
2354 $this->_emailField
= TRUE;
2356 if ($tableName == 'civicrm_phone') {
2357 $this->_phoneField
= TRUE;
2359 // 1. In many cases we want select clause to be built in slightly different way
2360 // for a particular field of a particular type.
2361 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2363 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2364 if ($selectClause) {
2365 $select[] = $selectClause;
2369 if (!empty($this->_params
['group_bys']) &&
2370 !empty($this->_params
['group_bys'][$fieldName]) &&
2371 !empty($this->_params
['group_bys_freq'])
2373 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2375 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2376 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2377 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2378 $field['title'] = 'Week';
2382 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2383 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2384 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2385 $field['title'] = 'Year';
2389 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2390 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2391 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2392 $field['title'] = 'Month';
2396 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2397 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2398 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2399 $field['title'] = 'Quarter';
2402 // for graphs and charts -
2403 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2404 $this->_interval
= $field['title'];
2405 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2406 = $field['title'] . ' Beginning';
2407 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2408 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2410 // just to make sure these values are transferred to rows.
2411 // since we 'll need them for calculation purpose,
2412 // e.g making subtotals look nicer or graphs
2413 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2414 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2421 $this->_selectClauses
= $select;
2422 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2426 * @param string $tableName
2428 * @param string $fieldName
2433 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2437 public function where() {
2438 $this->storeWhereHavingClauseArray();
2440 if (empty($this->_whereClauses
)) {
2441 $this->_where
= "WHERE ( 1 ) ";
2442 $this->_having
= "";
2445 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2448 if ($this->_aclWhere
) {
2449 $this->_where
.= " AND {$this->_aclWhere} ";
2452 if (!empty($this->_havingClauses
)) {
2453 // use this clause to construct group by clause.
2454 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2459 * Store Where clauses into an array - breaking out this step makes
2460 * over-riding more flexible as the clauses can be used in constructing a
2461 * temp table that may not be part of the final where clause or added
2462 * in other functions
2464 public function storeWhereHavingClauseArray() {
2465 foreach ($this->_columns
as $tableName => $table) {
2466 if (array_key_exists('filters', $table)) {
2467 foreach ($table['filters'] as $fieldName => $field) {
2468 // respect pseudofield to filter spec so fields can be marked as
2469 // not to be handled here
2470 if (!empty($field['pseudofield'])) {
2474 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2475 if (CRM_Utils_Array
::value('operatorType', $field) ==
2476 CRM_Report_Form
::OP_MONTH
2478 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2479 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2480 if (is_array($value) && !empty($value)) {
2482 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2487 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2488 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2489 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2490 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2491 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2492 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2496 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2498 $clause = $this->whereClause($field,
2500 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2501 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2502 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2507 if (!empty($clause)) {
2508 if (!empty($field['having'])) {
2509 $this->_havingClauses
[] = $clause;
2512 $this->_whereClauses
[] = $clause;
2521 public function processReportMode() {
2522 $buttonName = $this->controller
->getButtonName();
2524 $output = CRM_Utils_Request
::retrieve(
2527 CRM_Core_DAO
::$_nullObject
2531 = CRM_Utils_Request
::retrieve(
2534 CRM_Core_DAO
::$_nullObject
2537 $this->_absoluteUrl
= FALSE;
2539 $this->assign('printOnly', FALSE);
2541 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2542 ($this->_sendmail
&& !$output)
2544 $this->assign('printOnly', TRUE);
2546 $this->assign('outputMode', 'print');
2547 $this->_outputMode
= 'print';
2548 if ($this->_sendmail
) {
2549 $this->_absoluteUrl
= TRUE;
2552 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2553 $this->assign('printOnly', TRUE);
2555 $this->assign('outputMode', 'pdf');
2556 $this->_outputMode
= 'pdf';
2557 $this->_absoluteUrl
= TRUE;
2559 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2560 $this->assign('printOnly', TRUE);
2562 $this->assign('outputMode', 'csv');
2563 $this->_outputMode
= 'csv';
2564 $this->_absoluteUrl
= TRUE;
2566 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2567 $this->assign('outputMode', 'group');
2568 $this->_outputMode
= 'group';
2570 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2571 $this->assign('outputMode', 'create_report');
2572 $this->_outputMode
= 'create_report';
2575 $this->assign('outputMode', 'html');
2576 $this->_outputMode
= 'html';
2579 // Get today's date to include in printed reports
2581 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2582 $this->assign('reportDate', $reportDate);
2587 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2589 public function beginPostProcess() {
2590 $this->setParams($this->controller
->exportValues($this->_name
));
2592 if (empty($this->_params
) &&
2595 $this->setParams($this->_formValues
);
2598 // hack to fix params when submitted from dashboard, CRM-8532
2599 // fields array is missing because form building etc is skipped
2600 // in dashboard mode for report
2601 //@todo - this could be done in the dashboard no we have a setter
2602 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2603 $this->setParams($this->_formValues
);
2606 $this->_formValues
= $this->_params
;
2607 if (CRM_Core_Permission
::check('administer Reports') &&
2608 isset($this->_id
) &&
2609 ($this->_instanceButtonName
==
2610 $this->controller
->getButtonName() . '_save' ||
2611 $this->_chartButtonName
== $this->controller
->getButtonName()
2614 $this->assign('updateReportButton', TRUE);
2616 $this->processReportMode();
2617 $this->beginPostProcessCommon();
2621 * BeginPostProcess function run in both report mode and non-report mode (api)
2623 public function beginPostProcessCommon() {
2628 * @param bool $applyLimit
2632 public function buildQuery($applyLimit = TRUE) {
2635 $this->customDataFrom();
2640 // order_by columns not selected for display need to be included in SELECT
2641 $unselectedSectionColumns = $this->unselectedSectionColumns();
2642 foreach ($unselectedSectionColumns as $alias => $section) {
2643 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2646 if ($applyLimit && empty($this->_params
['charts'])) {
2649 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2651 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2655 public function groupBy() {
2656 $groupBys = array();
2657 if (!empty($this->_params
['group_bys']) &&
2658 is_array($this->_params
['group_bys']) &&
2659 !empty($this->_params
['group_bys'])
2661 foreach ($this->_columns
as $tableName => $table) {
2662 if (array_key_exists('group_bys', $table)) {
2663 foreach ($table['group_bys'] as $fieldName => $field) {
2664 if (!empty($this->_params
['group_bys'][$fieldName])) {
2665 $groupBys[] = $field['dbAlias'];
2672 if (!empty($groupBys)) {
2673 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2677 public function orderBy() {
2678 $this->_orderBy
= "";
2679 $this->_sections
= array();
2680 $this->storeOrderByArray();
2681 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2682 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2684 $this->assign('sections', $this->_sections
);
2688 * In some cases other functions want to know which fields are selected for ordering by
2689 * Separating this into a separate function allows it to be called separately from constructing
2690 * the order by clause
2692 public function storeOrderByArray() {
2693 $orderBys = array();
2695 if (!empty($this->_params
['order_bys']) &&
2696 is_array($this->_params
['order_bys']) &&
2697 !empty($this->_params
['order_bys'])
2700 // Process order_bys in user-specified order
2701 foreach ($this->_params
['order_bys'] as $orderBy) {
2702 $orderByField = array();
2703 foreach ($this->_columns
as $tableName => $table) {
2704 if (array_key_exists('order_bys', $table)) {
2705 // For DAO columns defined in $this->_columns
2706 $fields = $table['order_bys'];
2708 elseif (array_key_exists('extends', $table)) {
2709 // For custom fields referenced in $this->_customGroupExtends
2710 $fields = CRM_Utils_Array
::value('fields', $table, array());
2715 if (!empty($fields) && is_array($fields)) {
2716 foreach ($fields as $fieldName => $field) {
2717 if ($fieldName == $orderBy['column']) {
2718 $orderByField = array_merge($field, $orderBy);
2719 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2726 if (!empty($orderByField)) {
2727 $this->_orderByFields
[] = $orderByField;
2728 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2730 // Record any section headers for assignment to the template
2731 if (!empty($orderBy['section'])) {
2732 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2733 $this->_sections
[$orderByField['tplField']] = $orderByField;
2739 $this->_orderByArray
= $orderBys;
2741 $this->assign('sections', $this->_sections
);
2747 public function unselectedSectionColumns() {
2748 $selectColumns = array();
2749 foreach ($this->_columns
as $tableName => $table) {
2750 if (array_key_exists('fields', $table)) {
2751 foreach ($table['fields'] as $fieldName => $field) {
2752 if (!empty($field['required']) ||
2753 !empty($this->_params
['fields'][$fieldName])
2756 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2762 if (is_array($this->_sections
)) {
2763 return array_diff_key($this->_sections
, $selectColumns);
2774 public function buildRows($sql, &$rows) {
2775 $dao = CRM_Core_DAO
::executeQuery($sql);
2776 if (!is_array($rows)) {
2780 // use this method to modify $this->_columnHeaders
2781 $this->modifyColumnHeaders();
2783 $unselectedSectionColumns = $this->unselectedSectionColumns();
2785 while ($dao->fetch()) {
2787 foreach ($this->_columnHeaders
as $key => $value) {
2788 if (property_exists($dao, $key)) {
2789 $row[$key] = $dao->$key;
2793 // section headers not selected for display need to be added to row
2794 foreach ($unselectedSectionColumns as $key => $values) {
2795 if (property_exists($dao, $key)) {
2796 $row[$key] = $dao->$key;
2805 * When "order by" fields are marked as sections, this assigns to the template
2806 * an array of total counts for each section. This data is used by the Smarty
2807 * plugin {sectionTotal}
2809 public function sectionTotals() {
2811 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2812 if (empty($this->_selectAliases
)) {
2816 if (!empty($this->_sections
)) {
2817 // build the query with no LIMIT clause
2818 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2819 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2821 // pull section aliases out of $this->_sections
2822 $sectionAliases = array_keys($this->_sections
);
2825 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2826 $ifnulls[] = "ifnull($alias, '') as $alias";
2829 // Group (un-limited) report by all aliases and get counts. This might
2830 // be done more efficiently when the contents of $sql are known, ie. by
2831 // overriding this method in the report class.
2833 $query = "select " . implode(", ", $ifnulls) .
2834 ", count(*) as ct from ($sql) as subquery group by " .
2835 implode(", ", $sectionAliases);
2837 // initialize array of total counts
2839 $dao = CRM_Core_DAO
::executeQuery($query);
2840 while ($dao->fetch()) {
2842 // let $this->_alterDisplay translate any integer ids to human-readable values.
2843 $rows[0] = $dao->toArray();
2844 $this->alterDisplay($rows);
2847 // add totals for all permutations of section values
2850 $aliasCount = count($sectionAliases);
2851 foreach ($sectionAliases as $alias) {
2852 $values[] = $row[$alias];
2853 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2854 if ($i == $aliasCount) {
2855 // the last alias is the lowest-level section header; use count as-is
2856 $totals[$key] = $dao->ct
;
2859 // other aliases are higher level; roll count into their total
2860 $totals[$key] +
= $dao->ct
;
2864 $this->assign('sectionTotals', $totals);
2868 public function modifyColumnHeaders() {
2869 // use this method to modify $this->_columnHeaders
2875 public function doTemplateAssignment(&$rows) {
2876 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2877 $this->assign_by_ref('rows', $rows);
2878 $this->assign('statistics', $this->statistics($rows));
2882 * override this method to build your own statistics
2887 public function statistics(&$rows) {
2888 $statistics = array();
2890 $count = count($rows);
2892 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2896 $this->countStat($statistics, $count);
2898 $this->groupByStat($statistics);
2900 $this->filterStat($statistics);
2906 * @param $statistics
2909 public function countStat(&$statistics, $count) {
2910 $statistics['counts']['rowCount'] = array(
2911 'title' => ts('Row(s) Listed'),
2915 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2916 $statistics['counts']['rowsFound'] = array(
2917 'title' => ts('Total Row(s)'),
2918 'value' => $this->_rowsFound
,
2924 * @param $statistics
2926 public function groupByStat(&$statistics) {
2927 if (!empty($this->_params
['group_bys']) &&
2928 is_array($this->_params
['group_bys']) &&
2929 !empty($this->_params
['group_bys'])
2931 foreach ($this->_columns
as $tableName => $table) {
2932 if (array_key_exists('group_bys', $table)) {
2933 foreach ($table['group_bys'] as $fieldName => $field) {
2934 if (!empty($this->_params
['group_bys'][$fieldName])) {
2935 $combinations[] = $field['title'];
2940 $statistics['groups'][] = array(
2941 'title' => ts('Grouping(s)'),
2942 'value' => implode(' & ', $combinations),
2948 * @param $statistics
2950 public function filterStat(&$statistics) {
2951 foreach ($this->_columns
as $tableName => $table) {
2952 if (array_key_exists('filters', $table)) {
2953 foreach ($table['filters'] as $fieldName => $field) {
2954 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
2955 CRM_Utils_Array
::value('operatorType', $field) !=
2956 CRM_Report_Form
::OP_MONTH
2960 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2961 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2962 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2963 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2964 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2966 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
2967 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
2969 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
2970 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
2973 $statistics['filters'][] = array(
2974 'title' => $field['title'],
2975 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2978 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2979 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
2981 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
2982 $statistics['filters'][] = array(
2983 'title' => $field['title'],
2984 'value' => $pair[$rel],
2989 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2992 $pair = $this->getOperationPair(
2993 CRM_Utils_Array
::value('operatorType', $field),
2996 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2997 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2998 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2999 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3000 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3002 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3003 $this->setEntityRefDefaults($field, $tableName);
3004 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3005 array('id' => $val) +
3006 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3008 foreach ($result['values'] as $v) {
3009 $values[] = $v['label'];
3011 $value = "{$pair[$op]} " . implode(', ', $values);
3013 elseif ($op == 'nll' ||
$op == 'nnll') {
3014 $value = $pair[$op];
3016 elseif (is_array($val) && (!empty($val))) {
3017 $options = CRM_Utils_Array
::value('options', $field, array());
3018 foreach ($val as $key => $valIds) {
3019 if (isset($options[$valIds])) {
3020 $val[$key] = $options[$valIds];
3023 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3024 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3025 $val = implode(', ', $val);
3026 $value = "{$pair[$op]} " . $val;
3028 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3029 isset($field['options']) &&
3030 is_array($field['options']) && !empty($field['options'])
3032 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3033 CRM_Utils_Array
::value($val, $field['options'], $val);
3036 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3040 $statistics['filters'][] = array(
3041 'title' => CRM_Utils_Array
::value('title', $field),
3052 * End post processing.
3054 * @param array|null $rows
3056 public function endPostProcess(&$rows = NULL) {
3057 if ($this->_storeResultSet
) {
3058 $this->_resultSet
= $rows;
3061 if ($this->_outputMode
== 'print' ||
3062 $this->_outputMode
== 'pdf' ||
3066 $content = $this->compileContent();
3067 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3071 if ($this->_sendmail
) {
3072 $config = CRM_Core_Config
::singleton();
3073 $attachments = array();
3075 if ($this->_outputMode
== 'csv') {
3077 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3078 ": {$url}</p>" . '<p>' .
3079 ts('The report is attached as a CSV file.') . '</p>' .
3080 $this->_formValues
['report_footer'];
3082 $csvFullFilename = $config->templateCompileDir
.
3083 CRM_Utils_File
::makeFileName('CiviReport.csv');
3084 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3085 file_put_contents($csvFullFilename, $csvContent);
3086 $attachments[] = array(
3087 'fullPath' => $csvFullFilename,
3088 'mime_type' => 'text/csv',
3089 'cleanName' => 'CiviReport.csv',
3092 if ($this->_outputMode
== 'pdf') {
3093 // generate PDF content
3094 $pdfFullFilename = $config->templateCompileDir
.
3095 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3096 file_put_contents($pdfFullFilename,
3097 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3098 TRUE, array('orientation' => 'landscape')
3101 // generate Email Content
3103 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3104 ": {$url}</p>" . '<p>' .
3105 ts('The report is attached as a PDF file.') . '</p>' .
3106 $this->_formValues
['report_footer'];
3108 $attachments[] = array(
3109 'fullPath' => $pdfFullFilename,
3110 'mime_type' => 'application/pdf',
3111 'cleanName' => 'CiviReport.pdf',
3115 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3116 $this->_outputMode
, $attachments
3119 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3122 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3126 elseif ($this->_outputMode
== 'print') {
3130 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3131 $config = CRM_Core_Config
::singleton();
3132 //get chart image name
3133 $chartImg = $this->_chartId
. '.png';
3134 //get image url path
3136 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3138 $uploadUrl .= $chartImg;
3139 //get image doc path to overwrite
3141 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3142 'openFlashChart/' . $chartImg;
3144 $chart = imagecreatefrompng($uploadUrl);
3145 //convert it into formatted png
3146 header('Content-type: image/png');
3147 //overwrite with same image
3148 imagepng($chart, $uploadImg);
3150 imagedestroy($chart);
3152 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3154 CRM_Utils_System
::civiExit();
3156 elseif ($this->_outputMode
== 'csv') {
3157 CRM_Report_Utils_Report
::export2csv($this, $rows);
3159 elseif ($this->_outputMode
== 'group') {
3160 $group = $this->_params
['groups'];
3161 $this->add2group($group);
3163 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3164 CRM_Report_Form_Instance
::postProcess($this);
3166 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3167 $this->_outputMode
== 'create_report'
3169 $this->_createNew
= TRUE;
3170 CRM_Report_Form_Instance
::postProcess($this);
3175 * Set store result set indicator to TRUE.
3177 * @todo explain what this does
3179 public function storeResultSet() {
3180 $this->_storeResultSet
= TRUE;
3188 public function getResultSet() {
3189 return $this->_resultSet
;
3193 * Use the form name to create the tpl file name.
3197 public function getTemplateFileName() {
3198 $defaultTpl = parent
::getTemplateFileName();
3199 $template = CRM_Core_Smarty
::singleton();
3200 if (!$template->template_exists($defaultTpl)) {
3201 $defaultTpl = 'CRM/Report/Form.tpl';
3207 * Compile the report content.
3208 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3212 public function compileContent() {
3213 $templateFile = $this->getHookedTemplateFileName();
3214 return $this->_formValues
['report_header'] .
3215 CRM_Core_Form
::$_template->fetch($templateFile) .
3216 $this->_formValues
['report_footer'];
3220 public function postProcess() {
3221 // get ready with post process params
3222 $this->beginPostProcess();
3225 $sql = $this->buildQuery();
3227 // build array of result based on column headers. This method also allows
3228 // modifying column headers before using it to build result set i.e $rows.
3230 $this->buildRows($sql, $rows);
3232 // format result set.
3233 $this->formatDisplay($rows);
3235 // assign variables to templates
3236 $this->doTemplateAssignment($rows);
3238 // do print / pdf / instance stuff if needed
3239 $this->endPostProcess($rows);
3243 * @param int $rowCount
3246 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3247 // lets do the pager if in html mode
3248 $this->_limit
= NULL;
3250 // CRM-14115, over-ride row count if rowCount is specified in URL
3251 if ($this->_dashBoardRowCount
) {
3252 $rowCount = $this->_dashBoardRowCount
;
3254 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3255 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3257 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3259 // @todo all http vars should be extracted in the preProcess
3260 // - not randomly in the class
3261 if (!$pageId && !empty($_POST)) {
3262 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3263 $pageId = max((int) $_POST['crmPID_B'], 1);
3265 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3266 $pageId = max((int) $_POST['crmPID'], 1);
3268 unset($_POST['crmPID_B'], $_POST['crmPID']);
3271 $pageId = $pageId ?
$pageId : 1;
3272 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3273 $offset = ($pageId - 1) * $rowCount;
3275 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3276 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3278 $this->_limit
= " LIMIT $offset, $rowCount";
3279 return array($offset, $rowCount);
3281 if ($this->_limitValue
) {
3282 if ($this->_offsetValue
) {
3283 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3286 $this->_limit
= " LIMIT " . $this->_limitValue
;
3292 * @param int $rowCount
3294 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3296 // CRM-14115, over-ride row count if rowCount is specified in URL
3297 if ($this->_dashBoardRowCount
) {
3298 $rowCount = $this->_dashBoardRowCount
;
3301 if ($this->_limit
&& ($this->_limit
!= '')) {
3302 $sql = "SELECT FOUND_ROWS();";
3303 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3305 'total' => $this->_rowsFound
,
3306 'rowCount' => $rowCount,
3307 'status' => ts('Records') . ' %%StatusMessage%%',
3308 'buttonBottom' => 'PagerBottomButton',
3309 'buttonTop' => 'PagerTopButton',
3310 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3313 $pager = new CRM_Utils_Pager($params);
3314 $this->assign_by_ref('pager', $pager);
3315 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3326 public function whereGroupClause($field, $value, $op) {
3328 $smartGroupQuery = "";
3330 $group = new CRM_Contact_DAO_Group();
3331 $group->is_active
= 1;
3333 $smartGroups = array();
3334 while ($group->fetch()) {
3335 if (in_array($group->id
, $this->_params
['gid_value']) &&
3336 $group->saved_search_id
3338 $smartGroups[] = $group->id
;
3342 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3344 $smartGroupQuery = '';
3345 if (!empty($smartGroups)) {
3346 $smartGroups = implode(',', $smartGroups);
3347 $smartGroupQuery = " UNION DISTINCT
3348 SELECT DISTINCT smartgroup_contact.contact_id
3349 FROM civicrm_group_contact_cache smartgroup_contact
3350 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3353 $sqlOp = $this->getSQLOperator($op);
3354 if (!is_array($value)) {
3355 $value = array($value);
3357 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3359 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3360 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3361 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3362 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3363 {$smartGroupQuery} ) ";
3373 public function whereTagClause($field, $value, $op) {
3374 // not using left join in query because if any contact
3375 // belongs to more than one tag, results duplicate
3377 $sqlOp = $this->getSQLOperator($op);
3378 if (!is_array($value)) {
3379 $value = array($value);
3381 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3382 $entity_table = $this->_tagFilterTable
;
3383 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3384 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3385 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3386 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3390 * Generate membership organization clause.
3392 * @param mixed $value
3393 * @param string $op SQL Operator
3397 public function whereMembershipOrgClause($value, $op) {
3398 $sqlOp = $this->getSQLOperator($op);
3399 if (!is_array($value)) {
3400 $value = array($value);
3403 $tmp_membership_org_sql_list = implode(', ', $value);
3404 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3405 SELECT DISTINCT mem.contact_id
3406 FROM civicrm_membership mem
3407 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3408 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3409 WHERE mt.member_of_contact_id IN (" .
3410 $tmp_membership_org_sql_list . ")
3411 AND mt.is_active = '1'
3412 AND mem_status.is_current_member = '1'
3413 AND mem_status.is_active = '1' ) ";
3417 * Generate Membership Type SQL Clause.
3418 * @param mixed $value
3424 public function whereMembershipTypeClause($value, $op) {
3425 $sqlOp = $this->getSQLOperator($op);
3426 if (!is_array($value)) {
3427 $value = array($value);
3430 $tmp_membership_sql_list = implode(', ', $value);
3431 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3432 SELECT DISTINCT mem.contact_id
3433 FROM civicrm_membership mem
3434 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3435 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3436 WHERE mem.membership_type_id IN (" .
3437 $tmp_membership_sql_list . ")
3438 AND mt.is_active = '1'
3439 AND mem_status.is_current_member = '1'
3440 AND mem_status.is_active = '1' ) ";
3444 * @param string $tableAlias
3446 public function buildACLClause($tableAlias = 'contact_a') {
3447 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3451 * @param bool $addFields
3452 * @param array $permCustomGroupIds
3454 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3455 if (empty($this->_customGroupExtends
)) {
3458 if (!is_array($this->_customGroupExtends
)) {
3459 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3461 $customGroupWhere = '';
3462 if (!empty($permCustomGroupIds)) {
3463 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3467 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3468 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3469 FROM civicrm_custom_group cg
3470 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3471 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3473 cg.is_active = 1 AND
3474 cf.is_active = 1 AND
3475 cf.is_searchable = 1
3476 ORDER BY cg.weight, cf.weight";
3477 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3480 while ($customDAO->fetch()) {
3481 if ($customDAO->table_name
!= $curTable) {
3482 $curTable = $customDAO->table_name
;
3483 $curFields = $curFilters = array();
3486 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3487 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3488 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3489 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3496 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3497 $this->_columns
[$curTable][$colKey] = array();
3501 $fieldName = 'custom_' . $customDAO->cf_id
;
3504 // this makes aliasing work in favor
3505 $curFields[$fieldName] = array(
3506 'name' => $customDAO->column_name
,
3507 'title' => $customDAO->label
,
3508 'dataType' => $customDAO->data_type
,
3509 'htmlType' => $customDAO->html_type
,
3512 if ($this->_customGroupFilters
) {
3513 // this makes aliasing work in favor
3514 $curFilters[$fieldName] = array(
3515 'name' => $customDAO->column_name
,
3516 'title' => $customDAO->label
,
3517 'dataType' => $customDAO->data_type
,
3518 'htmlType' => $customDAO->html_type
,
3522 switch ($customDAO->data_type
) {
3525 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3526 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3527 // CRM-6946, show time part for datetime date fields
3528 if ($customDAO->time_format
) {
3529 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3534 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3535 $curFilters[$fieldName]['options'] = array(
3536 '' => ts('- select -'),
3540 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3544 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3545 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3549 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3550 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3554 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3555 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3559 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3561 if (!empty($customDAO->option_group_id
)) {
3562 if (in_array($customDAO->html_type
, array(
3567 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3570 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3572 if ($this->_customGroupFilters
) {
3573 $curFilters[$fieldName]['options'] = array();
3574 $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(
3576 $customDAO->option_group_id
,
3580 while ($ogDAO->fetch()) {
3581 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3583 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3588 case 'StateProvince':
3589 if (in_array($customDAO->html_type
, array(
3590 'Multi-Select State/Province',
3592 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3595 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3597 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3601 if (in_array($customDAO->html_type
, array(
3602 'Multi-Select Country',
3604 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3607 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3609 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3612 case 'ContactReference':
3613 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3614 $curFilters[$fieldName]['name'] = 'display_name';
3615 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3617 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3618 $curFields[$fieldName]['name'] = 'display_name';
3619 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3623 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3624 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3627 if (!array_key_exists('type', $curFields[$fieldName])) {
3628 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3632 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3634 if ($this->_customGroupFilters
) {
3635 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3637 if ($this->_customGroupGroupBy
) {
3638 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3643 public function customDataFrom() {
3644 if (empty($this->_customGroupExtends
)) {
3647 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3649 foreach ($this->_columns
as $table => $prop) {
3650 if (substr($table, 0, 13) == 'civicrm_value' ||
3651 substr($table, 0, 12) == 'custom_value'
3653 $extendsTable = $mapper[$prop['extends']];
3655 // check field is in params
3656 if (!$this->isFieldSelected($prop)) {
3659 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3661 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3663 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3664 // handle for ContactReference
3665 if (array_key_exists('fields', $prop)) {
3666 foreach ($prop['fields'] as $fieldName => $field) {
3667 if (CRM_Utils_Array
::value('dataType', $field) ==
3670 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3672 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3685 public function isFieldSelected($prop) {
3690 if (!empty($this->_params
['fields'])) {
3691 foreach (array_keys($prop['fields']) as $fieldAlias) {
3692 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3693 if ($customFieldId) {
3694 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3698 //might be survey response field.
3699 if (!empty($this->_params
['fields']['survey_response']) &&
3700 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3708 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3709 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3710 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3711 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3718 if (!empty($this->_params
['order_bys'])) {
3719 foreach (array_keys($prop['fields']) as $fieldAlias) {
3720 foreach ($this->_params
['order_bys'] as $orderBy) {
3721 if ($fieldAlias == $orderBy['column'] &&
3722 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3730 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3731 foreach ($prop['filters'] as $fieldAlias => $val) {
3740 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3741 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3742 ||
($attach != 'relative' &&
3743 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3749 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3750 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3761 * Check for empty order_by configurations and remove them; also set
3762 * template to hide them.
3764 * @param array $formValues
3766 public function preProcessOrderBy(&$formValues) {
3767 // Object to show/hide form elements
3768 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3770 $_showHide->addShow('optionField_1');
3772 // Cycle through order_by options; skip any empty ones, and hide them as well
3775 if (!empty($formValues['order_bys'])) {
3776 foreach ($formValues['order_bys'] as $order_by) {
3777 if ($order_by['column'] && $order_by['column'] != '-') {
3778 $_showHide->addShow('optionField_' . $n);
3779 $orderBys[$n] = $order_by;
3784 for ($i = $n; $i <= 5; $i++
) {
3786 $_showHide->addHide('optionField_' . $i);
3790 // overwrite order_by options with modified values
3791 if (!empty($orderBys)) {
3792 $formValues['order_bys'] = $orderBys;
3795 $formValues['order_bys'] = array(1 => array('column' => '-'));
3798 // assign show/hide data to template
3799 $_showHide->addToTemplate();
3803 * Does table name have columns in SELECT clause?
3805 * @param string $tableName
3806 * Name of table (index of $this->_columns array).
3810 public function isTableSelected($tableName) {
3811 return in_array($tableName, $this->selectedTables());
3815 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3816 * (building the array if it's unset)
3821 public function selectedTables() {
3822 if (!$this->_selectedTables
) {
3823 $orderByColumns = array();
3824 if (array_key_exists('order_bys', $this->_params
) &&
3825 is_array($this->_params
['order_bys'])
3827 foreach ($this->_params
['order_bys'] as $orderBy) {
3828 $orderByColumns[] = $orderBy['column'];
3832 foreach ($this->_columns
as $tableName => $table) {
3833 if (array_key_exists('fields', $table)) {
3834 foreach ($table['fields'] as $fieldName => $field) {
3835 if (!empty($field['required']) ||
3836 !empty($this->_params
['fields'][$fieldName])
3838 $this->_selectedTables
[] = $tableName;
3843 if (array_key_exists('order_bys', $table)) {
3844 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3845 if (in_array($orderByName, $orderByColumns)) {
3846 $this->_selectedTables
[] = $tableName;
3851 if (array_key_exists('filters', $table)) {
3852 foreach ($table['filters'] as $filterName => $filter) {
3853 if (!empty($this->_params
["{$filterName}_value"]) ||
3854 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3856 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3859 $this->_selectedTables
[] = $tableName;
3866 return $this->_selectedTables
;
3870 * @deprecated - use getAddressColumns which is a more accurate description
3871 * and also accepts an array of options rather than a long list
3873 * adding address fields to construct function in reports
3875 * @param bool $groupBy
3876 * Add GroupBy? Not appropriate for detail report.
3877 * @param bool $orderBy
3878 * Add GroupBy? Not appropriate for detail report.
3879 * @param bool $filters
3880 * @param array $defaults
3883 * address fields for construct clause
3885 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3886 $addressFields = array(
3887 'civicrm_address' => array(
3888 'dao' => 'CRM_Core_DAO_Address',
3891 'title' => ts('Address Name'),
3892 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3894 'street_address' => array(
3895 'title' => ts('Street Address'),
3896 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3898 'supplemental_address_1' => array(
3899 'title' => ts('Supplementary Address Field 1'),
3900 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3902 'supplemental_address_2' => array(
3903 'title' => ts('Supplementary Address Field 2'),
3904 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3906 'street_number' => array(
3907 'name' => 'street_number',
3908 'title' => ts('Street Number'),
3910 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3912 'street_name' => array(
3913 'name' => 'street_name',
3914 'title' => ts('Street Name'),
3916 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3918 'street_unit' => array(
3919 'name' => 'street_unit',
3920 'title' => ts('Street Unit'),
3922 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3925 'title' => ts('City'),
3926 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3928 'postal_code' => array(
3929 'title' => ts('Postal Code'),
3930 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3932 'postal_code_suffix' => array(
3933 'title' => ts('Postal Code Suffix'),
3934 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
3936 'country_id' => array(
3937 'title' => ts('Country'),
3938 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3940 'state_province_id' => array(
3941 'title' => ts('State/Province'),
3942 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3944 'county_id' => array(
3945 'title' => ts('County'),
3946 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3949 'grouping' => 'location-fields',
3954 $addressFields['civicrm_address']['filters'] = array(
3955 'street_number' => array(
3956 'title' => ts('Street Number'),
3958 'name' => 'street_number',
3960 'street_name' => array(
3961 'title' => ts('Street Name'),
3962 'name' => 'street_name',
3963 'operator' => 'like',
3965 'postal_code' => array(
3966 'title' => ts('Postal Code'),
3968 'name' => 'postal_code',
3971 'title' => ts('City'),
3972 'operator' => 'like',
3975 'country_id' => array(
3976 'name' => 'country_id',
3977 'title' => ts('Country'),
3978 'type' => CRM_Utils_Type
::T_INT
,
3979 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3980 'options' => CRM_Core_PseudoConstant
::country(),
3982 'state_province_id' => array(
3983 'name' => 'state_province_id',
3984 'title' => ts('State/Province'),
3985 'type' => CRM_Utils_Type
::T_INT
,
3986 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3987 'options' => array(),
3989 'county_id' => array(
3990 'name' => 'county_id',
3991 'title' => ts('County'),
3992 'type' => CRM_Utils_Type
::T_INT
,
3993 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
3994 'options' => array(),
4000 $addressFields['civicrm_address']['order_bys'] = array(
4001 'street_name' => array('title' => ts('Street Name')),
4002 'street_number' => array('title' => 'Odd / Even Street Number'),
4003 'street_address' => NULL,
4005 'postal_code' => NULL,
4010 $addressFields['civicrm_address']['group_bys'] = array(
4011 'street_address' => NULL,
4013 'postal_code' => NULL,
4014 'state_province_id' => array(
4015 'title' => ts('State/Province'),
4017 'country_id' => array(
4018 'title' => ts('Country'),
4020 'county_id' => array(
4021 'title' => ts('County'),
4025 return $addressFields;
4029 * Do AlterDisplay processing on Address Fields.
4039 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
4040 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4041 $entryFound = FALSE;
4043 if (array_key_exists('civicrm_address_country_id', $row)) {
4044 if ($value = $row['civicrm_address_country_id']) {
4045 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4046 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4047 "reset=1&force=1&{$criteriaQueryParams}&" .
4048 "country_id_op=in&country_id_value={$value}",
4049 $this->_absoluteUrl
, $this->_id
4051 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4052 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4059 if (array_key_exists('civicrm_address_county_id', $row)) {
4060 if ($value = $row['civicrm_address_county_id']) {
4061 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4062 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4063 "reset=1&force=1&{$criteriaQueryParams}&" .
4064 "county_id_op=in&county_id_value={$value}",
4065 $this->_absoluteUrl
, $this->_id
4067 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4068 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4074 // handle state province
4075 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4076 if ($value = $row['civicrm_address_state_province_id']) {
4077 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4079 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4080 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4081 $this->_absoluteUrl
, $this->_id
4083 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4084 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4095 * Adjusts dates passed in to YEAR() for fiscal year.
4097 * @param string $fieldName
4101 public function fiscalYearOffset($fieldName) {
4102 $config = CRM_Core_Config
::singleton();
4103 $fy = $config->fiscalYearStart
;
4104 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4105 ($fy['d'] == 1 && $fy['M'] == 1)
4107 return "YEAR( $fieldName )";
4109 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4110 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4114 * Add Address into From Table if required.
4116 public function addAddressFromClause() {
4117 // include address field if address column is to be included
4118 if ((isset($this->_addressField
) &&
4119 $this->_addressField
4121 $this->isTableSelected('civicrm_address')
4124 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4125 ON ({$this->_aliases['civicrm_contact']}.id =
4126 {$this->_aliases['civicrm_address']}.contact_id) AND
4127 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4132 * Add Phone into From Table if required.
4134 public function addPhoneFromClause() {
4135 // include address field if address column is to be included
4136 if ($this->isTableSelected('civicrm_phone')
4139 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4140 ON ({$this->_aliases['civicrm_contact']}.id =
4141 {$this->_aliases['civicrm_phone']}.contact_id) AND
4142 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4147 * Get phone columns to add to array.
4149 * @param array $options
4150 * - prefix Prefix to add to table (in case of more than one instance of the table)
4151 * - prefix_label Label to give columns from this phone table instance
4154 * phone columns definition
4156 public function getPhoneColumns($options = array()) {
4157 $defaultOptions = array(
4159 'prefix_label' => '',
4162 $options = array_merge($defaultOptions, $options);
4165 $options['prefix'] . 'civicrm_phone' => array(
4166 'dao' => 'CRM_Core_DAO_Phone',
4168 $options['prefix'] . 'phone' => array(
4169 'title' => ts($options['prefix_label'] . 'Phone'),
4179 * Get address columns to add to array.
4181 * @param array $options
4182 * - prefix Prefix to add to table (in case of more than one instance of the table)
4183 * - prefix_label Label to give columns from this address table instance
4186 * address columns definition
4188 public function getAddressColumns($options = array()) {
4191 'prefix_label' => '',
4195 'defaults' => array(),
4197 return $this->addAddressFields(
4198 $options['group_by'],
4199 $options['order_by'],
4200 $options['filters'],
4201 $options['defaults']
4206 * @param int $groupID
4208 public function add2group($groupID) {
4209 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4210 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4211 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4213 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4214 $sql = str_replace('WITH ROLLUP', '', $sql);
4215 $dao = CRM_Core_DAO
::executeQuery($sql);
4217 $contact_ids = array();
4218 // Add resulting contacts to group
4219 while ($dao->fetch()) {
4220 if ($dao->addtogroup_contact_id
) {
4221 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4225 if (!empty($contact_ids)) {
4226 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4227 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4230 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4236 * function used for showing charts on print screen.
4238 public static function uploadChartImage() {
4239 // upload strictly for '.png' images
4240 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4241 if (preg_match('/\.png$/', $name)) {
4243 // POST data is usually string data, but we are passing a RAW .png
4244 // so PHP is a bit confused and $_POST is empty. But it has saved
4245 // the raw bits into $HTTP_RAW_POST_DATA
4247 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4249 // prepare the directory
4250 $config = CRM_Core_Config
::singleton();
4252 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4254 if (!file_exists($defaultPath)) {
4255 mkdir($defaultPath, 0777, TRUE);
4258 // full path to the saved image including filename
4259 $destination = $defaultPath . $name;
4262 $jfh = fopen($destination, 'w') or die("can't open file");
4263 fwrite($jfh, $httpRawPostData);
4265 CRM_Utils_System
::civiExit();
4270 * Apply common settings to entityRef fields.
4272 * @param array $field
4273 * @param string $table
4275 private function setEntityRefDefaults(&$field, $table) {
4276 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4277 $field['attributes'] +
= array(
4278 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4280 'placeholder' => ts('- select -'),