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 . " )";
1740 // mhas == multiple has
1741 if ($value !== NULL && count($value) > 0) {
1742 $sqlOP = $this->getSQLOperator($op);
1744 = "{$field['dbAlias']} REGEXP '[[:cntrl:]]" . implode('|', $value) .
1750 // mnot == multiple is not one of
1751 if ($value !== NULL && count($value) > 0) {
1752 $sqlOP = $this->getSQLOperator($op);
1754 = "( {$field['dbAlias']} NOT REGEXP '[[:cntrl:]]" . implode('|', $value) .
1755 "[[:cntrl:]]' OR {$field['dbAlias']} IS NULL )";
1761 if ($value !== NULL && strlen($value) > 0) {
1762 $value = CRM_Utils_Type
::escape($value, $type);
1763 if (strpos($value, '%') === FALSE) {
1765 $value = "'{$value}%'";
1768 $value = "'%{$value}'";
1772 $value = "'{$value}'";
1774 $sqlOP = $this->getSQLOperator($op);
1775 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1781 $sqlOP = $this->getSQLOperator($op);
1782 $clause = "( {$field['dbAlias']} $sqlOP )";
1786 if ($value !== NULL && strlen($value) > 0) {
1787 if (isset($field['clause'])) {
1788 // FIXME: we not doing escape here. Better solution is to use two
1789 // different types - data-type and filter-type
1790 $clause = $field['clause'];
1793 $value = CRM_Utils_Type
::escape($value, $type);
1794 $sqlOP = $this->getSQLOperator($op);
1795 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1796 $value = "'{$value}'";
1798 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1804 if (!empty($field['group']) && $clause) {
1805 $clause = $this->whereGroupClause($field, $value, $op);
1807 elseif (!empty($field['tag']) && $clause) {
1808 // not using left join in query because if any contact
1809 // belongs to more than one tag, results duplicate
1811 $clause = $this->whereTagClause($field, $value, $op);
1813 elseif (!empty($field['membership_org']) && $clause) {
1814 $clause = $this->whereMembershipOrgClause($value, $op);
1816 elseif (!empty($field['membership_type']) && $clause) {
1817 $clause = $this->whereMembershipTypeClause($value, $op);
1823 * Get SQL where clause for a date field.
1825 * @param string $fieldName
1826 * @param string $relative
1827 * @param string $from
1829 * @param string $type
1830 * @param string $fromTime
1831 * @param string $toTime
1833 * @return null|string
1835 public function dateClause(
1837 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1840 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1841 $sqlOP = $this->getSQLOperator($relative);
1842 return "( {$fieldName} {$sqlOP} )";
1845 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1848 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1849 $clauses[] = "( {$fieldName} >= $from )";
1853 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1854 $clauses[] = "( {$fieldName} <= {$to} )";
1857 if (!empty($clauses)) {
1858 return implode(' AND ', $clauses);
1865 * Possibly unused function.
1867 * @todo - could not find any instances where this is called
1869 * @param bool $relative
1870 * @param string $from
1873 * @return string|NULL
1875 public function dateDisplay($relative, $from, $to) {
1876 list($from, $to) = $this->getFromTo($relative, $from, $to);
1879 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1882 $clauses[] = 'Past';
1886 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1889 $clauses[] = 'Today';
1892 if (!empty($clauses)) {
1893 return implode(' - ', $clauses);
1900 * Get values for from and to for date ranges.
1902 * @param bool $relative
1903 * @param string $from
1905 * @param string $fromTime
1906 * @param string $toTime
1910 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1911 if (empty($toTime)) {
1914 //FIX ME not working for relative
1916 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1917 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1918 $from = substr($dateRange['from'], 0, 8);
1919 //Take only Date Part, Sometime Time part is also present in 'to'
1920 $to = substr($dateRange['to'], 0, 8);
1922 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1923 $to = CRM_Utils_Date
::processDate($to, $toTime);
1924 return array($from, $to);
1928 * Alter display of rows.
1930 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1931 * such as rendering contacts as links.
1933 * @param array $rows
1934 * Rows generated by SQL, with an array for each row.
1936 public function alterDisplay(&$rows) {
1940 * Alter the way in which custom data fields are displayed.
1942 * @param array $rows
1944 public function alterCustomDataDisplay(&$rows) {
1945 // custom code to alter rows having custom values
1946 if (empty($this->_customGroupExtends
)) {
1950 $customFieldIds = array();
1951 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1952 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1953 $customFieldIds[$fieldAlias] = $fieldId;
1956 if (empty($customFieldIds)) {
1960 $customFields = $fieldValueMap = array();
1961 $customFieldCols = array(
1969 // skip for type date and ContactReference since date format is already handled
1971 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1972 FROM civicrm_custom_field cf
1973 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1974 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1975 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1976 cg.is_active = 1 AND
1977 cf.is_active = 1 AND
1978 cf.is_searchable = 1 AND
1979 cf.data_type NOT IN ('ContactReference', 'Date') AND
1980 cf.id IN (" . implode(",", $customFieldIds) . ")";
1982 $dao = CRM_Core_DAO
::executeQuery($query);
1983 while ($dao->fetch()) {
1984 foreach ($customFieldCols as $key) {
1985 $customFields[$dao->table_name
. '_custom_' .
1986 $dao->id
][$key] = $dao->$key;
1988 if ($dao->option_group_id
) {
1989 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1994 $entryFound = FALSE;
1995 foreach ($rows as $rowNum => $row) {
1996 foreach ($row as $tableCol => $val) {
1997 if (array_key_exists($tableCol, $customFields)) {
1998 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
2003 // skip looking further in rows, if first row itself doesn't
2004 // have the column we need
2012 * Format custom values.
2014 * @param mixed $value
2015 * @param array $customField
2016 * @param array $fieldValueMap
2018 * @return float|string|void
2020 public function formatCustomValues($value, $customField, $fieldValueMap) {
2021 if (CRM_Utils_System
::isNull($value)) {
2025 $htmlType = $customField['html_type'];
2027 switch ($customField['data_type']) {
2029 if ($value == '1') {
2030 $retValue = ts('Yes');
2033 $retValue = ts('No');
2038 $retValue = CRM_Utils_System
::formatWikiURL($value);
2050 if ($htmlType == 'Text') {
2051 $retValue = (float) $value;
2055 if ($htmlType == 'Text') {
2056 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2061 if (in_array($htmlType, array(
2068 case 'StateProvince':
2071 switch ($htmlType) {
2072 case 'Multi-Select Country':
2073 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2074 $customData = array();
2075 foreach ($value as $val) {
2077 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
2080 $retValue = implode(', ', $customData);
2083 case 'Select Country':
2084 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
2087 case 'Select State/Province':
2088 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2091 case 'Multi-Select State/Province':
2092 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2093 $customData = array();
2094 foreach ($value as $val) {
2096 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
2099 $retValue = implode(', ', $customData);
2104 case 'Autocomplete-Select':
2105 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2109 case 'AdvMulti-Select':
2110 case 'Multi-Select':
2111 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2112 $customData = array();
2113 foreach ($value as $val) {
2115 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2118 $retValue = implode(', ', $customData);
2134 * Remove duplicate rows.
2136 * @param array $rows
2138 public function removeDuplicates(&$rows) {
2139 if (empty($this->_noRepeats
)) {
2142 $checkList = array();
2144 foreach ($rows as $key => $list) {
2145 foreach ($list as $colName => $colVal) {
2146 if (array_key_exists($colName, $checkList) &&
2147 $checkList[$colName] == $colVal
2149 $rows[$key][$colName] = "";
2151 if (in_array($colName, $this->_noRepeats
)) {
2152 $checkList[$colName] = $colVal;
2159 * Fix subtotal display.
2162 * @param array $fields
2163 * @param bool $subtotal
2165 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2166 foreach ($row as $colName => $colVal) {
2167 if (in_array($colName, $fields)) {
2169 elseif (isset($this->_columnHeaders
[$colName])) {
2171 $row[$colName] = "Subtotal";
2175 unset($row[$colName]);
2182 * Calculate grant total.
2184 * @param array $rows
2188 public function grandTotal(&$rows) {
2189 if (!$this->_rollup ||
($this->_rollup
== '') ||
2190 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2194 $lastRow = array_pop($rows);
2196 foreach ($this->_columnHeaders
as $fld => $val) {
2197 if (!in_array($fld, $this->_statFields
)) {
2198 if (!$this->_grandFlag
) {
2199 $lastRow[$fld] = "Grand Total";
2200 $this->_grandFlag
= TRUE;
2203 $lastRow[$fld] = "";
2208 $this->assign('grandStat', $lastRow);
2213 * Format display output.
2215 * @param array $rows
2216 * @param bool $pager
2218 public function formatDisplay(&$rows, $pager = TRUE) {
2219 // set pager based on if any limit was applied in the query.
2224 // allow building charts if any
2225 if (!empty($this->_params
['charts']) && !empty($rows)) {
2226 $this->buildChart($rows);
2227 $this->assign('chartEnabled', TRUE);
2228 $this->_chartId
= "{$this->_params['charts']}_" .
2229 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2231 $this->assign('chartId', $this->_chartId
);
2234 // unset columns not to be displayed.
2235 foreach ($this->_columnHeaders
as $key => $value) {
2236 if (!empty($value['no_display'])) {
2237 unset($this->_columnHeaders
[$key]);
2241 // unset columns not to be displayed.
2242 if (!empty($rows)) {
2243 foreach ($this->_noDisplay
as $noDisplayField) {
2244 foreach ($rows as $rowNum => $row) {
2245 unset($this->_columnHeaders
[$noDisplayField]);
2250 // build array of section totals
2251 $this->sectionTotals();
2253 // process grand-total row
2254 $this->grandTotal($rows);
2256 // use this method for formatting rows for display purpose.
2257 $this->alterDisplay($rows);
2258 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2260 // use this method for formatting custom rows for display purpose.
2261 $this->alterCustomDataDisplay($rows);
2267 * @param array $rows
2269 public function buildChart(&$rows) {
2270 // override this method for building charts.
2273 // select() method below has been added recently (v3.3), and many of the report templates might
2274 // still be having their own select() method. We should fix them as and when encountered and move
2275 // towards generalizing the select() method below.
2278 * Generate the SELECT clause and set class variable $_select.
2280 public function select() {
2281 $select = $this->_selectAliases
= array();
2283 foreach ($this->_columns
as $tableName => $table) {
2284 if (array_key_exists('fields', $table)) {
2285 foreach ($table['fields'] as $fieldName => $field) {
2286 if ($tableName == 'civicrm_address') {
2287 $this->_addressField
= TRUE;
2289 if ($tableName == 'civicrm_email') {
2290 $this->_emailField
= TRUE;
2292 if ($tableName == 'civicrm_phone') {
2293 $this->_phoneField
= TRUE;
2296 if (!empty($field['required']) ||
2297 !empty($this->_params
['fields'][$fieldName])
2300 // 1. In many cases we want select clause to be built in slightly different way
2301 // for a particular field of a particular type.
2302 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2304 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2305 if ($selectClause) {
2306 $select[] = $selectClause;
2310 // include statistics columns only if set
2311 if (!empty($field['statistics'])) {
2312 foreach ($field['statistics'] as $stat => $label) {
2313 $alias = "{$tableName}_{$fieldName}_{$stat}";
2314 switch (strtolower($stat)) {
2317 $select[] = "$stat({$field['dbAlias']}) as $alias";
2318 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2319 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2320 $this->_statFields
[$label] = $alias;
2321 $this->_selectAliases
[] = $alias;
2325 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2326 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2327 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2328 $this->_statFields
[$label] = $alias;
2329 $this->_selectAliases
[] = $alias;
2332 case 'count_distinct':
2333 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2334 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2335 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2336 $this->_statFields
[$label] = $alias;
2337 $this->_selectAliases
[] = $alias;
2341 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2342 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2343 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2344 $this->_statFields
[$label] = $alias;
2345 $this->_selectAliases
[] = $alias;
2351 $alias = "{$tableName}_{$fieldName}";
2352 $select[] = "{$field['dbAlias']} as $alias";
2353 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2354 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2355 $this->_selectAliases
[] = $alias;
2361 // select for group bys
2362 if (array_key_exists('group_bys', $table)) {
2363 foreach ($table['group_bys'] as $fieldName => $field) {
2365 if ($tableName == 'civicrm_address') {
2366 $this->_addressField
= TRUE;
2368 if ($tableName == 'civicrm_email') {
2369 $this->_emailField
= TRUE;
2371 if ($tableName == 'civicrm_phone') {
2372 $this->_phoneField
= TRUE;
2374 // 1. In many cases we want select clause to be built in slightly different way
2375 // for a particular field of a particular type.
2376 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2378 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2379 if ($selectClause) {
2380 $select[] = $selectClause;
2384 if (!empty($this->_params
['group_bys']) &&
2385 !empty($this->_params
['group_bys'][$fieldName]) &&
2386 !empty($this->_params
['group_bys_freq'])
2388 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2390 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2391 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2392 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2393 $field['title'] = 'Week';
2397 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2398 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2399 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2400 $field['title'] = 'Year';
2404 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2405 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2406 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2407 $field['title'] = 'Month';
2411 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2412 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2413 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2414 $field['title'] = 'Quarter';
2417 // for graphs and charts -
2418 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2419 $this->_interval
= $field['title'];
2420 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2421 = $field['title'] . ' Beginning';
2422 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2423 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2425 // just to make sure these values are transferred to rows.
2426 // since we 'll need them for calculation purpose,
2427 // e.g making subtotals look nicer or graphs
2428 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2429 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2436 $this->_selectClauses
= $select;
2437 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2441 * Build select clause for a single field.
2443 * @param string $tableName
2444 * @param string $tableKey
2445 * @param string $fieldName
2446 * @param string $field
2450 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2455 * Build where clause.
2457 public function where() {
2458 $this->storeWhereHavingClauseArray();
2460 if (empty($this->_whereClauses
)) {
2461 $this->_where
= "WHERE ( 1 ) ";
2462 $this->_having
= "";
2465 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2468 if ($this->_aclWhere
) {
2469 $this->_where
.= " AND {$this->_aclWhere} ";
2472 if (!empty($this->_havingClauses
)) {
2473 // use this clause to construct group by clause.
2474 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2479 * Store Where clauses into an array.
2481 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2482 * temp table that may not be part of the final where clause or added
2483 * in other functions
2485 public function storeWhereHavingClauseArray() {
2486 foreach ($this->_columns
as $tableName => $table) {
2487 if (array_key_exists('filters', $table)) {
2488 foreach ($table['filters'] as $fieldName => $field) {
2489 // respect pseudofield to filter spec so fields can be marked as
2490 // not to be handled here
2491 if (!empty($field['pseudofield'])) {
2495 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2496 if (CRM_Utils_Array
::value('operatorType', $field) ==
2497 CRM_Report_Form
::OP_MONTH
2499 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2500 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2501 if (is_array($value) && !empty($value)) {
2503 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2508 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2509 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2510 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2511 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2512 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2513 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2517 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2519 $clause = $this->whereClause($field,
2521 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2522 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2523 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2528 if (!empty($clause)) {
2529 if (!empty($field['having'])) {
2530 $this->_havingClauses
[] = $clause;
2533 $this->_whereClauses
[] = $clause;
2545 public function processReportMode() {
2546 $buttonName = $this->controller
->getButtonName();
2548 $output = CRM_Utils_Request
::retrieve(
2551 CRM_Core_DAO
::$_nullObject
2555 = CRM_Utils_Request
::retrieve(
2558 CRM_Core_DAO
::$_nullObject
2561 $this->_absoluteUrl
= FALSE;
2563 $this->assign('printOnly', FALSE);
2565 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2566 ($this->_sendmail
&& !$output)
2568 $this->assign('printOnly', TRUE);
2570 $this->assign('outputMode', 'print');
2571 $this->_outputMode
= 'print';
2572 if ($this->_sendmail
) {
2573 $this->_absoluteUrl
= TRUE;
2576 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2577 $this->assign('printOnly', TRUE);
2579 $this->assign('outputMode', 'pdf');
2580 $this->_outputMode
= 'pdf';
2581 $this->_absoluteUrl
= TRUE;
2583 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2584 $this->assign('printOnly', TRUE);
2586 $this->assign('outputMode', 'csv');
2587 $this->_outputMode
= 'csv';
2588 $this->_absoluteUrl
= TRUE;
2590 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2591 $this->assign('outputMode', 'group');
2592 $this->_outputMode
= 'group';
2594 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2595 $this->assign('outputMode', 'create_report');
2596 $this->_outputMode
= 'create_report';
2599 $this->assign('outputMode', 'html');
2600 $this->_outputMode
= 'html';
2603 // Get today's date to include in printed reports
2605 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2606 $this->assign('reportDate', $reportDate);
2611 * Post Processing function for Form.
2613 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2615 public function beginPostProcess() {
2616 $this->setParams($this->controller
->exportValues($this->_name
));
2618 if (empty($this->_params
) &&
2621 $this->setParams($this->_formValues
);
2624 // hack to fix params when submitted from dashboard, CRM-8532
2625 // fields array is missing because form building etc is skipped
2626 // in dashboard mode for report
2627 //@todo - this could be done in the dashboard no we have a setter
2628 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2629 $this->setParams($this->_formValues
);
2632 $this->_formValues
= $this->_params
;
2633 if (CRM_Core_Permission
::check('administer Reports') &&
2634 isset($this->_id
) &&
2635 ($this->_instanceButtonName
==
2636 $this->controller
->getButtonName() . '_save' ||
2637 $this->_chartButtonName
== $this->controller
->getButtonName()
2640 $this->assign('updateReportButton', TRUE);
2642 $this->processReportMode();
2643 $this->beginPostProcessCommon();
2647 * BeginPostProcess function run in both report mode and non-report mode (api).
2649 public function beginPostProcessCommon() {}
2652 * Build the report query.
2654 * @param bool $applyLimit
2658 public function buildQuery($applyLimit = TRUE) {
2661 $this->customDataFrom();
2666 // order_by columns not selected for display need to be included in SELECT
2667 $unselectedSectionColumns = $this->unselectedSectionColumns();
2668 foreach ($unselectedSectionColumns as $alias => $section) {
2669 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2672 if ($applyLimit && empty($this->_params
['charts'])) {
2675 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2677 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2682 * Build group by clause.
2684 public function groupBy() {
2685 $groupBys = array();
2686 if (!empty($this->_params
['group_bys']) &&
2687 is_array($this->_params
['group_bys'])
2689 foreach ($this->_columns
as $tableName => $table) {
2690 if (array_key_exists('group_bys', $table)) {
2691 foreach ($table['group_bys'] as $fieldName => $field) {
2692 if (!empty($this->_params
['group_bys'][$fieldName])) {
2693 $groupBys[] = $field['dbAlias'];
2700 if (!empty($groupBys)) {
2701 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2706 * Build order by clause.
2708 public function orderBy() {
2709 $this->_orderBy
= "";
2710 $this->_sections
= array();
2711 $this->storeOrderByArray();
2712 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2713 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2715 $this->assign('sections', $this->_sections
);
2719 * Extract order by fields and store as an array.
2721 * In some cases other functions want to know which fields are selected for ordering by
2722 * Separating this into a separate function allows it to be called separately from constructing
2723 * the order by clause
2725 public function storeOrderByArray() {
2726 $orderBys = array();
2728 if (!empty($this->_params
['order_bys']) &&
2729 is_array($this->_params
['order_bys']) &&
2730 !empty($this->_params
['order_bys'])
2733 // Process order_bys in user-specified order
2734 foreach ($this->_params
['order_bys'] as $orderBy) {
2735 $orderByField = array();
2736 foreach ($this->_columns
as $tableName => $table) {
2737 if (array_key_exists('order_bys', $table)) {
2738 // For DAO columns defined in $this->_columns
2739 $fields = $table['order_bys'];
2741 elseif (array_key_exists('extends', $table)) {
2742 // For custom fields referenced in $this->_customGroupExtends
2743 $fields = CRM_Utils_Array
::value('fields', $table, array());
2748 if (!empty($fields) && is_array($fields)) {
2749 foreach ($fields as $fieldName => $field) {
2750 if ($fieldName == $orderBy['column']) {
2751 $orderByField = array_merge($field, $orderBy);
2752 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2759 if (!empty($orderByField)) {
2760 $this->_orderByFields
[] = $orderByField;
2761 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2763 // Record any section headers for assignment to the template
2764 if (!empty($orderBy['section'])) {
2765 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2766 $this->_sections
[$orderByField['tplField']] = $orderByField;
2772 $this->_orderByArray
= $orderBys;
2774 $this->assign('sections', $this->_sections
);
2778 * Determine unselected columns.
2782 public function unselectedSectionColumns() {
2783 $selectColumns = array();
2784 foreach ($this->_columns
as $tableName => $table) {
2785 if (array_key_exists('fields', $table)) {
2786 foreach ($table['fields'] as $fieldName => $field) {
2787 if (!empty($field['required']) ||
2788 !empty($this->_params
['fields'][$fieldName])
2791 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2797 if (is_array($this->_sections
)) {
2798 return array_diff_key($this->_sections
, $selectColumns);
2806 * Build output rows.
2808 * @param string $sql
2809 * @param array $rows
2811 public function buildRows($sql, &$rows) {
2812 $dao = CRM_Core_DAO
::executeQuery($sql);
2813 if (!is_array($rows)) {
2817 // use this method to modify $this->_columnHeaders
2818 $this->modifyColumnHeaders();
2820 $unselectedSectionColumns = $this->unselectedSectionColumns();
2822 while ($dao->fetch()) {
2824 foreach ($this->_columnHeaders
as $key => $value) {
2825 if (property_exists($dao, $key)) {
2826 $row[$key] = $dao->$key;
2830 // section headers not selected for display need to be added to row
2831 foreach ($unselectedSectionColumns as $key => $values) {
2832 if (property_exists($dao, $key)) {
2833 $row[$key] = $dao->$key;
2842 * Calculate section totals.
2844 * When "order by" fields are marked as sections, this assigns to the template
2845 * an array of total counts for each section. This data is used by the Smarty
2846 * plugin {sectionTotal}.
2848 public function sectionTotals() {
2850 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2851 if (empty($this->_selectAliases
)) {
2855 if (!empty($this->_sections
)) {
2856 // build the query with no LIMIT clause
2857 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2858 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2860 // pull section aliases out of $this->_sections
2861 $sectionAliases = array_keys($this->_sections
);
2864 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2865 $ifnulls[] = "ifnull($alias, '') as $alias";
2868 // Group (un-limited) report by all aliases and get counts. This might
2869 // be done more efficiently when the contents of $sql are known, ie. by
2870 // overriding this method in the report class.
2872 $query = "select " . implode(", ", $ifnulls) .
2873 ", count(*) as ct from ($sql) as subquery group by " .
2874 implode(", ", $sectionAliases);
2876 // initialize array of total counts
2878 $dao = CRM_Core_DAO
::executeQuery($query);
2879 while ($dao->fetch()) {
2881 // let $this->_alterDisplay translate any integer ids to human-readable values.
2882 $rows[0] = $dao->toArray();
2883 $this->alterDisplay($rows);
2886 // add totals for all permutations of section values
2889 $aliasCount = count($sectionAliases);
2890 foreach ($sectionAliases as $alias) {
2891 $values[] = $row[$alias];
2892 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2893 if ($i == $aliasCount) {
2894 // the last alias is the lowest-level section header; use count as-is
2895 $totals[$key] = $dao->ct
;
2898 // other aliases are higher level; roll count into their total
2899 $totals[$key] +
= $dao->ct
;
2903 $this->assign('sectionTotals', $totals);
2908 * Modify column headers.
2910 public function modifyColumnHeaders() {
2911 // use this method to modify $this->_columnHeaders
2915 * Assign rows to the template.
2917 * @param array $rows
2919 public function doTemplateAssignment(&$rows) {
2920 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2921 $this->assign_by_ref('rows', $rows);
2922 $this->assign('statistics', $this->statistics($rows));
2926 * Build report statistics.
2928 * Override this method to build your own statistics.
2930 * @param array $rows
2934 public function statistics(&$rows) {
2935 $statistics = array();
2937 $count = count($rows);
2939 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2943 $this->countStat($statistics, $count);
2945 $this->groupByStat($statistics);
2947 $this->filterStat($statistics);
2953 * Add count statistics.
2955 * @param array $statistics
2958 public function countStat(&$statistics, $count) {
2959 $statistics['counts']['rowCount'] = array(
2960 'title' => ts('Row(s) Listed'),
2964 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2965 $statistics['counts']['rowsFound'] = array(
2966 'title' => ts('Total Row(s)'),
2967 'value' => $this->_rowsFound
,
2973 * Add group by statistics.
2975 * @param array $statistics
2977 public function groupByStat(&$statistics) {
2978 if (!empty($this->_params
['group_bys']) &&
2979 is_array($this->_params
['group_bys']) &&
2980 !empty($this->_params
['group_bys'])
2982 foreach ($this->_columns
as $tableName => $table) {
2983 if (array_key_exists('group_bys', $table)) {
2984 foreach ($table['group_bys'] as $fieldName => $field) {
2985 if (!empty($this->_params
['group_bys'][$fieldName])) {
2986 $combinations[] = $field['title'];
2991 $statistics['groups'][] = array(
2992 'title' => ts('Grouping(s)'),
2993 'value' => implode(' & ', $combinations),
2999 * Filter statistics.
3001 * @param array $statistics
3003 public function filterStat(&$statistics) {
3004 foreach ($this->_columns
as $tableName => $table) {
3005 if (array_key_exists('filters', $table)) {
3006 foreach ($table['filters'] as $fieldName => $field) {
3007 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
3008 CRM_Utils_Array
::value('operatorType', $field) !=
3009 CRM_Report_Form
::OP_MONTH
3013 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3014 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3015 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3016 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3017 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3019 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3020 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3022 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3023 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3026 $statistics['filters'][] = array(
3027 'title' => $field['title'],
3028 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3031 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3032 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3034 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3035 $statistics['filters'][] = array(
3036 'title' => $field['title'],
3037 'value' => $pair[$rel],
3042 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3045 $pair = $this->getOperationPair(
3046 CRM_Utils_Array
::value('operatorType', $field),
3049 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3050 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3051 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3052 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3053 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3055 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3056 $this->setEntityRefDefaults($field, $tableName);
3057 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3058 array('id' => $val) +
3059 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3061 foreach ($result['values'] as $v) {
3062 $values[] = $v['label'];
3064 $value = "{$pair[$op]} " . implode(', ', $values);
3066 elseif ($op == 'nll' ||
$op == 'nnll') {
3067 $value = $pair[$op];
3069 elseif (is_array($val) && (!empty($val))) {
3070 $options = CRM_Utils_Array
::value('options', $field, array());
3071 foreach ($val as $key => $valIds) {
3072 if (isset($options[$valIds])) {
3073 $val[$key] = $options[$valIds];
3076 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3077 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3078 $val = implode(', ', $val);
3079 $value = "{$pair[$op]} " . $val;
3081 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3082 isset($field['options']) &&
3083 is_array($field['options']) && !empty($field['options'])
3085 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3086 CRM_Utils_Array
::value($val, $field['options'], $val);
3089 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3093 $statistics['filters'][] = array(
3094 'title' => CRM_Utils_Array
::value('title', $field),
3105 * End post processing.
3107 * @param array|null $rows
3109 public function endPostProcess(&$rows = NULL) {
3110 if ($this->_storeResultSet
) {
3111 $this->_resultSet
= $rows;
3114 if ($this->_outputMode
== 'print' ||
3115 $this->_outputMode
== 'pdf' ||
3119 $content = $this->compileContent();
3120 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3124 if ($this->_sendmail
) {
3125 $config = CRM_Core_Config
::singleton();
3126 $attachments = array();
3128 if ($this->_outputMode
== 'csv') {
3130 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3131 ": {$url}</p>" . '<p>' .
3132 ts('The report is attached as a CSV file.') . '</p>' .
3133 $this->_formValues
['report_footer'];
3135 $csvFullFilename = $config->templateCompileDir
.
3136 CRM_Utils_File
::makeFileName('CiviReport.csv');
3137 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3138 file_put_contents($csvFullFilename, $csvContent);
3139 $attachments[] = array(
3140 'fullPath' => $csvFullFilename,
3141 'mime_type' => 'text/csv',
3142 'cleanName' => 'CiviReport.csv',
3145 if ($this->_outputMode
== 'pdf') {
3146 // generate PDF content
3147 $pdfFullFilename = $config->templateCompileDir
.
3148 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3149 file_put_contents($pdfFullFilename,
3150 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3151 TRUE, array('orientation' => 'landscape')
3154 // generate Email Content
3156 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3157 ": {$url}</p>" . '<p>' .
3158 ts('The report is attached as a PDF file.') . '</p>' .
3159 $this->_formValues
['report_footer'];
3161 $attachments[] = array(
3162 'fullPath' => $pdfFullFilename,
3163 'mime_type' => 'application/pdf',
3164 'cleanName' => 'CiviReport.pdf',
3168 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3169 $this->_outputMode
, $attachments
3172 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3175 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3179 elseif ($this->_outputMode
== 'print') {
3183 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3184 $config = CRM_Core_Config
::singleton();
3185 //get chart image name
3186 $chartImg = $this->_chartId
. '.png';
3187 //get image url path
3189 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3191 $uploadUrl .= $chartImg;
3192 //get image doc path to overwrite
3194 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3195 'openFlashChart/' . $chartImg;
3197 $chart = imagecreatefrompng($uploadUrl);
3198 //convert it into formatted png
3199 header('Content-type: image/png');
3200 //overwrite with same image
3201 imagepng($chart, $uploadImg);
3203 imagedestroy($chart);
3205 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3207 CRM_Utils_System
::civiExit();
3209 elseif ($this->_outputMode
== 'csv') {
3210 CRM_Report_Utils_Report
::export2csv($this, $rows);
3212 elseif ($this->_outputMode
== 'group') {
3213 $group = $this->_params
['groups'];
3214 $this->add2group($group);
3216 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3217 CRM_Report_Form_Instance
::postProcess($this);
3219 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3220 $this->_outputMode
== 'create_report'
3222 $this->_createNew
= TRUE;
3223 CRM_Report_Form_Instance
::postProcess($this);
3228 * Set store result set indicator to TRUE.
3230 * @todo explain what this does
3232 public function storeResultSet() {
3233 $this->_storeResultSet
= TRUE;
3241 public function getResultSet() {
3242 return $this->_resultSet
;
3246 * Use the form name to create the tpl file name.
3250 public function getTemplateFileName() {
3251 $defaultTpl = parent
::getTemplateFileName();
3252 $template = CRM_Core_Smarty
::singleton();
3253 if (!$template->template_exists($defaultTpl)) {
3254 $defaultTpl = 'CRM/Report/Form.tpl';
3260 * Compile the report content.
3262 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3266 public function compileContent() {
3267 $templateFile = $this->getHookedTemplateFileName();
3268 return $this->_formValues
['report_header'] .
3269 CRM_Core_Form
::$_template->fetch($templateFile) .
3270 $this->_formValues
['report_footer'];
3275 * Post process function.
3277 public function postProcess() {
3278 // get ready with post process params
3279 $this->beginPostProcess();
3282 $sql = $this->buildQuery();
3284 // build array of result based on column headers. This method also allows
3285 // modifying column headers before using it to build result set i.e $rows.
3287 $this->buildRows($sql, $rows);
3289 // format result set.
3290 $this->formatDisplay($rows);
3292 // assign variables to templates
3293 $this->doTemplateAssignment($rows);
3295 // do print / pdf / instance stuff if needed
3296 $this->endPostProcess($rows);
3302 * @param int $rowCount
3306 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3307 // lets do the pager if in html mode
3308 $this->_limit
= NULL;
3310 // CRM-14115, over-ride row count if rowCount is specified in URL
3311 if ($this->_dashBoardRowCount
) {
3312 $rowCount = $this->_dashBoardRowCount
;
3314 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3315 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3317 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3319 // @todo all http vars should be extracted in the preProcess
3320 // - not randomly in the class
3321 if (!$pageId && !empty($_POST)) {
3322 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3323 $pageId = max((int) $_POST['crmPID_B'], 1);
3325 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3326 $pageId = max((int) $_POST['crmPID'], 1);
3328 unset($_POST['crmPID_B'], $_POST['crmPID']);
3331 $pageId = $pageId ?
$pageId : 1;
3332 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3333 $offset = ($pageId - 1) * $rowCount;
3335 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3336 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3338 $this->_limit
= " LIMIT $offset, $rowCount";
3339 return array($offset, $rowCount);
3341 if ($this->_limitValue
) {
3342 if ($this->_offsetValue
) {
3343 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3346 $this->_limit
= " LIMIT " . $this->_limitValue
;
3354 * @param int $rowCount
3356 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3358 // CRM-14115, over-ride row count if rowCount is specified in URL
3359 if ($this->_dashBoardRowCount
) {
3360 $rowCount = $this->_dashBoardRowCount
;
3363 if ($this->_limit
&& ($this->_limit
!= '')) {
3364 $sql = "SELECT FOUND_ROWS();";
3365 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3367 'total' => $this->_rowsFound
,
3368 'rowCount' => $rowCount,
3369 'status' => ts('Records') . ' %%StatusMessage%%',
3370 'buttonBottom' => 'PagerBottomButton',
3371 'buttonTop' => 'PagerTopButton',
3372 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3375 $pager = new CRM_Utils_Pager($params);
3376 $this->assign_by_ref('pager', $pager);
3377 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3382 * Build where clause for groups.
3384 * @param string $field
3385 * @param mixed $value
3390 public function whereGroupClause($field, $value, $op) {
3392 $smartGroupQuery = "";
3394 $group = new CRM_Contact_DAO_Group();
3395 $group->is_active
= 1;
3397 $smartGroups = array();
3398 while ($group->fetch()) {
3399 if (in_array($group->id
, $this->_params
['gid_value']) &&
3400 $group->saved_search_id
3402 $smartGroups[] = $group->id
;
3406 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3408 $smartGroupQuery = '';
3409 if (!empty($smartGroups)) {
3410 $smartGroups = implode(',', $smartGroups);
3411 $smartGroupQuery = " UNION DISTINCT
3412 SELECT DISTINCT smartgroup_contact.contact_id
3413 FROM civicrm_group_contact_cache smartgroup_contact
3414 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3417 $sqlOp = $this->getSQLOperator($op);
3418 if (!is_array($value)) {
3419 $value = array($value);
3421 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3423 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3424 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3425 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3426 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3427 {$smartGroupQuery} ) ";
3431 * Build where clause for tags.
3433 * @param string $field
3434 * @param mixed $value
3439 public function whereTagClause($field, $value, $op) {
3440 // not using left join in query because if any contact
3441 // belongs to more than one tag, results duplicate
3443 $sqlOp = $this->getSQLOperator($op);
3444 if (!is_array($value)) {
3445 $value = array($value);
3447 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3448 $entity_table = $this->_tagFilterTable
;
3449 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3450 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3451 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3452 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3456 * Generate membership organization clause.
3458 * @param mixed $value
3459 * @param string $op SQL Operator
3463 public function whereMembershipOrgClause($value, $op) {
3464 $sqlOp = $this->getSQLOperator($op);
3465 if (!is_array($value)) {
3466 $value = array($value);
3469 $tmp_membership_org_sql_list = implode(', ', $value);
3470 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3471 SELECT DISTINCT mem.contact_id
3472 FROM civicrm_membership mem
3473 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3474 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3475 WHERE mt.member_of_contact_id IN (" .
3476 $tmp_membership_org_sql_list . ")
3477 AND mt.is_active = '1'
3478 AND mem_status.is_current_member = '1'
3479 AND mem_status.is_active = '1' ) ";
3483 * Generate Membership Type SQL Clause.
3485 * @param mixed $value
3491 public function whereMembershipTypeClause($value, $op) {
3492 $sqlOp = $this->getSQLOperator($op);
3493 if (!is_array($value)) {
3494 $value = array($value);
3497 $tmp_membership_sql_list = implode(', ', $value);
3498 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3499 SELECT DISTINCT mem.contact_id
3500 FROM civicrm_membership mem
3501 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3502 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3503 WHERE mem.membership_type_id IN (" .
3504 $tmp_membership_sql_list . ")
3505 AND mt.is_active = '1'
3506 AND mem_status.is_current_member = '1'
3507 AND mem_status.is_active = '1' ) ";
3511 * Build acl clauses.
3513 * @param string $tableAlias
3515 public function buildACLClause($tableAlias = 'contact_a') {
3516 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3520 * Add custom data to the columns.
3522 * @param bool $addFields
3523 * @param array $permCustomGroupIds
3525 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3526 if (empty($this->_customGroupExtends
)) {
3529 if (!is_array($this->_customGroupExtends
)) {
3530 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3532 $customGroupWhere = '';
3533 if (!empty($permCustomGroupIds)) {
3534 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3538 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3539 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3540 FROM civicrm_custom_group cg
3541 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3542 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3544 cg.is_active = 1 AND
3545 cf.is_active = 1 AND
3546 cf.is_searchable = 1
3547 ORDER BY cg.weight, cf.weight";
3548 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3551 while ($customDAO->fetch()) {
3552 if ($customDAO->table_name
!= $curTable) {
3553 $curTable = $customDAO->table_name
;
3554 $curFields = $curFilters = array();
3557 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3558 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3559 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3560 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3567 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3568 $this->_columns
[$curTable][$colKey] = array();
3572 $fieldName = 'custom_' . $customDAO->cf_id
;
3575 // this makes aliasing work in favor
3576 $curFields[$fieldName] = array(
3577 'name' => $customDAO->column_name
,
3578 'title' => $customDAO->label
,
3579 'dataType' => $customDAO->data_type
,
3580 'htmlType' => $customDAO->html_type
,
3583 if ($this->_customGroupFilters
) {
3584 // this makes aliasing work in favor
3585 $curFilters[$fieldName] = array(
3586 'name' => $customDAO->column_name
,
3587 'title' => $customDAO->label
,
3588 'dataType' => $customDAO->data_type
,
3589 'htmlType' => $customDAO->html_type
,
3593 switch ($customDAO->data_type
) {
3596 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3597 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3598 // CRM-6946, show time part for datetime date fields
3599 if ($customDAO->time_format
) {
3600 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3605 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3606 $curFilters[$fieldName]['options'] = array(
3607 '' => ts('- select -'),
3611 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3615 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3616 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3620 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3621 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3625 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3626 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3630 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3632 if (!empty($customDAO->option_group_id
)) {
3633 if (in_array($customDAO->html_type
, array(
3638 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3641 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3643 if ($this->_customGroupFilters
) {
3644 $curFilters[$fieldName]['options'] = array();
3645 $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(
3647 $customDAO->option_group_id
,
3651 while ($ogDAO->fetch()) {
3652 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3654 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3659 case 'StateProvince':
3660 if (in_array($customDAO->html_type
, array(
3661 'Multi-Select State/Province',
3663 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3666 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3668 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3672 if (in_array($customDAO->html_type
, array(
3673 'Multi-Select Country',
3675 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3678 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3680 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3683 case 'ContactReference':
3684 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3685 $curFilters[$fieldName]['name'] = 'display_name';
3686 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3688 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3689 $curFields[$fieldName]['name'] = 'display_name';
3690 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3694 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3695 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3698 if (!array_key_exists('type', $curFields[$fieldName])) {
3699 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3703 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3705 if ($this->_customGroupFilters
) {
3706 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3708 if ($this->_customGroupGroupBy
) {
3709 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3715 * Build custom data from clause.
3717 public function customDataFrom() {
3718 if (empty($this->_customGroupExtends
)) {
3721 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3723 foreach ($this->_columns
as $table => $prop) {
3724 if (substr($table, 0, 13) == 'civicrm_value' ||
3725 substr($table, 0, 12) == 'custom_value'
3727 $extendsTable = $mapper[$prop['extends']];
3729 // check field is in params
3730 if (!$this->isFieldSelected($prop)) {
3733 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3735 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3737 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3738 // handle for ContactReference
3739 if (array_key_exists('fields', $prop)) {
3740 foreach ($prop['fields'] as $fieldName => $field) {
3741 if (CRM_Utils_Array
::value('dataType', $field) ==
3744 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3746 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3755 * Check if the field is selected.
3757 * @param string $prop
3761 public function isFieldSelected($prop) {
3766 if (!empty($this->_params
['fields'])) {
3767 foreach (array_keys($prop['fields']) as $fieldAlias) {
3768 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3769 if ($customFieldId) {
3770 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3774 //might be survey response field.
3775 if (!empty($this->_params
['fields']['survey_response']) &&
3776 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3784 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3785 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3786 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3787 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3794 if (!empty($this->_params
['order_bys'])) {
3795 foreach (array_keys($prop['fields']) as $fieldAlias) {
3796 foreach ($this->_params
['order_bys'] as $orderBy) {
3797 if ($fieldAlias == $orderBy['column'] &&
3798 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3806 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3807 foreach ($prop['filters'] as $fieldAlias => $val) {
3816 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3817 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3818 ||
($attach != 'relative' &&
3819 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3825 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3826 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3837 * Check for empty order_by configurations and remove them.
3839 * Also set template to hide them.
3841 * @param array $formValues
3843 public function preProcessOrderBy(&$formValues) {
3844 // Object to show/hide form elements
3845 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3847 $_showHide->addShow('optionField_1');
3849 // Cycle through order_by options; skip any empty ones, and hide them as well
3852 if (!empty($formValues['order_bys'])) {
3853 foreach ($formValues['order_bys'] as $order_by) {
3854 if ($order_by['column'] && $order_by['column'] != '-') {
3855 $_showHide->addShow('optionField_' . $n);
3856 $orderBys[$n] = $order_by;
3861 for ($i = $n; $i <= 5; $i++
) {
3863 $_showHide->addHide('optionField_' . $i);
3867 // overwrite order_by options with modified values
3868 if (!empty($orderBys)) {
3869 $formValues['order_bys'] = $orderBys;
3872 $formValues['order_bys'] = array(1 => array('column' => '-'));
3875 // assign show/hide data to template
3876 $_showHide->addToTemplate();
3880 * Check if table name has columns in SELECT clause.
3882 * @param string $tableName
3883 * Name of table (index of $this->_columns array).
3887 public function isTableSelected($tableName) {
3888 return in_array($tableName, $this->selectedTables());
3892 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3894 * If the array is unset it will be built.
3899 public function selectedTables() {
3900 if (!$this->_selectedTables
) {
3901 $orderByColumns = array();
3902 if (array_key_exists('order_bys', $this->_params
) &&
3903 is_array($this->_params
['order_bys'])
3905 foreach ($this->_params
['order_bys'] as $orderBy) {
3906 $orderByColumns[] = $orderBy['column'];
3910 foreach ($this->_columns
as $tableName => $table) {
3911 if (array_key_exists('fields', $table)) {
3912 foreach ($table['fields'] as $fieldName => $field) {
3913 if (!empty($field['required']) ||
3914 !empty($this->_params
['fields'][$fieldName])
3916 $this->_selectedTables
[] = $tableName;
3921 if (array_key_exists('order_bys', $table)) {
3922 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3923 if (in_array($orderByName, $orderByColumns)) {
3924 $this->_selectedTables
[] = $tableName;
3929 if (array_key_exists('filters', $table)) {
3930 foreach ($table['filters'] as $filterName => $filter) {
3931 if (!empty($this->_params
["{$filterName}_value"]) ||
3932 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3934 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3937 $this->_selectedTables
[] = $tableName;
3944 return $this->_selectedTables
;
3948 * Add address fields.
3950 * @deprecated - use getAddressColumns which is a more accurate description
3951 * and also accepts an array of options rather than a long list
3953 * adding address fields to construct function in reports
3955 * @param bool $groupBy
3956 * Add GroupBy? Not appropriate for detail report.
3957 * @param bool $orderBy
3958 * Add GroupBy? Not appropriate for detail report.
3959 * @param bool $filters
3960 * @param array $defaults
3963 * address fields for construct clause
3965 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3966 $addressFields = array(
3967 'civicrm_address' => array(
3968 'dao' => 'CRM_Core_DAO_Address',
3970 'address_name' => array(
3971 'title' => ts('Address Name'),
3972 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3975 'street_address' => array(
3976 'title' => ts('Street Address'),
3977 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3979 'supplemental_address_1' => array(
3980 'title' => ts('Supplementary Address Field 1'),
3981 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3983 'supplemental_address_2' => array(
3984 'title' => ts('Supplementary Address Field 2'),
3985 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3987 'street_number' => array(
3988 'name' => 'street_number',
3989 'title' => ts('Street Number'),
3991 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3993 'street_name' => array(
3994 'name' => 'street_name',
3995 'title' => ts('Street Name'),
3997 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3999 'street_unit' => array(
4000 'name' => 'street_unit',
4001 'title' => ts('Street Unit'),
4003 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
4006 'title' => ts('City'),
4007 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
4009 'postal_code' => array(
4010 'title' => ts('Postal Code'),
4011 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
4013 'postal_code_suffix' => array(
4014 'title' => ts('Postal Code Suffix'),
4015 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
4017 'country_id' => array(
4018 'title' => ts('Country'),
4019 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
4021 'state_province_id' => array(
4022 'title' => ts('State/Province'),
4023 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
4025 'county_id' => array(
4026 'title' => ts('County'),
4027 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
4030 'grouping' => 'location-fields',
4035 $addressFields['civicrm_address']['filters'] = array(
4036 'street_number' => array(
4037 'title' => ts('Street Number'),
4039 'name' => 'street_number',
4041 'street_name' => array(
4042 'title' => ts('Street Name'),
4043 'name' => 'street_name',
4044 'operator' => 'like',
4046 'postal_code' => array(
4047 'title' => ts('Postal Code'),
4049 'name' => 'postal_code',
4052 'title' => ts('City'),
4053 'operator' => 'like',
4056 'country_id' => array(
4057 'name' => 'country_id',
4058 'title' => ts('Country'),
4059 'type' => CRM_Utils_Type
::T_INT
,
4060 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4061 'options' => CRM_Core_PseudoConstant
::country(),
4063 'state_province_id' => array(
4064 'name' => 'state_province_id',
4065 'title' => ts('State/Province'),
4066 'type' => CRM_Utils_Type
::T_INT
,
4067 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4068 'options' => array(),
4070 'county_id' => array(
4071 'name' => 'county_id',
4072 'title' => ts('County'),
4073 'type' => CRM_Utils_Type
::T_INT
,
4074 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4075 'options' => array(),
4081 $addressFields['civicrm_address']['order_bys'] = array(
4082 'street_name' => array('title' => ts('Street Name')),
4083 'street_number' => array('title' => 'Odd / Even Street Number'),
4084 'street_address' => NULL,
4086 'postal_code' => NULL,
4091 $addressFields['civicrm_address']['group_bys'] = array(
4092 'street_address' => NULL,
4094 'postal_code' => NULL,
4095 'state_province_id' => array(
4096 'title' => ts('State/Province'),
4098 'country_id' => array(
4099 'title' => ts('Country'),
4101 'county_id' => array(
4102 'title' => ts('County'),
4106 return $addressFields;
4110 * Do AlterDisplay processing on Address Fields.
4113 * @param array $rows
4114 * @param int $rowNum
4115 * @param string $baseUrl
4116 * @param string $linkText
4120 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4121 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4122 $entryFound = FALSE;
4124 if (array_key_exists('civicrm_address_country_id', $row)) {
4125 if ($value = $row['civicrm_address_country_id']) {
4126 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4127 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4128 "reset=1&force=1&{$criteriaQueryParams}&" .
4129 "country_id_op=in&country_id_value={$value}",
4130 $this->_absoluteUrl
, $this->_id
4132 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4133 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4134 array(1 => $linkText)
4140 if (array_key_exists('civicrm_address_county_id', $row)) {
4141 if ($value = $row['civicrm_address_county_id']) {
4142 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4143 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4144 "reset=1&force=1&{$criteriaQueryParams}&" .
4145 "county_id_op=in&county_id_value={$value}",
4146 $this->_absoluteUrl
, $this->_id
4148 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4149 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4150 array(1 => $linkText)
4155 // handle state province
4156 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4157 if ($value = $row['civicrm_address_state_province_id']) {
4158 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4160 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4161 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4162 $this->_absoluteUrl
, $this->_id
4164 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4165 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4166 array(1 => $linkText)
4176 * Do AlterDisplay processing on Address Fields.
4179 * @param array $rows
4180 * @param int $rowNum
4181 * @param string $baseUrl
4182 * @param string $linkText
4186 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4187 $entryFound = FALSE;
4188 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4189 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4190 $addLinks = array('gender_id' => 'Gender');
4191 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4192 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4193 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4194 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4195 if (($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4196 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4206 * Adjusts dates passed in to YEAR() for fiscal year.
4208 * @param string $fieldName
4212 public function fiscalYearOffset($fieldName) {
4213 $config = CRM_Core_Config
::singleton();
4214 $fy = $config->fiscalYearStart
;
4215 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4216 ($fy['d'] == 1 && $fy['M'] == 1)
4218 return "YEAR( $fieldName )";
4220 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4221 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4225 * Add Address into From Table if required.
4227 public function addAddressFromClause() {
4228 // include address field if address column is to be included
4229 if ((isset($this->_addressField
) &&
4230 $this->_addressField
4232 $this->isTableSelected('civicrm_address')
4235 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4236 ON ({$this->_aliases['civicrm_contact']}.id =
4237 {$this->_aliases['civicrm_address']}.contact_id) AND
4238 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4243 * Add Phone into From Table if required.
4245 public function addPhoneFromClause() {
4246 // include address field if address column is to be included
4247 if ($this->isTableSelected('civicrm_phone')
4250 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4251 ON ({$this->_aliases['civicrm_contact']}.id =
4252 {$this->_aliases['civicrm_phone']}.contact_id) AND
4253 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4258 * Get phone columns to add to array.
4260 * @param array $options
4261 * - prefix Prefix to add to table (in case of more than one instance of the table)
4262 * - prefix_label Label to give columns from this phone table instance
4265 * phone columns definition
4267 public function getPhoneColumns($options = array()) {
4268 $defaultOptions = array(
4270 'prefix_label' => '',
4273 $options = array_merge($defaultOptions, $options);
4276 $options['prefix'] . 'civicrm_phone' => array(
4277 'dao' => 'CRM_Core_DAO_Phone',
4279 $options['prefix'] . 'phone' => array(
4280 'title' => ts($options['prefix_label'] . 'Phone'),
4290 * Get address columns to add to array.
4292 * @param array $options
4293 * - prefix Prefix to add to table (in case of more than one instance of the table)
4294 * - prefix_label Label to give columns from this address table instance
4297 * address columns definition
4299 public function getAddressColumns($options = array()) {
4302 'prefix_label' => '',
4306 'defaults' => array(),
4308 return $this->addAddressFields(
4309 $options['group_by'],
4310 $options['order_by'],
4311 $options['filters'],
4312 $options['defaults']
4317 * Get a standard set of contact fields.
4321 public function getBasicContactFields() {
4323 'sort_name' => array(
4324 'title' => ts('Contact Name'),
4329 'no_display' => TRUE,
4332 'prefix_id' => array(
4333 'title' => ts('Contact Prefix'),
4335 'first_name' => array(
4336 'title' => ts('First Name'),
4338 'nick_name' => array(
4339 'title' => ts('Nick Name'),
4341 'middle_name' => array(
4342 'title' => ts('Middle Name'),
4344 'last_name' => array(
4345 'title' => ts('Last Name'),
4347 'suffix_id' => array(
4348 'title' => ts('Contact Suffix'),
4350 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4351 'email_greeting_display' => array('title' => ts('Email Greeting')),
4352 'addressee_display' => array('title' => ts('Address Greeting')),
4353 'contact_type' => array(
4354 'title' => ts('Contact Type'),
4356 'contact_sub_type' => array(
4357 'title' => ts('Contact Subtype'),
4359 'gender_id' => array(
4360 'title' => ts('Gender'),
4362 'birth_date' => array(
4363 'title' => ts('Birth Date'),
4366 'title' => ts('Age'),
4367 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4369 'job_title' => array(
4370 'title' => ts('Contact Job title'),
4372 'organization_name' => array(
4373 'title' => ts('Organization Name'),
4375 'external_identifier' => array(
4376 'title' => ts('Contact identifier from external system'),
4382 * Add contact to group.
4384 * @param int $groupID
4386 public function add2group($groupID) {
4387 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4388 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4389 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4391 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4392 $sql = str_replace('WITH ROLLUP', '', $sql);
4393 $dao = CRM_Core_DAO
::executeQuery($sql);
4395 $contact_ids = array();
4396 // Add resulting contacts to group
4397 while ($dao->fetch()) {
4398 if ($dao->addtogroup_contact_id
) {
4399 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4403 if (!empty($contact_ids)) {
4404 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4405 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4408 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4414 * Show charts on print screen.
4416 public static function uploadChartImage() {
4417 // upload strictly for '.png' images
4418 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4419 if (preg_match('/\.png$/', $name)) {
4421 // POST data is usually string data, but we are passing a RAW .png
4422 // so PHP is a bit confused and $_POST is empty. But it has saved
4423 // the raw bits into $HTTP_RAW_POST_DATA
4425 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4427 // prepare the directory
4428 $config = CRM_Core_Config
::singleton();
4430 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4432 if (!file_exists($defaultPath)) {
4433 mkdir($defaultPath, 0777, TRUE);
4436 // full path to the saved image including filename
4437 $destination = $defaultPath . $name;
4440 $jfh = fopen($destination, 'w') or die("can't open file");
4441 fwrite($jfh, $httpRawPostData);
4443 CRM_Utils_System
::civiExit();
4448 * Apply common settings to entityRef fields.
4450 * @param array $field
4451 * @param string $table
4453 private function setEntityRefDefaults(&$field, $table) {
4454 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4455 $field['attributes'] +
= array(
4456 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4458 'placeholder' => ts('- select -'),
4463 * Add link fields to the row.
4465 * Function adds the _link & _hover fields to the row.
4468 * @param string $baseUrl
4469 * @param string $linkText
4470 * @param string $value
4471 * @param string $fieldName
4472 * @param string $tablePrefix
4473 * @param string $fieldLabel
4477 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4478 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4479 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4480 "reset=1&force=1&{$criteriaQueryParams}&" .
4481 $fieldName . "_op=in&{$fieldName}_value={$value}",
4482 $this->_absoluteUrl
, $this->_id
4484 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4485 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4486 array(1 => $linkText, 2 => $fieldLabel)