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.
946 * @param bool $isForce
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
1208 foreach ($this->_options
as $fieldName => $field) {
1211 if ($field['type'] == 'select') {
1212 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1214 elseif ($field['type'] == 'checkbox') {
1215 $options[$field['title']] = $fieldName;
1216 $this->addCheckBox($fieldName, NULL,
1218 NULL, NULL, NULL, $this->_fourColumnAttribute
1223 if (!empty($this->_options
)) {
1224 $this->tabs
['ReportOptions'] = array(
1225 'title' => ts('Display Options'),
1226 'tpl' => 'ReportOptions',
1227 'div_label' => 'other-options',
1230 $this->assign('otherOptions', $this->_options
);
1234 * Add chart options to the report.
1236 public function addChartOptions() {
1237 if (!empty($this->_charts
)) {
1238 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1239 $this->assign('charts', $this->_charts
);
1240 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1245 * Add group by options to the report.
1247 public function addGroupBys() {
1248 $options = $freqElements = array();
1250 foreach ($this->_columns
as $tableName => $table) {
1251 if (array_key_exists('group_bys', $table)) {
1252 foreach ($table['group_bys'] as $fieldName => $field) {
1253 if (!empty($field)) {
1254 $options[$field['title']] = $fieldName;
1255 if (!empty($field['frequency'])) {
1256 $freqElements[$field['title']] = $fieldName;
1262 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1263 NULL, NULL, NULL, $this->_fourColumnAttribute
1265 $this->assign('groupByElements', $options);
1266 if (!empty($options)) {
1267 $this->tabs
['GroupBy'] = array(
1268 'title' => ts('Grouping'),
1270 'div_label' => 'group-by-elements',
1274 foreach ($freqElements as $name) {
1275 $this->addElement('select', "group_bys_freq[$name]",
1276 ts('Frequency'), $this->_groupByDateFreq
1282 * Add data for order by tab.
1284 public function addOrderBys() {
1286 foreach ($this->_columns
as $tableName => $table) {
1288 // Report developer may define any column to order by; include these as order-by options.
1289 if (array_key_exists('order_bys', $table)) {
1290 foreach ($table['order_bys'] as $fieldName => $field) {
1291 if (!empty($field)) {
1292 $options[$fieldName] = $field['title'];
1297 // Add searchable custom fields as order-by options, if so requested
1298 // (These are already indexed, so allowing to order on them is cheap.)
1300 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1301 array_key_exists('extends', $table) && !empty($table['extends'])
1303 foreach ($table['fields'] as $fieldName => $field) {
1304 if (empty($field['no_display'])) {
1305 $options[$fieldName] = $field['title'];
1313 $this->assign('orderByOptions', $options);
1314 if (!empty($options)) {
1315 $this->tabs
['OrderBy'] = array(
1316 'title' => ts('Sorting'),
1318 'div_label' => 'order-by-elements',
1322 if (!empty($options)) {
1324 '-' => ' - none - ',
1326 for ($i = 1; $i <= 5; $i++
) {
1327 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1328 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1329 'ASC' => 'Ascending',
1330 'DESC' => 'Descending',
1332 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1333 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1339 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1341 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1342 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1345 public function buildInstanceAndButtons() {
1346 CRM_Report_Form_Instance
::buildForm($this);
1348 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1350 $this->addElement('submit', $this->_instanceButtonName
, $label);
1351 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1352 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1355 $this->addElement('submit', $this->_createNewButtonName
,
1356 ts('Save a Copy') . '...');
1358 $this->assign('instanceForm', $this->_instanceForm
);
1360 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1361 $this->addElement('submit', $this->_printButtonName
, $label);
1363 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1364 $this->addElement('submit', $this->_pdfButtonName
, $label);
1366 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1368 if ($this->_csvSupported
) {
1369 $this->addElement('submit', $this->_csvButtonName
, $label);
1372 if (CRM_Core_Permission
::check('administer Reports') &&
1373 $this->_add2groupSupported
1375 $this->addElement('select', 'groups', ts('Group'),
1376 array('' => ts('Add Contacts to Group')) +
1377 CRM_Core_PseudoConstant
::nestedGroup(),
1378 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1380 $this->assign('group', TRUE);
1383 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1385 $this->addChartOptions();
1386 $this->addButtons(array(
1389 'name' => ts('Preview Report'),
1390 'isDefault' => TRUE,
1397 * Main build form function.
1399 public function buildQuickForm() {
1400 $this->addColumns();
1402 $this->addFilters();
1404 $this->addOptions();
1406 $this->addGroupBys();
1408 $this->addOrderBys();
1410 $this->buildInstanceAndButtons();
1412 // Add form rule for report.
1413 if (is_callable(array(
1417 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1419 $this->assignTabs();
1423 * A form rule function for custom data.
1425 * The rule ensures that fields selected in group_by if any) should only be the ones
1426 * present in display/select fields criteria;
1427 * note: works if and only if any custom field selected in group_by.
1429 * @param array $fields
1430 * @param array $ignoreFields
1434 public function customDataFormRule($fields, $ignoreFields = array()) {
1436 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1437 !empty($fields['group_bys'])
1439 foreach ($this->_columns
as $tableName => $table) {
1440 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1441 substr($tableName, 0, 12) == 'custom_value') &&
1442 !empty($this->_columns
[$tableName]['fields'])
1444 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1445 if (array_key_exists($fieldName, $fields['group_bys']) &&
1446 !array_key_exists($fieldName, $fields['fields'])
1448 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1450 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1451 foreach ($fields['fields'] as $fld => $val) {
1452 if (!array_key_exists($fld, $fields['group_bys']) &&
1453 !in_array($fld, $ignoreFields)
1455 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1467 * Get operators to display on form.
1469 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1471 * @param string $type
1472 * @param string $fieldName
1476 public function getOperationPair($type = "string", $fieldName = NULL) {
1477 // FIXME: At some point we should move these key-val pairs
1478 // to option_group and option_value table.
1480 case CRM_Report_Form
::OP_INT
:
1481 case CRM_Report_Form
::OP_FLOAT
:
1484 'lte' => ts('Is less than or equal to'),
1485 'gte' => ts('Is greater than or equal to'),
1486 'bw' => ts('Is between'),
1487 'eq' => ts('Is equal to'),
1488 'lt' => ts('Is less than'),
1489 'gt' => ts('Is greater than'),
1490 'neq' => ts('Is not equal to'),
1491 'nbw' => ts('Is not between'),
1492 'nll' => ts('Is empty (Null)'),
1493 'nnll' => ts('Is not empty (Null)'),
1497 case CRM_Report_Form
::OP_SELECT
:
1499 'eq' => ts('Is equal to'),
1503 case CRM_Report_Form
::OP_MONTH
:
1504 case CRM_Report_Form
::OP_MULTISELECT
:
1505 case CRM_Report_Form
::OP_ENTITYREF
:
1508 'in' => ts('Is one of'),
1509 'notin' => ts('Is not one of'),
1513 case CRM_Report_Form
::OP_DATE
:
1516 'nll' => ts('Is empty (Null)'),
1517 'nnll' => ts('Is not empty (Null)'),
1521 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1522 // use this operator for the values, concatenated with separator. For e.g if
1523 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1525 'mhas' => ts('Is one of'),
1526 'mnot' => ts('Is not one of'),
1533 'has' => ts('Contains'),
1534 'sw' => ts('Starts with'),
1535 'ew' => ts('Ends with'),
1536 'nhas' => ts('Does not contain'),
1537 'eq' => ts('Is equal to'),
1538 'neq' => ts('Is not equal to'),
1539 'nll' => ts('Is empty (Null)'),
1540 'nnll' => ts('Is not empty (Null)'),
1547 * Build the tag filter field to display on the filters tab.
1549 public function buildTagFilter() {
1550 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1551 if (!empty($contactTags)) {
1552 $this->_columns
['civicrm_tag'] = array(
1553 'dao' => 'CRM_Core_DAO_Tag',
1557 'title' => ts('Tag'),
1559 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1560 'options' => $contactTags,
1568 * Adds group filters to _columns (called from _Construct).
1570 public function buildGroupFilter() {
1571 $this->_columns
['civicrm_group']['filters'] = array(
1573 'name' => 'group_id',
1574 'title' => ts('Group'),
1575 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1577 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1580 if (empty($this->_columns
['civicrm_group']['dao'])) {
1581 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1583 if (empty($this->_columns
['civicrm_group']['alias'])) {
1584 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1589 * Get SQL operator from form text version.
1591 * @param string $operator
1595 public function getSQLOperator($operator = "like") {
1596 switch ($operator) {
1629 return 'IS NOT NULL';
1638 * Generate where clause.
1640 * This can be overridden in reports for special treatment of a field
1642 * @param array $field Field specifications
1643 * @param string $op Query operator (not an exact match to sql)
1644 * @param mixed $value
1648 * @return null|string
1650 public function whereClause(&$field, $op, $value, $min, $max) {
1652 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1658 if (($min !== NULL && strlen($min) > 0) ||
1659 ($max !== NULL && strlen($max) > 0)
1661 $min = CRM_Utils_Type
::escape($min, $type);
1662 $max = CRM_Utils_Type
::escape($max, $type);
1666 $clauses[] = "( {$field['dbAlias']} >= $min )";
1669 $clauses[] = "( {$field['dbAlias']} < $min )";
1674 $clauses[] = "( {$field['dbAlias']} <= $max )";
1677 $clauses[] = "( {$field['dbAlias']} > $max )";
1681 if (!empty($clauses)) {
1683 $clause = implode(' AND ', $clauses);
1686 $clause = implode(' OR ', $clauses);
1694 if ($value !== NULL && strlen($value) > 0) {
1695 $value = CRM_Utils_Type
::escape($value, $type);
1696 if (strpos($value, '%') === FALSE) {
1697 $value = "'%{$value}%'";
1700 $value = "'{$value}'";
1702 $sqlOP = $this->getSQLOperator($op);
1703 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1709 if (is_string($value) && strlen($value)) {
1710 $value = explode(',', $value);
1712 if ($value !== NULL && is_array($value) && count($value) > 0) {
1713 $sqlOP = $this->getSQLOperator($op);
1714 if (CRM_Utils_Array
::value('type', $field) ==
1715 CRM_Utils_Type
::T_STRING
1717 //cycle through selections and escape values
1718 foreach ($value as $key => $selection) {
1719 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1722 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1726 // for numerical values
1727 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1730 if ($op == 'notin') {
1731 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1734 $clause = "( " . $clause . " )";
1741 // mhas == multiple has
1742 if ($value !== NULL && count($value) > 0) {
1743 $sqlOP = $this->getSQLOperator($op);
1745 if ($op == 'mnot') {
1746 // mnot == multiple is not one of
1749 $regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', (array) $value) . "[[:cntrl:]]*";
1750 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1756 if ($value !== NULL && strlen($value) > 0) {
1757 $value = CRM_Utils_Type
::escape($value, $type);
1758 if (strpos($value, '%') === FALSE) {
1760 $value = "'{$value}%'";
1763 $value = "'%{$value}'";
1767 $value = "'{$value}'";
1769 $sqlOP = $this->getSQLOperator($op);
1770 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1776 $sqlOP = $this->getSQLOperator($op);
1777 $clause = "( {$field['dbAlias']} $sqlOP )";
1781 if ($value !== NULL && strlen($value) > 0) {
1782 if (isset($field['clause'])) {
1783 // FIXME: we not doing escape here. Better solution is to use two
1784 // different types - data-type and filter-type
1785 $clause = $field['clause'];
1788 $value = CRM_Utils_Type
::escape($value, $type);
1789 $sqlOP = $this->getSQLOperator($op);
1790 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1791 $value = "'{$value}'";
1793 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1799 if (!empty($field['group']) && $clause) {
1800 $clause = $this->whereGroupClause($field, $value, $op);
1802 elseif (!empty($field['tag']) && $clause) {
1803 // not using left join in query because if any contact
1804 // belongs to more than one tag, results duplicate
1806 $clause = $this->whereTagClause($field, $value, $op);
1808 elseif (!empty($field['membership_org']) && $clause) {
1809 $clause = $this->whereMembershipOrgClause($value, $op);
1811 elseif (!empty($field['membership_type']) && $clause) {
1812 $clause = $this->whereMembershipTypeClause($value, $op);
1818 * Get SQL where clause for a date field.
1820 * @param string $fieldName
1821 * @param string $relative
1822 * @param string $from
1824 * @param string $type
1825 * @param string $fromTime
1826 * @param string $toTime
1828 * @return null|string
1830 public function dateClause(
1832 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1835 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1836 $sqlOP = $this->getSQLOperator($relative);
1837 return "( {$fieldName} {$sqlOP} )";
1840 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1843 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1844 $clauses[] = "( {$fieldName} >= $from )";
1848 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1849 $clauses[] = "( {$fieldName} <= {$to} )";
1852 if (!empty($clauses)) {
1853 return implode(' AND ', $clauses);
1860 * Possibly unused function.
1862 * @todo - could not find any instances where this is called
1864 * @param bool $relative
1865 * @param string $from
1868 * @return string|NULL
1870 public function dateDisplay($relative, $from, $to) {
1871 list($from, $to) = $this->getFromTo($relative, $from, $to);
1874 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1877 $clauses[] = 'Past';
1881 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1884 $clauses[] = 'Today';
1887 if (!empty($clauses)) {
1888 return implode(' - ', $clauses);
1895 * Get values for from and to for date ranges.
1897 * @param bool $relative
1898 * @param string $from
1900 * @param string $fromTime
1901 * @param string $toTime
1905 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1906 if (empty($toTime)) {
1909 //FIX ME not working for relative
1911 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1912 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1913 $from = substr($dateRange['from'], 0, 8);
1914 //Take only Date Part, Sometime Time part is also present in 'to'
1915 $to = substr($dateRange['to'], 0, 8);
1917 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1918 $to = CRM_Utils_Date
::processDate($to, $toTime);
1919 return array($from, $to);
1923 * Alter display of rows.
1925 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1926 * such as rendering contacts as links.
1928 * @param array $rows
1929 * Rows generated by SQL, with an array for each row.
1931 public function alterDisplay(&$rows) {
1935 * Alter the way in which custom data fields are displayed.
1937 * @param array $rows
1939 public function alterCustomDataDisplay(&$rows) {
1940 // custom code to alter rows having custom values
1941 if (empty($this->_customGroupExtends
)) {
1945 $customFieldIds = array();
1946 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1947 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1948 $customFieldIds[$fieldAlias] = $fieldId;
1951 if (empty($customFieldIds)) {
1955 $customFields = $fieldValueMap = array();
1956 $customFieldCols = array(
1964 // skip for type date and ContactReference since date format is already handled
1966 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1967 FROM civicrm_custom_field cf
1968 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1969 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1970 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1971 cg.is_active = 1 AND
1972 cf.is_active = 1 AND
1973 cf.is_searchable = 1 AND
1974 cf.data_type NOT IN ('ContactReference', 'Date') AND
1975 cf.id IN (" . implode(",", $customFieldIds) . ")";
1977 $dao = CRM_Core_DAO
::executeQuery($query);
1978 while ($dao->fetch()) {
1979 foreach ($customFieldCols as $key) {
1980 $customFields[$dao->table_name
. '_custom_' .
1981 $dao->id
][$key] = $dao->$key;
1983 if ($dao->option_group_id
) {
1984 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1989 $entryFound = FALSE;
1990 foreach ($rows as $rowNum => $row) {
1991 foreach ($row as $tableCol => $val) {
1992 if (array_key_exists($tableCol, $customFields)) {
1993 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1998 // skip looking further in rows, if first row itself doesn't
1999 // have the column we need
2007 * Format custom values.
2009 * @param mixed $value
2010 * @param array $customField
2011 * @param array $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);
2129 * Remove duplicate rows.
2131 * @param array $rows
2133 public function removeDuplicates(&$rows) {
2134 if (empty($this->_noRepeats
)) {
2137 $checkList = array();
2139 foreach ($rows as $key => $list) {
2140 foreach ($list as $colName => $colVal) {
2141 if (array_key_exists($colName, $checkList) &&
2142 $checkList[$colName] == $colVal
2144 $rows[$key][$colName] = "";
2146 if (in_array($colName, $this->_noRepeats
)) {
2147 $checkList[$colName] = $colVal;
2154 * Fix subtotal display.
2157 * @param array $fields
2158 * @param bool $subtotal
2160 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2161 foreach ($row as $colName => $colVal) {
2162 if (in_array($colName, $fields)) {
2164 elseif (isset($this->_columnHeaders
[$colName])) {
2166 $row[$colName] = "Subtotal";
2170 unset($row[$colName]);
2177 * Calculate grant total.
2179 * @param array $rows
2183 public function grandTotal(&$rows) {
2184 if (!$this->_rollup ||
($this->_rollup
== '') ||
2185 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2189 $lastRow = array_pop($rows);
2191 foreach ($this->_columnHeaders
as $fld => $val) {
2192 if (!in_array($fld, $this->_statFields
)) {
2193 if (!$this->_grandFlag
) {
2194 $lastRow[$fld] = "Grand Total";
2195 $this->_grandFlag
= TRUE;
2198 $lastRow[$fld] = "";
2203 $this->assign('grandStat', $lastRow);
2208 * Format display output.
2210 * @param array $rows
2211 * @param bool $pager
2213 public function formatDisplay(&$rows, $pager = TRUE) {
2214 // set pager based on if any limit was applied in the query.
2219 // allow building charts if any
2220 if (!empty($this->_params
['charts']) && !empty($rows)) {
2221 $this->buildChart($rows);
2222 $this->assign('chartEnabled', TRUE);
2223 $this->_chartId
= "{$this->_params['charts']}_" .
2224 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2226 $this->assign('chartId', $this->_chartId
);
2229 // unset columns not to be displayed.
2230 foreach ($this->_columnHeaders
as $key => $value) {
2231 if (!empty($value['no_display'])) {
2232 unset($this->_columnHeaders
[$key]);
2236 // unset columns not to be displayed.
2237 if (!empty($rows)) {
2238 foreach ($this->_noDisplay
as $noDisplayField) {
2239 foreach ($rows as $rowNum => $row) {
2240 unset($this->_columnHeaders
[$noDisplayField]);
2245 // build array of section totals
2246 $this->sectionTotals();
2248 // process grand-total row
2249 $this->grandTotal($rows);
2251 // use this method for formatting rows for display purpose.
2252 $this->alterDisplay($rows);
2253 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2255 // use this method for formatting custom rows for display purpose.
2256 $this->alterCustomDataDisplay($rows);
2262 * @param array $rows
2264 public function buildChart(&$rows) {
2265 // override this method for building charts.
2268 // select() method below has been added recently (v3.3), and many of the report templates might
2269 // still be having their own select() method. We should fix them as and when encountered and move
2270 // towards generalizing the select() method below.
2273 * Generate the SELECT clause and set class variable $_select.
2275 public function select() {
2276 $select = $this->_selectAliases
= array();
2278 foreach ($this->_columns
as $tableName => $table) {
2279 if (array_key_exists('fields', $table)) {
2280 foreach ($table['fields'] as $fieldName => $field) {
2281 if ($tableName == 'civicrm_address') {
2282 $this->_addressField
= TRUE;
2284 if ($tableName == 'civicrm_email') {
2285 $this->_emailField
= TRUE;
2287 if ($tableName == 'civicrm_phone') {
2288 $this->_phoneField
= TRUE;
2291 if (!empty($field['required']) ||
2292 !empty($this->_params
['fields'][$fieldName])
2295 // 1. In many cases we want select clause to be built in slightly different way
2296 // for a particular field of a particular type.
2297 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2299 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2300 if ($selectClause) {
2301 $select[] = $selectClause;
2305 // include statistics columns only if set
2306 if (!empty($field['statistics'])) {
2307 foreach ($field['statistics'] as $stat => $label) {
2308 $alias = "{$tableName}_{$fieldName}_{$stat}";
2309 switch (strtolower($stat)) {
2312 $select[] = "$stat({$field['dbAlias']}) as $alias";
2313 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2314 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2315 $this->_statFields
[$label] = $alias;
2316 $this->_selectAliases
[] = $alias;
2320 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2321 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2322 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2323 $this->_statFields
[$label] = $alias;
2324 $this->_selectAliases
[] = $alias;
2327 case 'count_distinct':
2328 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2329 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2330 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2331 $this->_statFields
[$label] = $alias;
2332 $this->_selectAliases
[] = $alias;
2336 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2337 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2338 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2339 $this->_statFields
[$label] = $alias;
2340 $this->_selectAliases
[] = $alias;
2346 $alias = "{$tableName}_{$fieldName}";
2347 $select[] = "{$field['dbAlias']} as $alias";
2348 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2349 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2350 $this->_selectAliases
[] = $alias;
2356 // select for group bys
2357 if (array_key_exists('group_bys', $table)) {
2358 foreach ($table['group_bys'] as $fieldName => $field) {
2360 if ($tableName == 'civicrm_address') {
2361 $this->_addressField
= TRUE;
2363 if ($tableName == 'civicrm_email') {
2364 $this->_emailField
= TRUE;
2366 if ($tableName == 'civicrm_phone') {
2367 $this->_phoneField
= TRUE;
2369 // 1. In many cases we want select clause to be built in slightly different way
2370 // for a particular field of a particular type.
2371 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2373 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2374 if ($selectClause) {
2375 $select[] = $selectClause;
2379 if (!empty($this->_params
['group_bys']) &&
2380 !empty($this->_params
['group_bys'][$fieldName]) &&
2381 !empty($this->_params
['group_bys_freq'])
2383 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2385 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2386 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2387 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2388 $field['title'] = 'Week';
2392 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2393 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2394 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2395 $field['title'] = 'Year';
2399 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2400 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2401 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2402 $field['title'] = 'Month';
2406 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2407 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2408 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2409 $field['title'] = 'Quarter';
2412 // for graphs and charts -
2413 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2414 $this->_interval
= $field['title'];
2415 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2416 = $field['title'] . ' Beginning';
2417 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2418 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2420 // just to make sure these values are transferred to rows.
2421 // since we 'll need them for calculation purpose,
2422 // e.g making subtotals look nicer or graphs
2423 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2424 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2431 $this->_selectClauses
= $select;
2432 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2436 * Build select clause for a single field.
2438 * @param string $tableName
2439 * @param string $tableKey
2440 * @param string $fieldName
2441 * @param string $field
2445 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2450 * Build where clause.
2452 public function where() {
2453 $this->storeWhereHavingClauseArray();
2455 if (empty($this->_whereClauses
)) {
2456 $this->_where
= "WHERE ( 1 ) ";
2457 $this->_having
= "";
2460 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2463 if ($this->_aclWhere
) {
2464 $this->_where
.= " AND {$this->_aclWhere} ";
2467 if (!empty($this->_havingClauses
)) {
2468 // use this clause to construct group by clause.
2469 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2474 * Store Where clauses into an array.
2476 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2477 * temp table that may not be part of the final where clause or added
2478 * in other functions
2480 public function storeWhereHavingClauseArray() {
2481 foreach ($this->_columns
as $tableName => $table) {
2482 if (array_key_exists('filters', $table)) {
2483 foreach ($table['filters'] as $fieldName => $field) {
2484 // respect pseudofield to filter spec so fields can be marked as
2485 // not to be handled here
2486 if (!empty($field['pseudofield'])) {
2490 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2491 if (CRM_Utils_Array
::value('operatorType', $field) ==
2492 CRM_Report_Form
::OP_MONTH
2494 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2495 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2496 if (is_array($value) && !empty($value)) {
2498 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2503 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2504 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2505 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2506 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2507 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2508 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2512 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2514 $clause = $this->whereClause($field,
2516 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2517 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2518 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2523 if (!empty($clause)) {
2524 if (!empty($field['having'])) {
2525 $this->_havingClauses
[] = $clause;
2528 $this->_whereClauses
[] = $clause;
2540 public function processReportMode() {
2541 $buttonName = $this->controller
->getButtonName();
2543 $output = CRM_Utils_Request
::retrieve(
2546 CRM_Core_DAO
::$_nullObject
2550 = CRM_Utils_Request
::retrieve(
2553 CRM_Core_DAO
::$_nullObject
2556 $this->_absoluteUrl
= FALSE;
2558 $this->assign('printOnly', FALSE);
2560 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2561 ($this->_sendmail
&& !$output)
2563 $this->assign('printOnly', TRUE);
2565 $this->assign('outputMode', 'print');
2566 $this->_outputMode
= 'print';
2567 if ($this->_sendmail
) {
2568 $this->_absoluteUrl
= TRUE;
2571 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2572 $this->assign('printOnly', TRUE);
2574 $this->assign('outputMode', 'pdf');
2575 $this->_outputMode
= 'pdf';
2576 $this->_absoluteUrl
= TRUE;
2578 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2579 $this->assign('printOnly', TRUE);
2581 $this->assign('outputMode', 'csv');
2582 $this->_outputMode
= 'csv';
2583 $this->_absoluteUrl
= TRUE;
2585 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2586 $this->assign('outputMode', 'group');
2587 $this->_outputMode
= 'group';
2589 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2590 $this->assign('outputMode', 'create_report');
2591 $this->_outputMode
= 'create_report';
2594 $this->assign('outputMode', 'html');
2595 $this->_outputMode
= 'html';
2598 // Get today's date to include in printed reports
2600 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2601 $this->assign('reportDate', $reportDate);
2606 * Post Processing function for Form.
2608 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2610 public function beginPostProcess() {
2611 $this->setParams($this->controller
->exportValues($this->_name
));
2613 if (empty($this->_params
) &&
2616 $this->setParams($this->_formValues
);
2619 // hack to fix params when submitted from dashboard, CRM-8532
2620 // fields array is missing because form building etc is skipped
2621 // in dashboard mode for report
2622 //@todo - this could be done in the dashboard no we have a setter
2623 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2624 $this->setParams($this->_formValues
);
2627 $this->_formValues
= $this->_params
;
2628 if (CRM_Core_Permission
::check('administer Reports') &&
2629 isset($this->_id
) &&
2630 ($this->_instanceButtonName
==
2631 $this->controller
->getButtonName() . '_save' ||
2632 $this->_chartButtonName
== $this->controller
->getButtonName()
2635 $this->assign('updateReportButton', TRUE);
2637 $this->processReportMode();
2638 $this->beginPostProcessCommon();
2642 * BeginPostProcess function run in both report mode and non-report mode (api).
2644 public function beginPostProcessCommon() {}
2647 * Build the report query.
2649 * @param bool $applyLimit
2653 public function buildQuery($applyLimit = TRUE) {
2656 $this->customDataFrom();
2661 // order_by columns not selected for display need to be included in SELECT
2662 $unselectedSectionColumns = $this->unselectedSectionColumns();
2663 foreach ($unselectedSectionColumns as $alias => $section) {
2664 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2667 if ($applyLimit && empty($this->_params
['charts'])) {
2670 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2672 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2677 * Build group by clause.
2679 public function groupBy() {
2680 $groupBys = array();
2681 if (!empty($this->_params
['group_bys']) &&
2682 is_array($this->_params
['group_bys'])
2684 foreach ($this->_columns
as $tableName => $table) {
2685 if (array_key_exists('group_bys', $table)) {
2686 foreach ($table['group_bys'] as $fieldName => $field) {
2687 if (!empty($this->_params
['group_bys'][$fieldName])) {
2688 $groupBys[] = $field['dbAlias'];
2695 if (!empty($groupBys)) {
2696 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2701 * Build order by clause.
2703 public function orderBy() {
2704 $this->_orderBy
= "";
2705 $this->_sections
= array();
2706 $this->storeOrderByArray();
2707 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2708 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2710 $this->assign('sections', $this->_sections
);
2714 * Extract order by fields and store as an array.
2716 * In some cases other functions want to know which fields are selected for ordering by
2717 * Separating this into a separate function allows it to be called separately from constructing
2718 * the order by clause
2720 public function storeOrderByArray() {
2721 $orderBys = array();
2723 if (!empty($this->_params
['order_bys']) &&
2724 is_array($this->_params
['order_bys']) &&
2725 !empty($this->_params
['order_bys'])
2728 // Process order_bys in user-specified order
2729 foreach ($this->_params
['order_bys'] as $orderBy) {
2730 $orderByField = array();
2731 foreach ($this->_columns
as $tableName => $table) {
2732 if (array_key_exists('order_bys', $table)) {
2733 // For DAO columns defined in $this->_columns
2734 $fields = $table['order_bys'];
2736 elseif (array_key_exists('extends', $table)) {
2737 // For custom fields referenced in $this->_customGroupExtends
2738 $fields = CRM_Utils_Array
::value('fields', $table, array());
2743 if (!empty($fields) && is_array($fields)) {
2744 foreach ($fields as $fieldName => $field) {
2745 if ($fieldName == $orderBy['column']) {
2746 $orderByField = array_merge($field, $orderBy);
2747 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2754 if (!empty($orderByField)) {
2755 $this->_orderByFields
[] = $orderByField;
2756 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2758 // Record any section headers for assignment to the template
2759 if (!empty($orderBy['section'])) {
2760 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2761 $this->_sections
[$orderByField['tplField']] = $orderByField;
2767 $this->_orderByArray
= $orderBys;
2769 $this->assign('sections', $this->_sections
);
2773 * Determine unselected columns.
2777 public function unselectedSectionColumns() {
2778 $selectColumns = array();
2779 foreach ($this->_columns
as $tableName => $table) {
2780 if (array_key_exists('fields', $table)) {
2781 foreach ($table['fields'] as $fieldName => $field) {
2782 if (!empty($field['required']) ||
2783 !empty($this->_params
['fields'][$fieldName])
2786 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2792 if (is_array($this->_sections
)) {
2793 return array_diff_key($this->_sections
, $selectColumns);
2801 * Build output rows.
2803 * @param string $sql
2804 * @param array $rows
2806 public function buildRows($sql, &$rows) {
2807 $dao = CRM_Core_DAO
::executeQuery($sql);
2808 if (!is_array($rows)) {
2812 // use this method to modify $this->_columnHeaders
2813 $this->modifyColumnHeaders();
2815 $unselectedSectionColumns = $this->unselectedSectionColumns();
2817 while ($dao->fetch()) {
2819 foreach ($this->_columnHeaders
as $key => $value) {
2820 if (property_exists($dao, $key)) {
2821 $row[$key] = $dao->$key;
2825 // section headers not selected for display need to be added to row
2826 foreach ($unselectedSectionColumns as $key => $values) {
2827 if (property_exists($dao, $key)) {
2828 $row[$key] = $dao->$key;
2837 * Calculate section totals.
2839 * When "order by" fields are marked as sections, this assigns to the template
2840 * an array of total counts for each section. This data is used by the Smarty
2841 * plugin {sectionTotal}.
2843 public function sectionTotals() {
2845 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2846 if (empty($this->_selectAliases
)) {
2850 if (!empty($this->_sections
)) {
2851 // build the query with no LIMIT clause
2852 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2853 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2855 // pull section aliases out of $this->_sections
2856 $sectionAliases = array_keys($this->_sections
);
2859 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2860 $ifnulls[] = "ifnull($alias, '') as $alias";
2863 // Group (un-limited) report by all aliases and get counts. This might
2864 // be done more efficiently when the contents of $sql are known, ie. by
2865 // overriding this method in the report class.
2867 $query = "select " . implode(", ", $ifnulls) .
2868 ", count(*) as ct from ($sql) as subquery group by " .
2869 implode(", ", $sectionAliases);
2871 // initialize array of total counts
2873 $dao = CRM_Core_DAO
::executeQuery($query);
2874 while ($dao->fetch()) {
2876 // let $this->_alterDisplay translate any integer ids to human-readable values.
2877 $rows[0] = $dao->toArray();
2878 $this->alterDisplay($rows);
2881 // add totals for all permutations of section values
2884 $aliasCount = count($sectionAliases);
2885 foreach ($sectionAliases as $alias) {
2886 $values[] = $row[$alias];
2887 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2888 if ($i == $aliasCount) {
2889 // the last alias is the lowest-level section header; use count as-is
2890 $totals[$key] = $dao->ct
;
2893 // other aliases are higher level; roll count into their total
2894 $totals[$key] +
= $dao->ct
;
2898 $this->assign('sectionTotals', $totals);
2903 * Modify column headers.
2905 public function modifyColumnHeaders() {
2906 // use this method to modify $this->_columnHeaders
2910 * Assign rows to the template.
2912 * @param array $rows
2914 public function doTemplateAssignment(&$rows) {
2915 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2916 $this->assign_by_ref('rows', $rows);
2917 $this->assign('statistics', $this->statistics($rows));
2921 * Build report statistics.
2923 * Override this method to build your own statistics.
2925 * @param array $rows
2929 public function statistics(&$rows) {
2930 $statistics = array();
2932 $count = count($rows);
2934 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2938 $this->countStat($statistics, $count);
2940 $this->groupByStat($statistics);
2942 $this->filterStat($statistics);
2948 * Add count statistics.
2950 * @param array $statistics
2953 public function countStat(&$statistics, $count) {
2954 $statistics['counts']['rowCount'] = array(
2955 'title' => ts('Row(s) Listed'),
2959 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2960 $statistics['counts']['rowsFound'] = array(
2961 'title' => ts('Total Row(s)'),
2962 'value' => $this->_rowsFound
,
2968 * Add group by statistics.
2970 * @param array $statistics
2972 public function groupByStat(&$statistics) {
2973 if (!empty($this->_params
['group_bys']) &&
2974 is_array($this->_params
['group_bys']) &&
2975 !empty($this->_params
['group_bys'])
2977 foreach ($this->_columns
as $tableName => $table) {
2978 if (array_key_exists('group_bys', $table)) {
2979 foreach ($table['group_bys'] as $fieldName => $field) {
2980 if (!empty($this->_params
['group_bys'][$fieldName])) {
2981 $combinations[] = $field['title'];
2986 $statistics['groups'][] = array(
2987 'title' => ts('Grouping(s)'),
2988 'value' => implode(' & ', $combinations),
2994 * Filter statistics.
2996 * @param array $statistics
2998 public function filterStat(&$statistics) {
2999 foreach ($this->_columns
as $tableName => $table) {
3000 if (array_key_exists('filters', $table)) {
3001 foreach ($table['filters'] as $fieldName => $field) {
3002 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
3003 CRM_Utils_Array
::value('operatorType', $field) !=
3004 CRM_Report_Form
::OP_MONTH
3008 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3009 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3010 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3011 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3012 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3014 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3015 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3017 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3018 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3021 $statistics['filters'][] = array(
3022 'title' => $field['title'],
3023 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3026 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3027 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3029 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3030 $statistics['filters'][] = array(
3031 'title' => $field['title'],
3032 'value' => $pair[$rel],
3037 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3040 $pair = $this->getOperationPair(
3041 CRM_Utils_Array
::value('operatorType', $field),
3044 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3045 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3046 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3047 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3048 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3050 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3051 $this->setEntityRefDefaults($field, $tableName);
3052 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3053 array('id' => $val) +
3054 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3056 foreach ($result['values'] as $v) {
3057 $values[] = $v['label'];
3059 $value = "{$pair[$op]} " . implode(', ', $values);
3061 elseif ($op == 'nll' ||
$op == 'nnll') {
3062 $value = $pair[$op];
3064 elseif (is_array($val) && (!empty($val))) {
3065 $options = CRM_Utils_Array
::value('options', $field, array());
3066 foreach ($val as $key => $valIds) {
3067 if (isset($options[$valIds])) {
3068 $val[$key] = $options[$valIds];
3071 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3072 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3073 $val = implode(', ', $val);
3074 $value = "{$pair[$op]} " . $val;
3076 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3077 isset($field['options']) &&
3078 is_array($field['options']) && !empty($field['options'])
3080 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3081 CRM_Utils_Array
::value($val, $field['options'], $val);
3084 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3088 $statistics['filters'][] = array(
3089 'title' => CRM_Utils_Array
::value('title', $field),
3100 * End post processing.
3102 * @param array|null $rows
3104 public function endPostProcess(&$rows = NULL) {
3105 if ($this->_storeResultSet
) {
3106 $this->_resultSet
= $rows;
3109 if ($this->_outputMode
== 'print' ||
3110 $this->_outputMode
== 'pdf' ||
3114 $content = $this->compileContent();
3115 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3119 if ($this->_sendmail
) {
3120 $config = CRM_Core_Config
::singleton();
3121 $attachments = array();
3123 if ($this->_outputMode
== 'csv') {
3125 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3126 ": {$url}</p>" . '<p>' .
3127 ts('The report is attached as a CSV file.') . '</p>' .
3128 $this->_formValues
['report_footer'];
3130 $csvFullFilename = $config->templateCompileDir
.
3131 CRM_Utils_File
::makeFileName('CiviReport.csv');
3132 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3133 file_put_contents($csvFullFilename, $csvContent);
3134 $attachments[] = array(
3135 'fullPath' => $csvFullFilename,
3136 'mime_type' => 'text/csv',
3137 'cleanName' => 'CiviReport.csv',
3140 if ($this->_outputMode
== 'pdf') {
3141 // generate PDF content
3142 $pdfFullFilename = $config->templateCompileDir
.
3143 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3144 file_put_contents($pdfFullFilename,
3145 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3146 TRUE, array('orientation' => 'landscape')
3149 // generate Email Content
3151 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3152 ": {$url}</p>" . '<p>' .
3153 ts('The report is attached as a PDF file.') . '</p>' .
3154 $this->_formValues
['report_footer'];
3156 $attachments[] = array(
3157 'fullPath' => $pdfFullFilename,
3158 'mime_type' => 'application/pdf',
3159 'cleanName' => 'CiviReport.pdf',
3163 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3164 $this->_outputMode
, $attachments
3167 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3170 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3174 elseif ($this->_outputMode
== 'print') {
3178 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3179 $config = CRM_Core_Config
::singleton();
3180 //get chart image name
3181 $chartImg = $this->_chartId
. '.png';
3182 //get image url path
3184 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3186 $uploadUrl .= $chartImg;
3187 //get image doc path to overwrite
3189 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3190 'openFlashChart/' . $chartImg;
3192 $chart = imagecreatefrompng($uploadUrl);
3193 //convert it into formatted png
3194 header('Content-type: image/png');
3195 //overwrite with same image
3196 imagepng($chart, $uploadImg);
3198 imagedestroy($chart);
3200 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3202 CRM_Utils_System
::civiExit();
3204 elseif ($this->_outputMode
== 'csv') {
3205 CRM_Report_Utils_Report
::export2csv($this, $rows);
3207 elseif ($this->_outputMode
== 'group') {
3208 $group = $this->_params
['groups'];
3209 $this->add2group($group);
3211 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3212 CRM_Report_Form_Instance
::postProcess($this);
3214 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3215 $this->_outputMode
== 'create_report'
3217 $this->_createNew
= TRUE;
3218 CRM_Report_Form_Instance
::postProcess($this);
3223 * Set store result set indicator to TRUE.
3225 * @todo explain what this does
3227 public function storeResultSet() {
3228 $this->_storeResultSet
= TRUE;
3236 public function getResultSet() {
3237 return $this->_resultSet
;
3241 * Use the form name to create the tpl file name.
3245 public function getTemplateFileName() {
3246 $defaultTpl = parent
::getTemplateFileName();
3247 $template = CRM_Core_Smarty
::singleton();
3248 if (!$template->template_exists($defaultTpl)) {
3249 $defaultTpl = 'CRM/Report/Form.tpl';
3255 * Compile the report content.
3257 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3261 public function compileContent() {
3262 $templateFile = $this->getHookedTemplateFileName();
3263 return $this->_formValues
['report_header'] .
3264 CRM_Core_Form
::$_template->fetch($templateFile) .
3265 $this->_formValues
['report_footer'];
3270 * Post process function.
3272 public function postProcess() {
3273 // get ready with post process params
3274 $this->beginPostProcess();
3277 $sql = $this->buildQuery();
3279 // build array of result based on column headers. This method also allows
3280 // modifying column headers before using it to build result set i.e $rows.
3282 $this->buildRows($sql, $rows);
3284 // format result set.
3285 $this->formatDisplay($rows);
3287 // assign variables to templates
3288 $this->doTemplateAssignment($rows);
3290 // do print / pdf / instance stuff if needed
3291 $this->endPostProcess($rows);
3297 * @param int $rowCount
3301 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3302 // lets do the pager if in html mode
3303 $this->_limit
= NULL;
3305 // CRM-14115, over-ride row count if rowCount is specified in URL
3306 if ($this->_dashBoardRowCount
) {
3307 $rowCount = $this->_dashBoardRowCount
;
3309 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3310 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3312 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3314 // @todo all http vars should be extracted in the preProcess
3315 // - not randomly in the class
3316 if (!$pageId && !empty($_POST)) {
3317 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3318 $pageId = max((int) $_POST['crmPID_B'], 1);
3320 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3321 $pageId = max((int) $_POST['crmPID'], 1);
3323 unset($_POST['crmPID_B'], $_POST['crmPID']);
3326 $pageId = $pageId ?
$pageId : 1;
3327 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3328 $offset = ($pageId - 1) * $rowCount;
3330 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3331 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3333 $this->_limit
= " LIMIT $offset, $rowCount";
3334 return array($offset, $rowCount);
3336 if ($this->_limitValue
) {
3337 if ($this->_offsetValue
) {
3338 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3341 $this->_limit
= " LIMIT " . $this->_limitValue
;
3349 * @param int $rowCount
3351 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3353 // CRM-14115, over-ride row count if rowCount is specified in URL
3354 if ($this->_dashBoardRowCount
) {
3355 $rowCount = $this->_dashBoardRowCount
;
3358 if ($this->_limit
&& ($this->_limit
!= '')) {
3359 $sql = "SELECT FOUND_ROWS();";
3360 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3362 'total' => $this->_rowsFound
,
3363 'rowCount' => $rowCount,
3364 'status' => ts('Records') . ' %%StatusMessage%%',
3365 'buttonBottom' => 'PagerBottomButton',
3366 'buttonTop' => 'PagerTopButton',
3367 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3370 $pager = new CRM_Utils_Pager($params);
3371 $this->assign_by_ref('pager', $pager);
3372 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3377 * Build where clause for groups.
3379 * @param string $field
3380 * @param mixed $value
3385 public function whereGroupClause($field, $value, $op) {
3387 $smartGroupQuery = "";
3389 $group = new CRM_Contact_DAO_Group();
3390 $group->is_active
= 1;
3392 $smartGroups = array();
3393 while ($group->fetch()) {
3394 if (in_array($group->id
, $this->_params
['gid_value']) &&
3395 $group->saved_search_id
3397 $smartGroups[] = $group->id
;
3401 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3403 $smartGroupQuery = '';
3404 if (!empty($smartGroups)) {
3405 $smartGroups = implode(',', $smartGroups);
3406 $smartGroupQuery = " UNION DISTINCT
3407 SELECT DISTINCT smartgroup_contact.contact_id
3408 FROM civicrm_group_contact_cache smartgroup_contact
3409 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3412 $sqlOp = $this->getSQLOperator($op);
3413 if (!is_array($value)) {
3414 $value = array($value);
3416 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3418 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3419 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3420 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3421 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3422 {$smartGroupQuery} ) ";
3426 * Build where clause for tags.
3428 * @param string $field
3429 * @param mixed $value
3434 public function whereTagClause($field, $value, $op) {
3435 // not using left join in query because if any contact
3436 // belongs to more than one tag, results duplicate
3438 $sqlOp = $this->getSQLOperator($op);
3439 if (!is_array($value)) {
3440 $value = array($value);
3442 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3443 $entity_table = $this->_tagFilterTable
;
3444 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3445 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3446 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3447 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3451 * Generate membership organization clause.
3453 * @param mixed $value
3454 * @param string $op SQL Operator
3458 public function whereMembershipOrgClause($value, $op) {
3459 $sqlOp = $this->getSQLOperator($op);
3460 if (!is_array($value)) {
3461 $value = array($value);
3464 $tmp_membership_org_sql_list = implode(', ', $value);
3465 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3466 SELECT DISTINCT mem.contact_id
3467 FROM civicrm_membership mem
3468 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3469 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3470 WHERE mt.member_of_contact_id IN (" .
3471 $tmp_membership_org_sql_list . ")
3472 AND mt.is_active = '1'
3473 AND mem_status.is_current_member = '1'
3474 AND mem_status.is_active = '1' ) ";
3478 * Generate Membership Type SQL Clause.
3480 * @param mixed $value
3486 public function whereMembershipTypeClause($value, $op) {
3487 $sqlOp = $this->getSQLOperator($op);
3488 if (!is_array($value)) {
3489 $value = array($value);
3492 $tmp_membership_sql_list = implode(', ', $value);
3493 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3494 SELECT DISTINCT mem.contact_id
3495 FROM civicrm_membership mem
3496 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3497 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3498 WHERE mem.membership_type_id IN (" .
3499 $tmp_membership_sql_list . ")
3500 AND mt.is_active = '1'
3501 AND mem_status.is_current_member = '1'
3502 AND mem_status.is_active = '1' ) ";
3506 * Build acl clauses.
3508 * @param string $tableAlias
3510 public function buildACLClause($tableAlias = 'contact_a') {
3511 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3515 * Add custom data to the columns.
3517 * @param bool $addFields
3518 * @param array $permCustomGroupIds
3520 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3521 if (empty($this->_customGroupExtends
)) {
3524 if (!is_array($this->_customGroupExtends
)) {
3525 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3527 $customGroupWhere = '';
3528 if (!empty($permCustomGroupIds)) {
3529 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3533 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3534 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3535 FROM civicrm_custom_group cg
3536 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3537 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3539 cg.is_active = 1 AND
3540 cf.is_active = 1 AND
3541 cf.is_searchable = 1
3542 ORDER BY cg.weight, cf.weight";
3543 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3546 while ($customDAO->fetch()) {
3547 if ($customDAO->table_name
!= $curTable) {
3548 $curTable = $customDAO->table_name
;
3549 $curFields = $curFilters = array();
3552 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3553 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3554 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3555 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3562 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3563 $this->_columns
[$curTable][$colKey] = array();
3567 $fieldName = 'custom_' . $customDAO->cf_id
;
3570 // this makes aliasing work in favor
3571 $curFields[$fieldName] = array(
3572 'name' => $customDAO->column_name
,
3573 'title' => $customDAO->label
,
3574 'dataType' => $customDAO->data_type
,
3575 'htmlType' => $customDAO->html_type
,
3578 if ($this->_customGroupFilters
) {
3579 // this makes aliasing work in favor
3580 $curFilters[$fieldName] = array(
3581 'name' => $customDAO->column_name
,
3582 'title' => $customDAO->label
,
3583 'dataType' => $customDAO->data_type
,
3584 'htmlType' => $customDAO->html_type
,
3588 switch ($customDAO->data_type
) {
3591 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3592 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3593 // CRM-6946, show time part for datetime date fields
3594 if ($customDAO->time_format
) {
3595 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3600 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3601 $curFilters[$fieldName]['options'] = array(
3602 '' => ts('- select -'),
3606 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3610 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3611 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3615 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3616 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3620 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3621 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3625 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3627 if (!empty($customDAO->option_group_id
)) {
3628 if (in_array($customDAO->html_type
, array(
3633 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3636 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3638 if ($this->_customGroupFilters
) {
3639 $curFilters[$fieldName]['options'] = array();
3640 $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(
3642 $customDAO->option_group_id
,
3646 while ($ogDAO->fetch()) {
3647 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3649 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3654 case 'StateProvince':
3655 if (in_array($customDAO->html_type
, array(
3656 'Multi-Select State/Province',
3658 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3661 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3663 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3667 if (in_array($customDAO->html_type
, array(
3668 'Multi-Select Country',
3670 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3673 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3675 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3678 case 'ContactReference':
3679 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3680 $curFilters[$fieldName]['name'] = 'display_name';
3681 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3683 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3684 $curFields[$fieldName]['name'] = 'display_name';
3685 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3689 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3690 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3693 if (!array_key_exists('type', $curFields[$fieldName])) {
3694 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3698 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3700 if ($this->_customGroupFilters
) {
3701 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3703 if ($this->_customGroupGroupBy
) {
3704 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3710 * Build custom data from clause.
3712 public function customDataFrom() {
3713 if (empty($this->_customGroupExtends
)) {
3716 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3718 foreach ($this->_columns
as $table => $prop) {
3719 if (substr($table, 0, 13) == 'civicrm_value' ||
3720 substr($table, 0, 12) == 'custom_value'
3722 $extendsTable = $mapper[$prop['extends']];
3724 // check field is in params
3725 if (!$this->isFieldSelected($prop)) {
3728 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3730 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3732 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3733 // handle for ContactReference
3734 if (array_key_exists('fields', $prop)) {
3735 foreach ($prop['fields'] as $fieldName => $field) {
3736 if (CRM_Utils_Array
::value('dataType', $field) ==
3739 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3741 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3750 * Check if the field is selected.
3752 * @param string $prop
3756 public function isFieldSelected($prop) {
3761 if (!empty($this->_params
['fields'])) {
3762 foreach (array_keys($prop['fields']) as $fieldAlias) {
3763 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3764 if ($customFieldId) {
3765 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3769 //might be survey response field.
3770 if (!empty($this->_params
['fields']['survey_response']) &&
3771 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3779 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3780 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3781 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3782 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3789 if (!empty($this->_params
['order_bys'])) {
3790 foreach (array_keys($prop['fields']) as $fieldAlias) {
3791 foreach ($this->_params
['order_bys'] as $orderBy) {
3792 if ($fieldAlias == $orderBy['column'] &&
3793 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3801 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3802 foreach ($prop['filters'] as $fieldAlias => $val) {
3811 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3812 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3813 ||
($attach != 'relative' &&
3814 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3820 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3821 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3832 * Check for empty order_by configurations and remove them.
3834 * Also set template to hide them.
3836 * @param array $formValues
3838 public function preProcessOrderBy(&$formValues) {
3839 // Object to show/hide form elements
3840 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3842 $_showHide->addShow('optionField_1');
3844 // Cycle through order_by options; skip any empty ones, and hide them as well
3847 if (!empty($formValues['order_bys'])) {
3848 foreach ($formValues['order_bys'] as $order_by) {
3849 if ($order_by['column'] && $order_by['column'] != '-') {
3850 $_showHide->addShow('optionField_' . $n);
3851 $orderBys[$n] = $order_by;
3856 for ($i = $n; $i <= 5; $i++
) {
3858 $_showHide->addHide('optionField_' . $i);
3862 // overwrite order_by options with modified values
3863 if (!empty($orderBys)) {
3864 $formValues['order_bys'] = $orderBys;
3867 $formValues['order_bys'] = array(1 => array('column' => '-'));
3870 // assign show/hide data to template
3871 $_showHide->addToTemplate();
3875 * Check if table name has columns in SELECT clause.
3877 * @param string $tableName
3878 * Name of table (index of $this->_columns array).
3882 public function isTableSelected($tableName) {
3883 return in_array($tableName, $this->selectedTables());
3887 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3889 * If the array is unset it will be built.
3894 public function selectedTables() {
3895 if (!$this->_selectedTables
) {
3896 $orderByColumns = array();
3897 if (array_key_exists('order_bys', $this->_params
) &&
3898 is_array($this->_params
['order_bys'])
3900 foreach ($this->_params
['order_bys'] as $orderBy) {
3901 $orderByColumns[] = $orderBy['column'];
3905 foreach ($this->_columns
as $tableName => $table) {
3906 if (array_key_exists('fields', $table)) {
3907 foreach ($table['fields'] as $fieldName => $field) {
3908 if (!empty($field['required']) ||
3909 !empty($this->_params
['fields'][$fieldName])
3911 $this->_selectedTables
[] = $tableName;
3916 if (array_key_exists('order_bys', $table)) {
3917 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3918 if (in_array($orderByName, $orderByColumns)) {
3919 $this->_selectedTables
[] = $tableName;
3924 if (array_key_exists('filters', $table)) {
3925 foreach ($table['filters'] as $filterName => $filter) {
3926 if (!empty($this->_params
["{$filterName}_value"]) ||
3927 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3929 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3932 $this->_selectedTables
[] = $tableName;
3939 return $this->_selectedTables
;
3943 * Add address fields.
3945 * @deprecated - use getAddressColumns which is a more accurate description
3946 * and also accepts an array of options rather than a long list
3948 * adding address fields to construct function in reports
3950 * @param bool $groupBy
3951 * Add GroupBy? Not appropriate for detail report.
3952 * @param bool $orderBy
3953 * Add GroupBy? Not appropriate for detail report.
3954 * @param bool $filters
3955 * @param array $defaults
3958 * address fields for construct clause
3960 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3961 $addressFields = array(
3962 'civicrm_address' => array(
3963 'dao' => 'CRM_Core_DAO_Address',
3965 'address_name' => array(
3966 'title' => ts('Address Name'),
3967 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3970 'street_address' => array(
3971 'title' => ts('Street Address'),
3972 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3974 'supplemental_address_1' => array(
3975 'title' => ts('Supplementary Address Field 1'),
3976 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3978 'supplemental_address_2' => array(
3979 'title' => ts('Supplementary Address Field 2'),
3980 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3982 'street_number' => array(
3983 'name' => 'street_number',
3984 'title' => ts('Street Number'),
3986 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3988 'street_name' => array(
3989 'name' => 'street_name',
3990 'title' => ts('Street Name'),
3992 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3994 'street_unit' => array(
3995 'name' => 'street_unit',
3996 'title' => ts('Street Unit'),
3998 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
4001 'title' => ts('City'),
4002 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
4004 'postal_code' => array(
4005 'title' => ts('Postal Code'),
4006 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
4008 'postal_code_suffix' => array(
4009 'title' => ts('Postal Code Suffix'),
4010 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
4012 'country_id' => array(
4013 'title' => ts('Country'),
4014 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
4016 'state_province_id' => array(
4017 'title' => ts('State/Province'),
4018 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
4020 'county_id' => array(
4021 'title' => ts('County'),
4022 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
4025 'grouping' => 'location-fields',
4030 $addressFields['civicrm_address']['filters'] = array(
4031 'street_number' => array(
4032 'title' => ts('Street Number'),
4034 'name' => 'street_number',
4036 'street_name' => array(
4037 'title' => ts('Street Name'),
4038 'name' => 'street_name',
4039 'operator' => 'like',
4041 'postal_code' => array(
4042 'title' => ts('Postal Code'),
4044 'name' => 'postal_code',
4047 'title' => ts('City'),
4048 'operator' => 'like',
4051 'country_id' => array(
4052 'name' => 'country_id',
4053 'title' => ts('Country'),
4054 'type' => CRM_Utils_Type
::T_INT
,
4055 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4056 'options' => CRM_Core_PseudoConstant
::country(),
4058 'state_province_id' => array(
4059 'name' => 'state_province_id',
4060 'title' => ts('State/Province'),
4061 'type' => CRM_Utils_Type
::T_INT
,
4062 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4063 'options' => array(),
4065 'county_id' => array(
4066 'name' => 'county_id',
4067 'title' => ts('County'),
4068 'type' => CRM_Utils_Type
::T_INT
,
4069 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4070 'options' => array(),
4076 $addressFields['civicrm_address']['order_bys'] = array(
4077 'street_name' => array('title' => ts('Street Name')),
4078 'street_number' => array('title' => 'Odd / Even Street Number'),
4079 'street_address' => NULL,
4081 'postal_code' => NULL,
4086 $addressFields['civicrm_address']['group_bys'] = array(
4087 'street_address' => NULL,
4089 'postal_code' => NULL,
4090 'state_province_id' => array(
4091 'title' => ts('State/Province'),
4093 'country_id' => array(
4094 'title' => ts('Country'),
4096 'county_id' => array(
4097 'title' => ts('County'),
4101 return $addressFields;
4105 * Do AlterDisplay processing on Address Fields.
4108 * @param array $rows
4109 * @param int $rowNum
4110 * @param string $baseUrl
4111 * @param string $linkText
4115 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4116 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4117 $entryFound = FALSE;
4119 if (array_key_exists('civicrm_address_country_id', $row)) {
4120 if ($value = $row['civicrm_address_country_id']) {
4121 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4122 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4123 "reset=1&force=1&{$criteriaQueryParams}&" .
4124 "country_id_op=in&country_id_value={$value}",
4125 $this->_absoluteUrl
, $this->_id
4127 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4128 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4129 array(1 => $linkText)
4135 if (array_key_exists('civicrm_address_county_id', $row)) {
4136 if ($value = $row['civicrm_address_county_id']) {
4137 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4138 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4139 "reset=1&force=1&{$criteriaQueryParams}&" .
4140 "county_id_op=in&county_id_value={$value}",
4141 $this->_absoluteUrl
, $this->_id
4143 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4144 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4145 array(1 => $linkText)
4150 // handle state province
4151 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4152 if ($value = $row['civicrm_address_state_province_id']) {
4153 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4155 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4156 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4157 $this->_absoluteUrl
, $this->_id
4159 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4160 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4161 array(1 => $linkText)
4171 * Do AlterDisplay processing on Address Fields.
4174 * @param array $rows
4175 * @param int $rowNum
4176 * @param string $baseUrl
4177 * @param string $linkText
4181 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4182 $entryFound = FALSE;
4183 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4184 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4185 $addLinks = array('gender_id' => 'Gender');
4186 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4187 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4188 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4189 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4190 if (($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4191 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4201 * Adjusts dates passed in to YEAR() for fiscal year.
4203 * @param string $fieldName
4207 public function fiscalYearOffset($fieldName) {
4208 $config = CRM_Core_Config
::singleton();
4209 $fy = $config->fiscalYearStart
;
4210 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4211 ($fy['d'] == 1 && $fy['M'] == 1)
4213 return "YEAR( $fieldName )";
4215 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4216 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4220 * Add Address into From Table if required.
4222 public function addAddressFromClause() {
4223 // include address field if address column is to be included
4224 if ((isset($this->_addressField
) &&
4225 $this->_addressField
4227 $this->isTableSelected('civicrm_address')
4230 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4231 ON ({$this->_aliases['civicrm_contact']}.id =
4232 {$this->_aliases['civicrm_address']}.contact_id) AND
4233 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4238 * Add Phone into From Table if required.
4240 public function addPhoneFromClause() {
4241 // include address field if address column is to be included
4242 if ($this->isTableSelected('civicrm_phone')
4245 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4246 ON ({$this->_aliases['civicrm_contact']}.id =
4247 {$this->_aliases['civicrm_phone']}.contact_id) AND
4248 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4253 * Get phone columns to add to array.
4255 * @param array $options
4256 * - prefix Prefix to add to table (in case of more than one instance of the table)
4257 * - prefix_label Label to give columns from this phone table instance
4260 * phone columns definition
4262 public function getPhoneColumns($options = array()) {
4263 $defaultOptions = array(
4265 'prefix_label' => '',
4268 $options = array_merge($defaultOptions, $options);
4271 $options['prefix'] . 'civicrm_phone' => array(
4272 'dao' => 'CRM_Core_DAO_Phone',
4274 $options['prefix'] . 'phone' => array(
4275 'title' => ts($options['prefix_label'] . 'Phone'),
4285 * Get address columns to add to array.
4287 * @param array $options
4288 * - prefix Prefix to add to table (in case of more than one instance of the table)
4289 * - prefix_label Label to give columns from this address table instance
4292 * address columns definition
4294 public function getAddressColumns($options = array()) {
4297 'prefix_label' => '',
4301 'defaults' => array(),
4303 return $this->addAddressFields(
4304 $options['group_by'],
4305 $options['order_by'],
4306 $options['filters'],
4307 $options['defaults']
4312 * Get a standard set of contact fields.
4316 public function getBasicContactFields() {
4318 'sort_name' => array(
4319 'title' => ts('Contact Name'),
4324 'no_display' => TRUE,
4327 'prefix_id' => array(
4328 'title' => ts('Contact Prefix'),
4330 'first_name' => array(
4331 'title' => ts('First Name'),
4333 'nick_name' => array(
4334 'title' => ts('Nick Name'),
4336 'middle_name' => array(
4337 'title' => ts('Middle Name'),
4339 'last_name' => array(
4340 'title' => ts('Last Name'),
4342 'suffix_id' => array(
4343 'title' => ts('Contact Suffix'),
4345 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4346 'email_greeting_display' => array('title' => ts('Email Greeting')),
4347 'addressee_display' => array('title' => ts('Address Greeting')),
4348 'contact_type' => array(
4349 'title' => ts('Contact Type'),
4351 'contact_sub_type' => array(
4352 'title' => ts('Contact Subtype'),
4354 'gender_id' => array(
4355 'title' => ts('Gender'),
4357 'birth_date' => array(
4358 'title' => ts('Birth Date'),
4361 'title' => ts('Age'),
4362 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4364 'job_title' => array(
4365 'title' => ts('Contact Job title'),
4367 'organization_name' => array(
4368 'title' => ts('Organization Name'),
4370 'external_identifier' => array(
4371 'title' => ts('Contact identifier from external system'),
4377 * Add contact to group.
4379 * @param int $groupID
4381 public function add2group($groupID) {
4382 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4383 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4384 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4386 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4387 $sql = str_replace('WITH ROLLUP', '', $sql);
4388 $dao = CRM_Core_DAO
::executeQuery($sql);
4390 $contact_ids = array();
4391 // Add resulting contacts to group
4392 while ($dao->fetch()) {
4393 if ($dao->addtogroup_contact_id
) {
4394 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4398 if (!empty($contact_ids)) {
4399 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4400 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4403 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4409 * Show charts on print screen.
4411 public static function uploadChartImage() {
4412 // upload strictly for '.png' images
4413 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4414 if (preg_match('/\.png$/', $name)) {
4416 // POST data is usually string data, but we are passing a RAW .png
4417 // so PHP is a bit confused and $_POST is empty. But it has saved
4418 // the raw bits into $HTTP_RAW_POST_DATA
4420 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4422 // prepare the directory
4423 $config = CRM_Core_Config
::singleton();
4425 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4427 if (!file_exists($defaultPath)) {
4428 mkdir($defaultPath, 0777, TRUE);
4431 // full path to the saved image including filename
4432 $destination = $defaultPath . $name;
4435 $jfh = fopen($destination, 'w') or die("can't open file");
4436 fwrite($jfh, $httpRawPostData);
4438 CRM_Utils_System
::civiExit();
4443 * Apply common settings to entityRef fields.
4445 * @param array $field
4446 * @param string $table
4448 private function setEntityRefDefaults(&$field, $table) {
4449 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4450 $field['attributes'] +
= array(
4451 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4453 'placeholder' => ts('- select -'),
4458 * Add link fields to the row.
4460 * Function adds the _link & _hover fields to the row.
4463 * @param string $baseUrl
4464 * @param string $linkText
4465 * @param string $value
4466 * @param string $fieldName
4467 * @param string $tablePrefix
4468 * @param string $fieldLabel
4472 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4473 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4474 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4475 "reset=1&force=1&{$criteriaQueryParams}&" .
4476 $fieldName . "_op=in&{$fieldName}_value={$value}",
4477 $this->_absoluteUrl
, $this->_id
4479 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4480 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4481 array(1 => $linkText, 2 => $fieldLabel)