3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 protected $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * Array of tabs to display on report.
167 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
169 * $this->tabs['OrderBy'] = array(
170 * 'title' => ts('Sorting'),
171 * 'tpl' => 'OrderBy',
172 * 'div_label' => 'order-by',
177 protected $tabs = array();
180 * An attribute for checkbox/radio form field layout
184 protected $_fourColumnAttribute = array(
185 '</td><td width="25%">',
186 '</td><td width="25%">',
187 '</td><td width="25%">',
191 protected $_force = 1;
193 protected $_params = NULL;
194 protected $_formValues = NULL;
195 protected $_instanceValues = NULL;
197 protected $_instanceForm = FALSE;
198 protected $_criteriaForm = FALSE;
200 protected $_instanceButtonName = NULL;
201 protected $_createNewButtonName = NULL;
202 protected $_printButtonName = NULL;
203 protected $_pdfButtonName = NULL;
204 protected $_csvButtonName = NULL;
205 protected $_groupButtonName = NULL;
206 protected $_chartButtonName = NULL;
207 protected $_csvSupported = TRUE;
208 protected $_add2groupSupported = TRUE;
209 protected $_groups = NULL;
210 protected $_grandFlag = FALSE;
211 protected $_rowsFound = NULL;
212 protected $_selectAliases = array();
213 protected $_rollup = NULL;
218 protected $_aliases = array();
234 protected $_limit = NULL;
237 * This can be set to specify a limit to the number of rows
238 * Since it is currently envisaged as part of the api usage it is only being applied
239 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
240 * of the code (see limit() fn
243 protected $_limitValue = NULL;
246 * This can be set to specify row offset
247 * See notes on _limitValue
250 protected $_offsetValue = NULL;
254 protected $_sections = NULL;
255 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
256 protected $_absoluteUrl = FALSE;
259 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
263 protected $_storeResultSet = FALSE;
266 * When _storeResultSet Flag is set use this var to store result set in form of array
270 protected $_resultSet = array();
273 * To what frequency group-by a date column
277 protected $_groupByDateFreq = array(
279 'YEARWEEK' => 'Week',
280 'QUARTER' => 'Quarter',
285 * Variables to hold the acl inner join and where clause
287 protected $_aclFrom = NULL;
288 protected $_aclWhere = NULL;
291 * Array of DAO tables having columns included in SELECT or ORDER BY clause
295 protected $_selectedTables;
298 * Output mode e.g 'print', 'csv', 'pdf'
301 protected $_outputMode;
303 public $_having = NULL;
304 public $_select = NULL;
305 public $_selectClauses = array();
306 public $_columnHeaders = array();
307 public $_orderBy = NULL;
308 public $_orderByFields = array();
309 public $_orderByArray = array();
310 public $_groupBy = NULL;
311 public $_whereClauses = array();
312 public $_havingClauses = array();
315 * DashBoardRowCount Dashboard row count
318 public $_dashBoardRowCount;
321 * Is this being called without a form controller (ie. the report is being render outside the normal form
322 * - e.g the api is retrieving the rows
325 public $noController = FALSE;
328 * Variable to hold the currency alias
330 protected $_currencyColumn = NULL;
335 protected $_interval;
340 protected $_sendmail;
353 * @var string Report description.
355 public $_description;
358 * @var bool Is an address field selected.
359 * This was intended to determine if the address table should be joined in
360 * The isTableSelected function is now preferred for this purpose
362 protected $_addressField;
365 * @var bool Is an email field selected.
366 * This was intended to determine if the email table should be joined in
367 * The isTableSelected function is now preferred for this purpose
369 protected $_emailField;
372 * @var bool Is a phone field selected.
373 * This was intended to determine if the phone table should be joined in
374 * The isTableSelected function is now preferred for this purpose
376 protected $_phoneField;
379 * @var bool Create new report instance? (or update existing) on save.
381 protected $_createNew;
386 public function __construct() {
387 parent
::__construct();
389 $this->addClass('crm-report-form');
391 if ($this->_tagFilter
) {
392 $this->buildTagFilter();
394 if ($this->_exposeContactID
) {
395 if (array_key_exists('civicrm_contact', $this->_columns
)) {
396 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
398 'title' => 'Contact ID',
404 if ($this->_groupFilter
) {
405 $this->buildGroupFilter();
408 // Get all custom groups
409 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
411 // Get the custom groupIds for which the user has VIEW permission
412 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
413 // and addCustomDataToColumns() will allow access to all custom groups.
414 $permCustomGroupIds = array();
415 if (!CRM_Core_Permission
::check('access all custom data')) {
416 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
417 // do not allow custom data for reports if user doesn't have
418 // permission to access custom data.
419 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
420 $this->_customGroupExtends
= array();
424 // merge custom data columns to _columns list, if any
425 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
427 // add / modify display columns, filters ..etc
428 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
430 //assign currencyColumn variable to tpl
431 $this->assign('currencyColumn', $this->_currencyColumn
);
435 * Shared pre-process function.
437 * If overriding preProcess function this should still be called.
441 public function preProcessCommon() {
443 = CRM_Utils_Request
::retrieve(
446 CRM_Core_DAO
::$_nullObject
449 $this->_dashBoardRowCount
450 = CRM_Utils_Request
::retrieve(
453 CRM_Core_DAO
::$_nullObject
456 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
458 $this->assign('section', $this->_section
);
459 CRM_Core_Region
::instance('page-header')->add(array(
460 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
462 if (!$this->noController
) {
463 $this->setID($this->get('instanceId'));
466 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
468 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
472 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
473 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
474 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
478 $this->assign('instanceId', $this->_id
);
479 $params = array('id' => $this->_id
);
480 $this->_instanceValues
= array();
481 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
483 $this->_instanceValues
485 if (empty($this->_instanceValues
)) {
486 CRM_Core_Error
::fatal("Report could not be loaded.");
488 $this->_title
= $this->_instanceValues
['title'];
489 if (!empty($this->_instanceValues
['permission']) &&
490 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
491 CRM_Core_Permission
::check('administer Reports')
494 CRM_Utils_System
::permissionDenied();
495 CRM_Utils_System
::civiExit();
498 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
500 $this->_formValues
= unserialize($formValues);
503 $this->_formValues
= NULL;
506 // lets always do a force if reset is found in the url.
507 if (!empty($_REQUEST['reset'])) {
512 $this->assign('mode', 'instance');
514 elseif (!$this->noController
) {
515 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
516 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
517 if (($instanceCount > 0) && $optionValueID) {
518 $this->assign('instanceUrl',
519 CRM_Utils_System
::url('civicrm/report/list',
520 "reset=1&ovid=$optionValueID"
524 if ($optionValueID) {
525 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
529 $this->assign('mode', 'template');
532 // lets display the Report Settings section
533 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
535 // Do not display Report Settings section if administer Reports permission is absent OR
536 // if report instance is reserved and administer reserved reports absent
537 if (!CRM_Core_Permission
::check('administer Reports') ||
538 ($this->_instanceValues
['is_reserved'] &&
539 !CRM_Core_Permission
::check('administer reserved reports'))
541 $this->_instanceForm
= FALSE;
544 $this->assign('criteriaForm', FALSE);
545 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
546 if (CRM_Core_Permission
::check('administer Reports') ||
547 CRM_Core_Permission
::check('access Report Criteria')
549 if (!$this->_instanceValues
['is_reserved'] ||
550 CRM_Core_Permission
::check('administer reserved reports')
552 $this->assign('criteriaForm', TRUE);
553 $this->_criteriaForm
= TRUE;
557 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
558 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
559 $this->_printButtonName
= $this->getButtonName('submit', 'print');
560 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
561 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
562 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
563 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
569 public function addBreadCrumb() {
573 'title' => ts('Report Templates'),
574 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
578 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
582 * Pre process function.
584 * Called prior to build form.
586 public function preProcess() {
587 $this->preProcessCommon();
590 $this->addBreadCrumb();
593 foreach ($this->_columns
as $tableName => $table) {
595 if (!isset($table['alias'])) {
596 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
600 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
603 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
605 $daoOrBaoName = NULL;
606 // higher preference to bao object
607 if (array_key_exists('bao', $table)) {
608 $daoOrBaoName = $table['bao'];
609 $expFields = $daoOrBaoName::exportableFields();
611 elseif (array_key_exists('dao', $table)) {
612 $daoOrBaoName = $table['dao'];
613 $expFields = $daoOrBaoName::export();
616 $expFields = array();
619 $doNotCopy = array('required');
621 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
622 foreach ($fieldGroups as $fieldGrp) {
623 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
624 foreach ($table[$fieldGrp] as $fieldName => $field) {
625 // $name is the field name used to reference the BAO/DAO export fields array
626 $name = isset($field['name']) ?
$field['name'] : $fieldName;
628 // Sometimes the field name key in the BAO/DAO export fields array is
629 // different from the actual database field name.
630 // Unset $field['name'] so that actual database field name can be obtained
631 // from the BAO/DAO export fields array.
632 unset($field['name']);
634 if (array_key_exists($name, $expFields)) {
635 foreach ($doNotCopy as $dnc) {
636 // unset the values we don't want to be copied.
637 unset($expFields[$name][$dnc]);
640 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
643 foreach ($expFields[$name] as $property => $val) {
644 if (!array_key_exists($property, $field)) {
645 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
652 if (!empty($field['no_repeat'])) {
653 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
655 if (!empty($field['no_display'])) {
656 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
659 // set alias = table-name, unless already set
660 $alias = isset($field['alias']) ?
$field['alias'] : (
661 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
663 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
665 // set name = fieldName, unless already set
666 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
667 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
670 // set dbAlias = alias.name, unless already set
671 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
672 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
674 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
677 // a few auto fills for filters
678 if ($fieldGrp == 'filters') {
679 // fill operator types
680 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
681 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
682 case CRM_Utils_Type
::T_MONEY
:
683 case CRM_Utils_Type
::T_FLOAT
:
684 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
687 case CRM_Utils_Type
::T_INT
:
688 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
691 case CRM_Utils_Type
::T_DATE
:
692 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
695 case CRM_Utils_Type
::T_BOOLEAN
:
696 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
697 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
698 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
709 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
711 // with multiple options operator-type is generally multi-select
712 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
713 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
715 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
726 // copy filters to a separate handy variable
727 if (array_key_exists('filters', $table)) {
728 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
731 if (array_key_exists('group_bys', $table)) {
732 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
735 if (array_key_exists('fields', $table)) {
736 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
741 $this->setDefaultValues(FALSE);
744 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
745 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
746 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
747 CRM_Report_Utils_Get
::processChart($this->_defaults
);
750 $this->_formValues
= $this->_defaults
;
751 $this->postProcess();
756 * Set default values.
758 * @param bool $freeze
762 public function setDefaultValues($freeze = TRUE) {
763 $freezeGroup = array();
765 // FIXME: generalizing form field naming conventions would reduce
766 // Lots of lines below.
767 foreach ($this->_columns
as $tableName => $table) {
768 if (array_key_exists('fields', $table)) {
769 foreach ($table['fields'] as $fieldName => $field) {
770 if (empty($field['no_display'])) {
771 if (isset($field['required'])) {
773 $this->_defaults
['fields'][$fieldName] = 1;
776 // find element object, so that we could use quickform's freeze method
777 // for required elements
778 $obj = $this->getElementFromGroup("fields", $fieldName);
780 $freezeGroup[] = $obj;
784 elseif (isset($field['default'])) {
785 $this->_defaults
['fields'][$fieldName] = $field['default'];
791 if (array_key_exists('group_bys', $table)) {
792 foreach ($table['group_bys'] as $fieldName => $field) {
793 if (isset($field['default'])) {
794 if (!empty($field['frequency'])) {
795 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
797 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
801 if (array_key_exists('filters', $table)) {
802 foreach ($table['filters'] as $fieldName => $field) {
803 if (isset($field['default'])) {
804 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
806 if (is_array($field['default'])) {
807 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
808 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
809 $this->_defaults
["{$fieldName}_relative"] = 0;
812 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
816 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
817 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
818 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
820 $this->_defaults
["{$fieldName}_value"] = $field['default'];
823 //assign default value as "in" for multiselect
824 //operator, To freeze the select element
825 if (CRM_Utils_Array
::value('operatorType', $field) ==
826 CRM_Report_Form
::OP_MULTISELECT
828 $this->_defaults
["{$fieldName}_op"] = 'in';
830 if (CRM_Utils_Array
::value('operatorType', $field) ==
831 CRM_Report_Form
::OP_ENTITYREF
833 $this->_defaults
["{$fieldName}_op"] = 'in';
835 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
836 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
838 $this->_defaults
["{$fieldName}_op"] = 'mhas';
840 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
841 $this->_defaults
["{$fieldName}_op"] = $op;
847 empty($this->_formValues
['order_bys']) &&
848 (array_key_exists('order_bys', $table) &&
849 is_array($table['order_bys']))
851 if (!array_key_exists('order_bys', $this->_defaults
)) {
852 $this->_defaults
['order_bys'] = array();
854 foreach ($table['order_bys'] as $fieldName => $field) {
855 if (!empty($field['default']) ||
!empty($field['default_order']) ||
856 CRM_Utils_Array
::value('default_is_section', $field) ||
857 !empty($field['default_weight'])
860 'column' => $fieldName,
861 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
862 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
865 if (!empty($field['default_weight'])) {
866 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
869 array_unshift($this->_defaults
['order_bys'], $order_by);
875 foreach ($this->_options
as $fieldName => $field) {
876 if (isset($field['default'])) {
877 $this->_defaults
['options'][$fieldName] = $field['default'];
882 if (!empty($this->_submitValues
)) {
883 $this->preProcessOrderBy($this->_submitValues
);
886 $this->preProcessOrderBy($this->_defaults
);
889 // lets finish freezing task here itself
890 if (!empty($freezeGroup)) {
891 foreach ($freezeGroup as $elem) {
896 if ($this->_formValues
) {
897 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
900 if ($this->_instanceValues
) {
901 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
904 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
906 return $this->_defaults
;
910 * Get element from group.
912 * @param string $group
913 * @param string $grpFieldName
917 public function getElementFromGroup($group, $grpFieldName) {
918 $eleObj = $this->getElement($group);
919 foreach ($eleObj->_elements
as $index => $obj) {
920 if ($grpFieldName == $obj->_attributes
['name']) {
928 * Setter for $_params.
930 * @param array $params
932 public function setParams($params) {
933 $this->_params
= $params;
939 * @param int $instanceID
941 public function setID($instanceID) {
942 $this->_id
= $instanceID;
946 * Setter for $_force.
948 * @param bool $isForce
950 public function setForce($isForce) {
951 $this->_force
= $isForce;
955 * Setter for $_limitValue.
957 * @param int $_limitValue
959 public function setLimitValue($_limitValue) {
960 $this->_limitValue
= $_limitValue;
964 * Setter for $_offsetValue.
966 * @param int $_offsetValue
968 public function setOffsetValue($_offsetValue) {
969 $this->_offsetValue
= $_offsetValue;
973 * Getter for $_defaultValues.
977 public function getDefaultValues() {
978 return $this->_defaults
;
982 * Add columns to report.
984 public function addColumns() {
987 foreach ($this->_columns
as $tableName => $table) {
988 if (array_key_exists('fields', $table)) {
989 foreach ($table['fields'] as $fieldName => $field) {
991 if (empty($field['no_display'])) {
992 foreach (array('table', 'field') as $var) {
993 if (!empty($
{$var}['grouping'])) {
994 if (!is_array($
{$var}['grouping'])) {
995 $tableName = $
{$var}['grouping'];
998 $tableName = array_keys($
{$var}['grouping']);
999 $tableName = $tableName[0];
1000 $groupTitle = array_values($
{$var}['grouping']);
1001 $groupTitle = $groupTitle[0];
1006 if (!$groupTitle && isset($table['group_title'])) {
1007 $groupTitle = $table['group_title'];
1008 // Having a group_title is secret code for being a custom group
1009 // which cryptically translates to needing an accordion.
1010 // here we make that explicit.
1011 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1014 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1015 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1016 $colGroups[$tableName]['group_title'] = $groupTitle;
1018 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1024 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1025 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1027 if (!empty($colGroups)) {
1028 $this->tabs
['FieldSelection'] = array(
1029 'title' => ts('Columns'),
1030 'tpl' => 'FieldSelection',
1031 'div_label' => 'col-groups',
1034 // Note this assignment is only really required in buildForm. It is being 'over-called'
1035 // to reduce risk of being missed due to overridden functions.
1036 $this->assign('tabs', $this->tabs
);
1039 $this->assign('colGroups', $colGroups);
1043 * Add filters to report.
1045 public function addFilters() {
1046 $filters = $filterGroups = array();
1049 foreach ($this->_filters
as $table => $attributes) {
1050 if (isset($this->_columns
[$table]['group_title'])) {
1051 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1052 // which magically means to 'display in an accordian'
1053 // here we make this explicit.
1054 $filterGroups[$table] = array(
1055 'group_title' => $this->_columns
[$table]['group_title'],
1056 'use_accordian_for_field_selection' => TRUE,
1060 foreach ($attributes as $fieldName => $field) {
1061 // get ready with option value pair
1062 // @ 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
1064 $operations = $this->getOperationPair(
1065 CRM_Utils_Array
::value('operatorType', $field),
1068 $filters[$table][$fieldName] = $field;
1070 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1071 case CRM_Report_Form
::OP_MONTH
:
1072 if (!array_key_exists('options', $field) ||
1073 !is_array($field['options']) ||
empty($field['options'])
1075 // If there's no option list for this filter, define one.
1076 $field['options'] = array(
1078 2 => ts('February'),
1085 9 => ts('September'),
1086 10 => ts('October'),
1087 11 => ts('November'),
1088 12 => ts('December'),
1090 // Add this option list to this column _columns. This is
1091 // required so that filter statistics show properly.
1092 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1094 case CRM_Report_Form
::OP_MULTISELECT
:
1095 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1096 // assume a multi-select field
1097 if (!empty($field['options']) ||
1098 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1100 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1101 if (count($operations) <= 1) {
1104 if ($fieldName == 'state_province_id' ||
1105 $fieldName == 'county_id'
1107 $this->addChainSelect($fieldName . '_value', array(
1114 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1115 'style' => 'min-width:250px',
1116 'class' => 'crm-select2 huge',
1118 'placeholder' => ts('- select -'),
1124 case CRM_Report_Form
::OP_SELECT
:
1125 // assume a select field
1126 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1127 if (!empty($field['options'])) {
1128 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1132 case CRM_Report_Form
::OP_ENTITYREF
:
1133 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1134 $this->setEntityRefDefaults($field, $table);
1135 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1138 case CRM_Report_Form
::OP_DATE
:
1139 // build datetime fields
1140 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1144 case CRM_Report_Form
::OP_DATETIME
:
1145 // build datetime fields
1146 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1150 case CRM_Report_Form
::OP_INT
:
1151 case CRM_Report_Form
::OP_FLOAT
:
1152 // and a min value input box
1153 $this->add('text', "{$fieldName}_min", ts('Min'));
1154 // and a max value input box
1155 $this->add('text', "{$fieldName}_max", ts('Max'));
1157 // default type is string
1158 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1159 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1161 // we need text box for value input
1162 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1167 if (!empty($filters)) {
1168 $this->tabs
['Filters'] = array(
1169 'title' => ts('Filters'),
1171 'div_label' => 'set-filters',
1174 $this->assign('filters', $filters);
1175 $this->assign('filterGroups', $filterGroups);
1179 * Function to assign the tabs to the template in the correct order.
1181 * We want the tabs to wind up in this order (if not overridden).
1189 protected function assignTabs() {
1197 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1198 $order = array_merge($order, $this->tabs
);
1199 $this->assign('tabs', $order);
1203 * Add options defined in $this->_options to the report.
1205 public function addOptions() {
1206 if (!empty($this->_options
)) {
1207 // FIXME: For now lets build all elements as checkboxes.
1208 // Once we clear with the format we can build elements based on type
1210 foreach ($this->_options
as $fieldName => $field) {
1213 if ($field['type'] == 'select') {
1214 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1216 elseif ($field['type'] == 'checkbox') {
1217 $options[$field['title']] = $fieldName;
1218 $this->addCheckBox($fieldName, NULL,
1220 NULL, NULL, NULL, $this->_fourColumnAttribute
1225 if (!empty($this->_options
)) {
1226 $this->tabs
['ReportOptions'] = array(
1227 'title' => ts('Display Options'),
1228 'tpl' => 'ReportOptions',
1229 'div_label' => 'other-options',
1232 $this->assign('otherOptions', $this->_options
);
1236 * Add chart options to the report.
1238 public function addChartOptions() {
1239 if (!empty($this->_charts
)) {
1240 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1241 $this->assign('charts', $this->_charts
);
1242 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1247 * Add group by options to the report.
1249 public function addGroupBys() {
1250 $options = $freqElements = array();
1252 foreach ($this->_columns
as $tableName => $table) {
1253 if (array_key_exists('group_bys', $table)) {
1254 foreach ($table['group_bys'] as $fieldName => $field) {
1255 if (!empty($field)) {
1256 $options[$field['title']] = $fieldName;
1257 if (!empty($field['frequency'])) {
1258 $freqElements[$field['title']] = $fieldName;
1264 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1265 NULL, NULL, NULL, $this->_fourColumnAttribute
1267 $this->assign('groupByElements', $options);
1268 if (!empty($options)) {
1269 $this->tabs
['GroupBy'] = array(
1270 'title' => ts('Grouping'),
1272 'div_label' => 'group-by-elements',
1276 foreach ($freqElements as $name) {
1277 $this->addElement('select', "group_bys_freq[$name]",
1278 ts('Frequency'), $this->_groupByDateFreq
1284 * Add data for order by tab.
1286 public function addOrderBys() {
1288 foreach ($this->_columns
as $tableName => $table) {
1290 // Report developer may define any column to order by; include these as order-by options.
1291 if (array_key_exists('order_bys', $table)) {
1292 foreach ($table['order_bys'] as $fieldName => $field) {
1293 if (!empty($field)) {
1294 $options[$fieldName] = $field['title'];
1299 // Add searchable custom fields as order-by options, if so requested
1300 // (These are already indexed, so allowing to order on them is cheap.)
1302 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1303 array_key_exists('extends', $table) && !empty($table['extends'])
1305 foreach ($table['fields'] as $fieldName => $field) {
1306 if (empty($field['no_display'])) {
1307 $options[$fieldName] = $field['title'];
1315 $this->assign('orderByOptions', $options);
1316 if (!empty($options)) {
1317 $this->tabs
['OrderBy'] = array(
1318 'title' => ts('Sorting'),
1320 'div_label' => 'order-by-elements',
1324 if (!empty($options)) {
1326 '-' => ' - none - ',
1328 for ($i = 1; $i <= 5; $i++
) {
1329 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1330 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1331 'ASC' => 'Ascending',
1332 'DESC' => 'Descending',
1334 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1335 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1341 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1343 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1344 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1347 public function buildInstanceAndButtons() {
1348 CRM_Report_Form_Instance
::buildForm($this);
1350 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1352 $this->addElement('submit', $this->_instanceButtonName
, $label);
1353 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1354 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1357 $this->addElement('submit', $this->_createNewButtonName
,
1358 ts('Save a Copy') . '...');
1360 $this->assign('instanceForm', $this->_instanceForm
);
1362 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1363 $this->addElement('submit', $this->_printButtonName
, $label);
1365 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1366 $this->addElement('submit', $this->_pdfButtonName
, $label);
1368 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1370 if ($this->_csvSupported
) {
1371 $this->addElement('submit', $this->_csvButtonName
, $label);
1374 if (CRM_Core_Permission
::check('administer Reports') &&
1375 $this->_add2groupSupported
1377 $this->addElement('select', 'groups', ts('Group'),
1378 array('' => ts('Add Contacts to Group')) +
1379 CRM_Core_PseudoConstant
::nestedGroup(),
1380 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
1382 $this->assign('group', TRUE);
1385 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1387 $this->addChartOptions();
1388 $this->addButtons(array(
1391 'name' => ts('Preview Report'),
1392 'isDefault' => TRUE,
1399 * Main build form function.
1401 public function buildQuickForm() {
1402 $this->addColumns();
1404 $this->addFilters();
1406 $this->addOptions();
1408 $this->addGroupBys();
1410 $this->addOrderBys();
1412 $this->buildInstanceAndButtons();
1414 // Add form rule for report.
1415 if (is_callable(array(
1419 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1421 $this->assignTabs();
1425 * A form rule function for custom data.
1427 * The rule ensures that fields selected in group_by if any) should only be the ones
1428 * present in display/select fields criteria;
1429 * note: works if and only if any custom field selected in group_by.
1431 * @param array $fields
1432 * @param array $ignoreFields
1436 public function customDataFormRule($fields, $ignoreFields = array()) {
1438 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1439 !empty($fields['group_bys'])
1441 foreach ($this->_columns
as $tableName => $table) {
1442 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1443 substr($tableName, 0, 12) == 'custom_value') &&
1444 !empty($this->_columns
[$tableName]['fields'])
1446 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1447 if (array_key_exists($fieldName, $fields['group_bys']) &&
1448 !array_key_exists($fieldName, $fields['fields'])
1450 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1452 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1453 foreach ($fields['fields'] as $fld => $val) {
1454 if (!array_key_exists($fld, $fields['group_bys']) &&
1455 !in_array($fld, $ignoreFields)
1457 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1469 * Get operators to display on form.
1471 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1473 * @param string $type
1474 * @param string $fieldName
1478 public function getOperationPair($type = "string", $fieldName = NULL) {
1479 // FIXME: At some point we should move these key-val pairs
1480 // to option_group and option_value table.
1482 case CRM_Report_Form
::OP_INT
:
1483 case CRM_Report_Form
::OP_FLOAT
:
1486 'lte' => ts('Is less than or equal to'),
1487 'gte' => ts('Is greater than or equal to'),
1488 'bw' => ts('Is between'),
1489 'eq' => ts('Is equal to'),
1490 'lt' => ts('Is less than'),
1491 'gt' => ts('Is greater than'),
1492 'neq' => ts('Is not equal to'),
1493 'nbw' => ts('Is not between'),
1494 'nll' => ts('Is empty (Null)'),
1495 'nnll' => ts('Is not empty (Null)'),
1499 case CRM_Report_Form
::OP_SELECT
:
1501 'eq' => ts('Is equal to'),
1505 case CRM_Report_Form
::OP_MONTH
:
1506 case CRM_Report_Form
::OP_MULTISELECT
:
1507 case CRM_Report_Form
::OP_ENTITYREF
:
1510 'in' => ts('Is one of'),
1511 'notin' => ts('Is not one of'),
1515 case CRM_Report_Form
::OP_DATE
:
1518 'nll' => ts('Is empty (Null)'),
1519 'nnll' => ts('Is not empty (Null)'),
1523 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1524 // use this operator for the values, concatenated with separator. For e.g if
1525 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1527 'mhas' => ts('Is one of'),
1528 'mnot' => ts('Is not one of'),
1535 'has' => ts('Contains'),
1536 'sw' => ts('Starts with'),
1537 'ew' => ts('Ends with'),
1538 'nhas' => ts('Does not contain'),
1539 'eq' => ts('Is equal to'),
1540 'neq' => ts('Is not equal to'),
1541 'nll' => ts('Is empty (Null)'),
1542 'nnll' => ts('Is not empty (Null)'),
1549 * Build the tag filter field to display on the filters tab.
1551 public function buildTagFilter() {
1552 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1553 if (!empty($contactTags)) {
1554 $this->_columns
['civicrm_tag'] = array(
1555 'dao' => 'CRM_Core_DAO_Tag',
1559 'title' => ts('Tag'),
1561 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1562 'options' => $contactTags,
1570 * Adds group filters to _columns (called from _Construct).
1572 public function buildGroupFilter() {
1573 $this->_columns
['civicrm_group']['filters'] = array(
1575 'name' => 'group_id',
1576 'title' => ts('Group'),
1577 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1579 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1582 if (empty($this->_columns
['civicrm_group']['dao'])) {
1583 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1585 if (empty($this->_columns
['civicrm_group']['alias'])) {
1586 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1591 * Get SQL operator from form text version.
1593 * @param string $operator
1597 public function getSQLOperator($operator = "like") {
1598 switch ($operator) {
1631 return 'IS NOT NULL';
1640 * Generate where clause.
1642 * This can be overridden in reports for special treatment of a field
1644 * @param array $field Field specifications
1645 * @param string $op Query operator (not an exact match to sql)
1646 * @param mixed $value
1650 * @return null|string
1652 public function whereClause(&$field, $op, $value, $min, $max) {
1654 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1660 if (($min !== NULL && strlen($min) > 0) ||
1661 ($max !== NULL && strlen($max) > 0)
1663 $min = CRM_Utils_Type
::escape($min, $type);
1664 $max = CRM_Utils_Type
::escape($max, $type);
1668 $clauses[] = "( {$field['dbAlias']} >= $min )";
1671 $clauses[] = "( {$field['dbAlias']} < $min )";
1676 $clauses[] = "( {$field['dbAlias']} <= $max )";
1679 $clauses[] = "( {$field['dbAlias']} > $max )";
1683 if (!empty($clauses)) {
1685 $clause = implode(' AND ', $clauses);
1688 $clause = implode(' OR ', $clauses);
1696 if ($value !== NULL && strlen($value) > 0) {
1697 $value = CRM_Utils_Type
::escape($value, $type);
1698 if (strpos($value, '%') === FALSE) {
1699 $value = "'%{$value}%'";
1702 $value = "'{$value}'";
1704 $sqlOP = $this->getSQLOperator($op);
1705 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1711 if (is_string($value) && strlen($value)) {
1712 $value = explode(',', $value);
1714 if ($value !== NULL && is_array($value) && count($value) > 0) {
1715 $sqlOP = $this->getSQLOperator($op);
1716 if (CRM_Utils_Array
::value('type', $field) ==
1717 CRM_Utils_Type
::T_STRING
1719 //cycle through selections and escape values
1720 foreach ($value as $key => $selection) {
1721 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1724 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1728 // for numerical values
1729 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1732 if ($op == 'notin') {
1733 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1736 $clause = "( " . $clause . " )";
1742 // mhas == multiple has
1743 if ($value !== NULL && count($value) > 0) {
1744 $sqlOP = $this->getSQLOperator($op);
1746 = "{$field['dbAlias']} REGEXP '[[:cntrl:]]" . implode('|', $value) .
1752 // mnot == multiple is not one of
1753 if ($value !== NULL && count($value) > 0) {
1754 $sqlOP = $this->getSQLOperator($op);
1756 = "( {$field['dbAlias']} NOT REGEXP '[[:cntrl:]]" . implode('|', $value) .
1757 "[[:cntrl:]]' OR {$field['dbAlias']} IS NULL )";
1763 if ($value !== NULL && strlen($value) > 0) {
1764 $value = CRM_Utils_Type
::escape($value, $type);
1765 if (strpos($value, '%') === FALSE) {
1767 $value = "'{$value}%'";
1770 $value = "'%{$value}'";
1774 $value = "'{$value}'";
1776 $sqlOP = $this->getSQLOperator($op);
1777 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1783 $sqlOP = $this->getSQLOperator($op);
1784 $clause = "( {$field['dbAlias']} $sqlOP )";
1788 if ($value !== NULL && strlen($value) > 0) {
1789 if (isset($field['clause'])) {
1790 // FIXME: we not doing escape here. Better solution is to use two
1791 // different types - data-type and filter-type
1792 $clause = $field['clause'];
1795 $value = CRM_Utils_Type
::escape($value, $type);
1796 $sqlOP = $this->getSQLOperator($op);
1797 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1798 $value = "'{$value}'";
1800 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1806 if (!empty($field['group']) && $clause) {
1807 $clause = $this->whereGroupClause($field, $value, $op);
1809 elseif (!empty($field['tag']) && $clause) {
1810 // not using left join in query because if any contact
1811 // belongs to more than one tag, results duplicate
1813 $clause = $this->whereTagClause($field, $value, $op);
1815 elseif (!empty($field['membership_org']) && $clause) {
1816 $clause = $this->whereMembershipOrgClause($value, $op);
1818 elseif (!empty($field['membership_type']) && $clause) {
1819 $clause = $this->whereMembershipTypeClause($value, $op);
1825 * Get SQL where clause for a date field.
1827 * @param string $fieldName
1828 * @param string $relative
1829 * @param string $from
1831 * @param string $type
1832 * @param string $fromTime
1833 * @param string $toTime
1835 * @return null|string
1837 public function dateClause(
1839 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1842 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1843 $sqlOP = $this->getSQLOperator($relative);
1844 return "( {$fieldName} {$sqlOP} )";
1847 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1850 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1851 $clauses[] = "( {$fieldName} >= $from )";
1855 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1856 $clauses[] = "( {$fieldName} <= {$to} )";
1859 if (!empty($clauses)) {
1860 return implode(' AND ', $clauses);
1867 * Possibly unused function.
1869 * @todo - could not find any instances where this is called
1871 * @param bool $relative
1872 * @param string $from
1875 * @return string|NULL
1877 public function dateDisplay($relative, $from, $to) {
1878 list($from, $to) = $this->getFromTo($relative, $from, $to);
1881 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1884 $clauses[] = 'Past';
1888 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1891 $clauses[] = 'Today';
1894 if (!empty($clauses)) {
1895 return implode(' - ', $clauses);
1902 * Get values for from and to for date ranges.
1904 * @param bool $relative
1905 * @param string $from
1907 * @param string $fromTime
1908 * @param string $toTime
1912 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1913 if (empty($toTime)) {
1916 //FIX ME not working for relative
1918 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1919 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1920 $from = substr($dateRange['from'], 0, 8);
1921 //Take only Date Part, Sometime Time part is also present in 'to'
1922 $to = substr($dateRange['to'], 0, 8);
1924 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1925 $to = CRM_Utils_Date
::processDate($to, $toTime);
1926 return array($from, $to);
1930 * Alter display of rows.
1932 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1933 * such as rendering contacts as links.
1935 * @param array $rows
1936 * Rows generated by SQL, with an array for each row.
1938 public function alterDisplay(&$rows) {
1942 * Alter the way in which custom data fields are displayed.
1944 * @param array $rows
1946 public function alterCustomDataDisplay(&$rows) {
1947 // custom code to alter rows having custom values
1948 if (empty($this->_customGroupExtends
)) {
1952 $customFieldIds = array();
1953 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1954 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1955 $customFieldIds[$fieldAlias] = $fieldId;
1958 if (empty($customFieldIds)) {
1962 $customFields = $fieldValueMap = array();
1963 $customFieldCols = array(
1971 // skip for type date and ContactReference since date format is already handled
1973 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1974 FROM civicrm_custom_field cf
1975 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1976 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1977 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1978 cg.is_active = 1 AND
1979 cf.is_active = 1 AND
1980 cf.is_searchable = 1 AND
1981 cf.data_type NOT IN ('ContactReference', 'Date') AND
1982 cf.id IN (" . implode(",", $customFieldIds) . ")";
1984 $dao = CRM_Core_DAO
::executeQuery($query);
1985 while ($dao->fetch()) {
1986 foreach ($customFieldCols as $key) {
1987 $customFields[$dao->table_name
. '_custom_' .
1988 $dao->id
][$key] = $dao->$key;
1990 if ($dao->option_group_id
) {
1991 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1996 $entryFound = FALSE;
1997 foreach ($rows as $rowNum => $row) {
1998 foreach ($row as $tableCol => $val) {
1999 if (array_key_exists($tableCol, $customFields)) {
2000 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
2005 // skip looking further in rows, if first row itself doesn't
2006 // have the column we need
2014 * Format custom values.
2016 * @param mixed $value
2017 * @param array $customField
2018 * @param array $fieldValueMap
2020 * @return float|string|void
2022 public function formatCustomValues($value, $customField, $fieldValueMap) {
2023 if (CRM_Utils_System
::isNull($value)) {
2027 $htmlType = $customField['html_type'];
2029 switch ($customField['data_type']) {
2031 if ($value == '1') {
2032 $retValue = ts('Yes');
2035 $retValue = ts('No');
2040 $retValue = CRM_Utils_System
::formatWikiURL($value);
2052 if ($htmlType == 'Text') {
2053 $retValue = (float) $value;
2057 if ($htmlType == 'Text') {
2058 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2063 if (in_array($htmlType, array(
2070 case 'StateProvince':
2073 switch ($htmlType) {
2074 case 'Multi-Select Country':
2075 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2076 $customData = array();
2077 foreach ($value as $val) {
2079 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
2082 $retValue = implode(', ', $customData);
2085 case 'Select Country':
2086 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
2089 case 'Select State/Province':
2090 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2093 case 'Multi-Select State/Province':
2094 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2095 $customData = array();
2096 foreach ($value as $val) {
2098 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
2101 $retValue = implode(', ', $customData);
2106 case 'Autocomplete-Select':
2107 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2111 case 'AdvMulti-Select':
2112 case 'Multi-Select':
2113 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2114 $customData = array();
2115 foreach ($value as $val) {
2117 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2120 $retValue = implode(', ', $customData);
2136 * Remove duplicate rows.
2138 * @param array $rows
2140 public function removeDuplicates(&$rows) {
2141 if (empty($this->_noRepeats
)) {
2144 $checkList = array();
2146 foreach ($rows as $key => $list) {
2147 foreach ($list as $colName => $colVal) {
2148 if (array_key_exists($colName, $checkList) &&
2149 $checkList[$colName] == $colVal
2151 $rows[$key][$colName] = "";
2153 if (in_array($colName, $this->_noRepeats
)) {
2154 $checkList[$colName] = $colVal;
2161 * Fix subtotal display.
2164 * @param array $fields
2165 * @param bool $subtotal
2167 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2168 foreach ($row as $colName => $colVal) {
2169 if (in_array($colName, $fields)) {
2171 elseif (isset($this->_columnHeaders
[$colName])) {
2173 $row[$colName] = "Subtotal";
2177 unset($row[$colName]);
2184 * Calculate grant total.
2186 * @param array $rows
2190 public function grandTotal(&$rows) {
2191 if (!$this->_rollup ||
($this->_rollup
== '') ||
2192 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2196 $lastRow = array_pop($rows);
2198 foreach ($this->_columnHeaders
as $fld => $val) {
2199 if (!in_array($fld, $this->_statFields
)) {
2200 if (!$this->_grandFlag
) {
2201 $lastRow[$fld] = "Grand Total";
2202 $this->_grandFlag
= TRUE;
2205 $lastRow[$fld] = "";
2210 $this->assign('grandStat', $lastRow);
2215 * Format display output.
2217 * @param array $rows
2218 * @param bool $pager
2220 public function formatDisplay(&$rows, $pager = TRUE) {
2221 // set pager based on if any limit was applied in the query.
2226 // allow building charts if any
2227 if (!empty($this->_params
['charts']) && !empty($rows)) {
2228 $this->buildChart($rows);
2229 $this->assign('chartEnabled', TRUE);
2230 $this->_chartId
= "{$this->_params['charts']}_" .
2231 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2233 $this->assign('chartId', $this->_chartId
);
2236 // unset columns not to be displayed.
2237 foreach ($this->_columnHeaders
as $key => $value) {
2238 if (!empty($value['no_display'])) {
2239 unset($this->_columnHeaders
[$key]);
2243 // unset columns not to be displayed.
2244 if (!empty($rows)) {
2245 foreach ($this->_noDisplay
as $noDisplayField) {
2246 foreach ($rows as $rowNum => $row) {
2247 unset($this->_columnHeaders
[$noDisplayField]);
2252 // build array of section totals
2253 $this->sectionTotals();
2255 // process grand-total row
2256 $this->grandTotal($rows);
2258 // use this method for formatting rows for display purpose.
2259 $this->alterDisplay($rows);
2260 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2262 // use this method for formatting custom rows for display purpose.
2263 $this->alterCustomDataDisplay($rows);
2269 * @param array $rows
2271 public function buildChart(&$rows) {
2272 // override this method for building charts.
2275 // select() method below has been added recently (v3.3), and many of the report templates might
2276 // still be having their own select() method. We should fix them as and when encountered and move
2277 // towards generalizing the select() method below.
2280 * Generate the SELECT clause and set class variable $_select.
2282 public function select() {
2283 $select = $this->_selectAliases
= array();
2285 foreach ($this->_columns
as $tableName => $table) {
2286 if (array_key_exists('fields', $table)) {
2287 foreach ($table['fields'] as $fieldName => $field) {
2288 if ($tableName == 'civicrm_address') {
2289 $this->_addressField
= TRUE;
2291 if ($tableName == 'civicrm_email') {
2292 $this->_emailField
= TRUE;
2294 if ($tableName == 'civicrm_phone') {
2295 $this->_phoneField
= TRUE;
2298 if (!empty($field['required']) ||
2299 !empty($this->_params
['fields'][$fieldName])
2302 // 1. In many cases we want select clause to be built in slightly different way
2303 // for a particular field of a particular type.
2304 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2306 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2307 if ($selectClause) {
2308 $select[] = $selectClause;
2312 // include statistics columns only if set
2313 if (!empty($field['statistics'])) {
2314 foreach ($field['statistics'] as $stat => $label) {
2315 $alias = "{$tableName}_{$fieldName}_{$stat}";
2316 switch (strtolower($stat)) {
2319 $select[] = "$stat({$field['dbAlias']}) as $alias";
2320 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2321 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2322 $this->_statFields
[$label] = $alias;
2323 $this->_selectAliases
[] = $alias;
2327 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2328 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2329 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2330 $this->_statFields
[$label] = $alias;
2331 $this->_selectAliases
[] = $alias;
2334 case 'count_distinct':
2335 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2336 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2337 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2338 $this->_statFields
[$label] = $alias;
2339 $this->_selectAliases
[] = $alias;
2343 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2344 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2345 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2346 $this->_statFields
[$label] = $alias;
2347 $this->_selectAliases
[] = $alias;
2353 $alias = "{$tableName}_{$fieldName}";
2354 $select[] = "{$field['dbAlias']} as $alias";
2355 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2356 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2357 $this->_selectAliases
[] = $alias;
2363 // select for group bys
2364 if (array_key_exists('group_bys', $table)) {
2365 foreach ($table['group_bys'] as $fieldName => $field) {
2367 if ($tableName == 'civicrm_address') {
2368 $this->_addressField
= TRUE;
2370 if ($tableName == 'civicrm_email') {
2371 $this->_emailField
= TRUE;
2373 if ($tableName == 'civicrm_phone') {
2374 $this->_phoneField
= TRUE;
2376 // 1. In many cases we want select clause to be built in slightly different way
2377 // for a particular field of a particular type.
2378 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2380 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2381 if ($selectClause) {
2382 $select[] = $selectClause;
2386 if (!empty($this->_params
['group_bys']) &&
2387 !empty($this->_params
['group_bys'][$fieldName]) &&
2388 !empty($this->_params
['group_bys_freq'])
2390 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2392 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2393 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2394 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2395 $field['title'] = 'Week';
2399 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2400 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2401 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2402 $field['title'] = 'Year';
2406 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2407 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2408 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2409 $field['title'] = 'Month';
2413 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2414 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2415 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2416 $field['title'] = 'Quarter';
2419 // for graphs and charts -
2420 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2421 $this->_interval
= $field['title'];
2422 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2423 = $field['title'] . ' Beginning';
2424 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2425 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2427 // just to make sure these values are transferred to rows.
2428 // since we 'll need them for calculation purpose,
2429 // e.g making subtotals look nicer or graphs
2430 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2431 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2438 $this->_selectClauses
= $select;
2439 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2443 * Build select clause for a single field.
2445 * @param string $tableName
2446 * @param string $tableKey
2447 * @param string $fieldName
2448 * @param string $field
2452 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2457 * Build where clause.
2459 public function where() {
2460 $this->storeWhereHavingClauseArray();
2462 if (empty($this->_whereClauses
)) {
2463 $this->_where
= "WHERE ( 1 ) ";
2464 $this->_having
= "";
2467 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2470 if ($this->_aclWhere
) {
2471 $this->_where
.= " AND {$this->_aclWhere} ";
2474 if (!empty($this->_havingClauses
)) {
2475 // use this clause to construct group by clause.
2476 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2481 * Store Where clauses into an array.
2483 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2484 * temp table that may not be part of the final where clause or added
2485 * in other functions
2487 public function storeWhereHavingClauseArray() {
2488 foreach ($this->_columns
as $tableName => $table) {
2489 if (array_key_exists('filters', $table)) {
2490 foreach ($table['filters'] as $fieldName => $field) {
2491 // respect pseudofield to filter spec so fields can be marked as
2492 // not to be handled here
2493 if (!empty($field['pseudofield'])) {
2497 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2498 if (CRM_Utils_Array
::value('operatorType', $field) ==
2499 CRM_Report_Form
::OP_MONTH
2501 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2502 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2503 if (is_array($value) && !empty($value)) {
2505 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2510 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2511 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2512 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2513 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2514 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2515 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2519 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2521 $clause = $this->whereClause($field,
2523 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2524 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2525 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2530 if (!empty($clause)) {
2531 if (!empty($field['having'])) {
2532 $this->_havingClauses
[] = $clause;
2535 $this->_whereClauses
[] = $clause;
2547 public function processReportMode() {
2548 $buttonName = $this->controller
->getButtonName();
2550 $output = CRM_Utils_Request
::retrieve(
2553 CRM_Core_DAO
::$_nullObject
2557 = CRM_Utils_Request
::retrieve(
2560 CRM_Core_DAO
::$_nullObject
2563 $this->_absoluteUrl
= FALSE;
2565 $this->assign('printOnly', FALSE);
2567 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
2568 ($this->_sendmail
&& !$output)
2570 $this->assign('printOnly', TRUE);
2572 $this->assign('outputMode', 'print');
2573 $this->_outputMode
= 'print';
2574 if ($this->_sendmail
) {
2575 $this->_absoluteUrl
= TRUE;
2578 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
2579 $this->assign('printOnly', TRUE);
2581 $this->assign('outputMode', 'pdf');
2582 $this->_outputMode
= 'pdf';
2583 $this->_absoluteUrl
= TRUE;
2585 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2586 $this->assign('printOnly', TRUE);
2588 $this->assign('outputMode', 'csv');
2589 $this->_outputMode
= 'csv';
2590 $this->_absoluteUrl
= TRUE;
2592 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2593 $this->assign('outputMode', 'group');
2594 $this->_outputMode
= 'group';
2596 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2597 $this->assign('outputMode', 'create_report');
2598 $this->_outputMode
= 'create_report';
2601 $this->assign('outputMode', 'html');
2602 $this->_outputMode
= 'html';
2605 // Get today's date to include in printed reports
2607 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2608 $this->assign('reportDate', $reportDate);
2613 * Post Processing function for Form.
2615 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2617 public function beginPostProcess() {
2618 $this->setParams($this->controller
->exportValues($this->_name
));
2620 if (empty($this->_params
) &&
2623 $this->setParams($this->_formValues
);
2626 // hack to fix params when submitted from dashboard, CRM-8532
2627 // fields array is missing because form building etc is skipped
2628 // in dashboard mode for report
2629 //@todo - this could be done in the dashboard no we have a setter
2630 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2631 $this->setParams($this->_formValues
);
2634 $this->_formValues
= $this->_params
;
2635 if (CRM_Core_Permission
::check('administer Reports') &&
2636 isset($this->_id
) &&
2637 ($this->_instanceButtonName
==
2638 $this->controller
->getButtonName() . '_save' ||
2639 $this->_chartButtonName
== $this->controller
->getButtonName()
2642 $this->assign('updateReportButton', TRUE);
2644 $this->processReportMode();
2645 $this->beginPostProcessCommon();
2649 * BeginPostProcess function run in both report mode and non-report mode (api).
2651 public function beginPostProcessCommon() {}
2654 * Build the report query.
2656 * @param bool $applyLimit
2660 public function buildQuery($applyLimit = TRUE) {
2663 $this->customDataFrom();
2668 // order_by columns not selected for display need to be included in SELECT
2669 $unselectedSectionColumns = $this->unselectedSectionColumns();
2670 foreach ($unselectedSectionColumns as $alias => $section) {
2671 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2674 if ($applyLimit && empty($this->_params
['charts'])) {
2677 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2679 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2684 * Build group by clause.
2686 public function groupBy() {
2687 $groupBys = array();
2688 if (!empty($this->_params
['group_bys']) &&
2689 is_array($this->_params
['group_bys'])
2691 foreach ($this->_columns
as $tableName => $table) {
2692 if (array_key_exists('group_bys', $table)) {
2693 foreach ($table['group_bys'] as $fieldName => $field) {
2694 if (!empty($this->_params
['group_bys'][$fieldName])) {
2695 $groupBys[] = $field['dbAlias'];
2702 if (!empty($groupBys)) {
2703 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2708 * Build order by clause.
2710 public function orderBy() {
2711 $this->_orderBy
= "";
2712 $this->_sections
= array();
2713 $this->storeOrderByArray();
2714 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2715 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2717 $this->assign('sections', $this->_sections
);
2721 * Extract order by fields and store as an array.
2723 * In some cases other functions want to know which fields are selected for ordering by
2724 * Separating this into a separate function allows it to be called separately from constructing
2725 * the order by clause
2727 public function storeOrderByArray() {
2728 $orderBys = array();
2730 if (!empty($this->_params
['order_bys']) &&
2731 is_array($this->_params
['order_bys']) &&
2732 !empty($this->_params
['order_bys'])
2735 // Process order_bys in user-specified order
2736 foreach ($this->_params
['order_bys'] as $orderBy) {
2737 $orderByField = array();
2738 foreach ($this->_columns
as $tableName => $table) {
2739 if (array_key_exists('order_bys', $table)) {
2740 // For DAO columns defined in $this->_columns
2741 $fields = $table['order_bys'];
2743 elseif (array_key_exists('extends', $table)) {
2744 // For custom fields referenced in $this->_customGroupExtends
2745 $fields = CRM_Utils_Array
::value('fields', $table, array());
2750 if (!empty($fields) && is_array($fields)) {
2751 foreach ($fields as $fieldName => $field) {
2752 if ($fieldName == $orderBy['column']) {
2753 $orderByField = array_merge($field, $orderBy);
2754 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2761 if (!empty($orderByField)) {
2762 $this->_orderByFields
[] = $orderByField;
2763 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2765 // Record any section headers for assignment to the template
2766 if (!empty($orderBy['section'])) {
2767 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2768 $this->_sections
[$orderByField['tplField']] = $orderByField;
2774 $this->_orderByArray
= $orderBys;
2776 $this->assign('sections', $this->_sections
);
2780 * Determine unselected columns.
2784 public function unselectedSectionColumns() {
2785 $selectColumns = array();
2786 foreach ($this->_columns
as $tableName => $table) {
2787 if (array_key_exists('fields', $table)) {
2788 foreach ($table['fields'] as $fieldName => $field) {
2789 if (!empty($field['required']) ||
2790 !empty($this->_params
['fields'][$fieldName])
2793 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2799 if (is_array($this->_sections
)) {
2800 return array_diff_key($this->_sections
, $selectColumns);
2808 * Build output rows.
2810 * @param string $sql
2811 * @param array $rows
2813 public function buildRows($sql, &$rows) {
2814 $dao = CRM_Core_DAO
::executeQuery($sql);
2815 if (!is_array($rows)) {
2819 // use this method to modify $this->_columnHeaders
2820 $this->modifyColumnHeaders();
2822 $unselectedSectionColumns = $this->unselectedSectionColumns();
2824 while ($dao->fetch()) {
2826 foreach ($this->_columnHeaders
as $key => $value) {
2827 if (property_exists($dao, $key)) {
2828 $row[$key] = $dao->$key;
2832 // section headers not selected for display need to be added to row
2833 foreach ($unselectedSectionColumns as $key => $values) {
2834 if (property_exists($dao, $key)) {
2835 $row[$key] = $dao->$key;
2844 * Calculate section totals.
2846 * When "order by" fields are marked as sections, this assigns to the template
2847 * an array of total counts for each section. This data is used by the Smarty
2848 * plugin {sectionTotal}.
2850 public function sectionTotals() {
2852 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2853 if (empty($this->_selectAliases
)) {
2857 if (!empty($this->_sections
)) {
2858 // build the query with no LIMIT clause
2859 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2860 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2862 // pull section aliases out of $this->_sections
2863 $sectionAliases = array_keys($this->_sections
);
2866 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2867 $ifnulls[] = "ifnull($alias, '') as $alias";
2870 // Group (un-limited) report by all aliases and get counts. This might
2871 // be done more efficiently when the contents of $sql are known, ie. by
2872 // overriding this method in the report class.
2874 $query = "select " . implode(", ", $ifnulls) .
2875 ", count(*) as ct from ($sql) as subquery group by " .
2876 implode(", ", $sectionAliases);
2878 // initialize array of total counts
2880 $dao = CRM_Core_DAO
::executeQuery($query);
2881 while ($dao->fetch()) {
2883 // let $this->_alterDisplay translate any integer ids to human-readable values.
2884 $rows[0] = $dao->toArray();
2885 $this->alterDisplay($rows);
2888 // add totals for all permutations of section values
2891 $aliasCount = count($sectionAliases);
2892 foreach ($sectionAliases as $alias) {
2893 $values[] = $row[$alias];
2894 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2895 if ($i == $aliasCount) {
2896 // the last alias is the lowest-level section header; use count as-is
2897 $totals[$key] = $dao->ct
;
2900 // other aliases are higher level; roll count into their total
2901 $totals[$key] +
= $dao->ct
;
2905 $this->assign('sectionTotals', $totals);
2910 * Modify column headers.
2912 public function modifyColumnHeaders() {
2913 // use this method to modify $this->_columnHeaders
2917 * Assign rows to the template.
2919 * @param array $rows
2921 public function doTemplateAssignment(&$rows) {
2922 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2923 $this->assign_by_ref('rows', $rows);
2924 $this->assign('statistics', $this->statistics($rows));
2928 * Build report statistics.
2930 * Override this method to build your own statistics.
2932 * @param array $rows
2936 public function statistics(&$rows) {
2937 $statistics = array();
2939 $count = count($rows);
2941 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2945 $this->countStat($statistics, $count);
2947 $this->groupByStat($statistics);
2949 $this->filterStat($statistics);
2955 * Add count statistics.
2957 * @param array $statistics
2960 public function countStat(&$statistics, $count) {
2961 $statistics['counts']['rowCount'] = array(
2962 'title' => ts('Row(s) Listed'),
2966 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2967 $statistics['counts']['rowsFound'] = array(
2968 'title' => ts('Total Row(s)'),
2969 'value' => $this->_rowsFound
,
2975 * Add group by statistics.
2977 * @param array $statistics
2979 public function groupByStat(&$statistics) {
2980 if (!empty($this->_params
['group_bys']) &&
2981 is_array($this->_params
['group_bys']) &&
2982 !empty($this->_params
['group_bys'])
2984 foreach ($this->_columns
as $tableName => $table) {
2985 if (array_key_exists('group_bys', $table)) {
2986 foreach ($table['group_bys'] as $fieldName => $field) {
2987 if (!empty($this->_params
['group_bys'][$fieldName])) {
2988 $combinations[] = $field['title'];
2993 $statistics['groups'][] = array(
2994 'title' => ts('Grouping(s)'),
2995 'value' => implode(' & ', $combinations),
3001 * Filter statistics.
3003 * @param array $statistics
3005 public function filterStat(&$statistics) {
3006 foreach ($this->_columns
as $tableName => $table) {
3007 if (array_key_exists('filters', $table)) {
3008 foreach ($table['filters'] as $fieldName => $field) {
3009 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&&
3010 CRM_Utils_Array
::value('operatorType', $field) !=
3011 CRM_Report_Form
::OP_MONTH
3015 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3016 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3017 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3018 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3019 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3021 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3022 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3024 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3025 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3028 $statistics['filters'][] = array(
3029 'title' => $field['title'],
3030 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3033 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3034 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3036 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3037 $statistics['filters'][] = array(
3038 'title' => $field['title'],
3039 'value' => $pair[$rel],
3044 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3047 $pair = $this->getOperationPair(
3048 CRM_Utils_Array
::value('operatorType', $field),
3051 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3052 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3053 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3054 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3055 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3057 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3058 $this->setEntityRefDefaults($field, $tableName);
3059 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3060 array('id' => $val) +
3061 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3063 foreach ($result['values'] as $v) {
3064 $values[] = $v['label'];
3066 $value = "{$pair[$op]} " . implode(', ', $values);
3068 elseif ($op == 'nll' ||
$op == 'nnll') {
3069 $value = $pair[$op];
3071 elseif (is_array($val) && (!empty($val))) {
3072 $options = CRM_Utils_Array
::value('options', $field, array());
3073 foreach ($val as $key => $valIds) {
3074 if (isset($options[$valIds])) {
3075 $val[$key] = $options[$valIds];
3078 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3079 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3080 $val = implode(', ', $val);
3081 $value = "{$pair[$op]} " . $val;
3083 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3084 isset($field['options']) &&
3085 is_array($field['options']) && !empty($field['options'])
3087 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3088 CRM_Utils_Array
::value($val, $field['options'], $val);
3091 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3095 $statistics['filters'][] = array(
3096 'title' => CRM_Utils_Array
::value('title', $field),
3107 * End post processing.
3109 * @param array|null $rows
3111 public function endPostProcess(&$rows = NULL) {
3112 if ($this->_storeResultSet
) {
3113 $this->_resultSet
= $rows;
3116 if ($this->_outputMode
== 'print' ||
3117 $this->_outputMode
== 'pdf' ||
3121 $content = $this->compileContent();
3122 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3126 if ($this->_sendmail
) {
3127 $config = CRM_Core_Config
::singleton();
3128 $attachments = array();
3130 if ($this->_outputMode
== 'csv') {
3132 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3133 ": {$url}</p>" . '<p>' .
3134 ts('The report is attached as a CSV file.') . '</p>' .
3135 $this->_formValues
['report_footer'];
3137 $csvFullFilename = $config->templateCompileDir
.
3138 CRM_Utils_File
::makeFileName('CiviReport.csv');
3139 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3140 file_put_contents($csvFullFilename, $csvContent);
3141 $attachments[] = array(
3142 'fullPath' => $csvFullFilename,
3143 'mime_type' => 'text/csv',
3144 'cleanName' => 'CiviReport.csv',
3147 if ($this->_outputMode
== 'pdf') {
3148 // generate PDF content
3149 $pdfFullFilename = $config->templateCompileDir
.
3150 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3151 file_put_contents($pdfFullFilename,
3152 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3153 TRUE, array('orientation' => 'landscape')
3156 // generate Email Content
3158 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3159 ": {$url}</p>" . '<p>' .
3160 ts('The report is attached as a PDF file.') . '</p>' .
3161 $this->_formValues
['report_footer'];
3163 $attachments[] = array(
3164 'fullPath' => $pdfFullFilename,
3165 'mime_type' => 'application/pdf',
3166 'cleanName' => 'CiviReport.pdf',
3170 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3171 $this->_outputMode
, $attachments
3174 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3177 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3181 elseif ($this->_outputMode
== 'print') {
3185 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3186 $config = CRM_Core_Config
::singleton();
3187 //get chart image name
3188 $chartImg = $this->_chartId
. '.png';
3189 //get image url path
3191 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3193 $uploadUrl .= $chartImg;
3194 //get image doc path to overwrite
3196 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3197 'openFlashChart/' . $chartImg;
3199 $chart = imagecreatefrompng($uploadUrl);
3200 //convert it into formatted png
3201 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3202 //overwrite with same image
3203 imagepng($chart, $uploadImg);
3205 imagedestroy($chart);
3207 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3209 CRM_Utils_System
::civiExit();
3211 elseif ($this->_outputMode
== 'csv') {
3212 CRM_Report_Utils_Report
::export2csv($this, $rows);
3214 elseif ($this->_outputMode
== 'group') {
3215 $group = $this->_params
['groups'];
3216 $this->add2group($group);
3218 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
3219 CRM_Report_Form_Instance
::postProcess($this);
3221 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
3222 $this->_outputMode
== 'create_report'
3224 $this->_createNew
= TRUE;
3225 CRM_Report_Form_Instance
::postProcess($this);
3230 * Set store result set indicator to TRUE.
3232 * @todo explain what this does
3234 public function storeResultSet() {
3235 $this->_storeResultSet
= TRUE;
3243 public function getResultSet() {
3244 return $this->_resultSet
;
3248 * Use the form name to create the tpl file name.
3252 public function getTemplateFileName() {
3253 $defaultTpl = parent
::getTemplateFileName();
3254 $template = CRM_Core_Smarty
::singleton();
3255 if (!$template->template_exists($defaultTpl)) {
3256 $defaultTpl = 'CRM/Report/Form.tpl';
3262 * Compile the report content.
3264 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3268 public function compileContent() {
3269 $templateFile = $this->getHookedTemplateFileName();
3270 return $this->_formValues
['report_header'] .
3271 CRM_Core_Form
::$_template->fetch($templateFile) .
3272 $this->_formValues
['report_footer'];
3277 * Post process function.
3279 public function postProcess() {
3280 // get ready with post process params
3281 $this->beginPostProcess();
3284 $sql = $this->buildQuery();
3286 // build array of result based on column headers. This method also allows
3287 // modifying column headers before using it to build result set i.e $rows.
3289 $this->buildRows($sql, $rows);
3291 // format result set.
3292 $this->formatDisplay($rows);
3294 // assign variables to templates
3295 $this->doTemplateAssignment($rows);
3297 // do print / pdf / instance stuff if needed
3298 $this->endPostProcess($rows);
3304 * @param int $rowCount
3308 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3309 // lets do the pager if in html mode
3310 $this->_limit
= NULL;
3312 // CRM-14115, over-ride row count if rowCount is specified in URL
3313 if ($this->_dashBoardRowCount
) {
3314 $rowCount = $this->_dashBoardRowCount
;
3316 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
3317 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3319 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3321 // @todo all http vars should be extracted in the preProcess
3322 // - not randomly in the class
3323 if (!$pageId && !empty($_POST)) {
3324 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3325 $pageId = max((int) $_POST['crmPID_B'], 1);
3327 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3328 $pageId = max((int) $_POST['crmPID'], 1);
3330 unset($_POST['crmPID_B'], $_POST['crmPID']);
3333 $pageId = $pageId ?
$pageId : 1;
3334 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3335 $offset = ($pageId - 1) * $rowCount;
3337 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3338 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3340 $this->_limit
= " LIMIT $offset, $rowCount";
3341 return array($offset, $rowCount);
3343 if ($this->_limitValue
) {
3344 if ($this->_offsetValue
) {
3345 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3348 $this->_limit
= " LIMIT " . $this->_limitValue
;
3356 * @param int $rowCount
3358 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3360 // CRM-14115, over-ride row count if rowCount is specified in URL
3361 if ($this->_dashBoardRowCount
) {
3362 $rowCount = $this->_dashBoardRowCount
;
3365 if ($this->_limit
&& ($this->_limit
!= '')) {
3366 $sql = "SELECT FOUND_ROWS();";
3367 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3369 'total' => $this->_rowsFound
,
3370 'rowCount' => $rowCount,
3371 'status' => ts('Records') . ' %%StatusMessage%%',
3372 'buttonBottom' => 'PagerBottomButton',
3373 'buttonTop' => 'PagerTopButton',
3374 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3377 $pager = new CRM_Utils_Pager($params);
3378 $this->assign_by_ref('pager', $pager);
3379 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3384 * Build where clause for groups.
3386 * @param string $field
3387 * @param mixed $value
3392 public function whereGroupClause($field, $value, $op) {
3394 $smartGroupQuery = "";
3396 $group = new CRM_Contact_DAO_Group();
3397 $group->is_active
= 1;
3399 $smartGroups = array();
3400 while ($group->fetch()) {
3401 if (in_array($group->id
, $this->_params
['gid_value']) &&
3402 $group->saved_search_id
3404 $smartGroups[] = $group->id
;
3408 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3410 $smartGroupQuery = '';
3411 if (!empty($smartGroups)) {
3412 $smartGroups = implode(',', $smartGroups);
3413 $smartGroupQuery = " UNION DISTINCT
3414 SELECT DISTINCT smartgroup_contact.contact_id
3415 FROM civicrm_group_contact_cache smartgroup_contact
3416 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3419 $sqlOp = $this->getSQLOperator($op);
3420 if (!is_array($value)) {
3421 $value = array($value);
3423 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3425 $contactAlias = $this->_aliases
['civicrm_contact'];
3426 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3427 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3429 return " {$contactAlias}.id {$sqlOp} (
3430 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3431 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3432 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3433 {$smartGroupQuery} ) ";
3437 * Build where clause for tags.
3439 * @param string $field
3440 * @param mixed $value
3445 public function whereTagClause($field, $value, $op) {
3446 // not using left join in query because if any contact
3447 // belongs to more than one tag, results duplicate
3449 $sqlOp = $this->getSQLOperator($op);
3450 if (!is_array($value)) {
3451 $value = array($value);
3453 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3454 $entity_table = $this->_tagFilterTable
;
3455 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3456 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3457 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3458 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3462 * Generate membership organization clause.
3464 * @param mixed $value
3465 * @param string $op SQL Operator
3469 public function whereMembershipOrgClause($value, $op) {
3470 $sqlOp = $this->getSQLOperator($op);
3471 if (!is_array($value)) {
3472 $value = array($value);
3475 $tmp_membership_org_sql_list = implode(', ', $value);
3476 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3477 SELECT DISTINCT mem.contact_id
3478 FROM civicrm_membership mem
3479 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3480 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3481 WHERE mt.member_of_contact_id IN (" .
3482 $tmp_membership_org_sql_list . ")
3483 AND mt.is_active = '1'
3484 AND mem_status.is_current_member = '1'
3485 AND mem_status.is_active = '1' ) ";
3489 * Generate Membership Type SQL Clause.
3491 * @param mixed $value
3497 public function whereMembershipTypeClause($value, $op) {
3498 $sqlOp = $this->getSQLOperator($op);
3499 if (!is_array($value)) {
3500 $value = array($value);
3503 $tmp_membership_sql_list = implode(', ', $value);
3504 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3505 SELECT DISTINCT mem.contact_id
3506 FROM civicrm_membership mem
3507 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3508 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3509 WHERE mem.membership_type_id IN (" .
3510 $tmp_membership_sql_list . ")
3511 AND mt.is_active = '1'
3512 AND mem_status.is_current_member = '1'
3513 AND mem_status.is_active = '1' ) ";
3517 * Build acl clauses.
3519 * @param string $tableAlias
3521 public function buildACLClause($tableAlias = 'contact_a') {
3522 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3526 * Add custom data to the columns.
3528 * @param bool $addFields
3529 * @param array $permCustomGroupIds
3531 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3532 if (empty($this->_customGroupExtends
)) {
3535 if (!is_array($this->_customGroupExtends
)) {
3536 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3538 $customGroupWhere = '';
3539 if (!empty($permCustomGroupIds)) {
3540 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3544 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3545 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3546 FROM civicrm_custom_group cg
3547 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3548 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3550 cg.is_active = 1 AND
3551 cf.is_active = 1 AND
3552 cf.is_searchable = 1
3553 ORDER BY cg.weight, cf.weight";
3554 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3557 while ($customDAO->fetch()) {
3558 if ($customDAO->table_name
!= $curTable) {
3559 $curTable = $customDAO->table_name
;
3560 $curFields = $curFilters = array();
3563 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3564 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3565 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3566 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3573 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3574 $this->_columns
[$curTable][$colKey] = array();
3578 $fieldName = 'custom_' . $customDAO->cf_id
;
3581 // this makes aliasing work in favor
3582 $curFields[$fieldName] = array(
3583 'name' => $customDAO->column_name
,
3584 'title' => $customDAO->label
,
3585 'dataType' => $customDAO->data_type
,
3586 'htmlType' => $customDAO->html_type
,
3589 if ($this->_customGroupFilters
) {
3590 // this makes aliasing work in favor
3591 $curFilters[$fieldName] = array(
3592 'name' => $customDAO->column_name
,
3593 'title' => $customDAO->label
,
3594 'dataType' => $customDAO->data_type
,
3595 'htmlType' => $customDAO->html_type
,
3599 switch ($customDAO->data_type
) {
3602 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3603 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3604 // CRM-6946, show time part for datetime date fields
3605 if ($customDAO->time_format
) {
3606 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3611 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3612 $curFilters[$fieldName]['options'] = array(
3613 '' => ts('- select -'),
3617 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3621 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3622 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3626 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3627 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3631 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3632 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3636 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3638 if (!empty($customDAO->option_group_id
)) {
3639 if (in_array($customDAO->html_type
, array(
3644 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3647 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3649 if ($this->_customGroupFilters
) {
3650 $curFilters[$fieldName]['options'] = array();
3651 $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(
3653 $customDAO->option_group_id
,
3657 while ($ogDAO->fetch()) {
3658 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3660 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3665 case 'StateProvince':
3666 if (in_array($customDAO->html_type
, array(
3667 'Multi-Select State/Province',
3669 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3672 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3674 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3678 if (in_array($customDAO->html_type
, array(
3679 'Multi-Select Country',
3681 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3684 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3686 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3689 case 'ContactReference':
3690 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3691 $curFilters[$fieldName]['name'] = 'display_name';
3692 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3694 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3695 $curFields[$fieldName]['name'] = 'display_name';
3696 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3700 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3701 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3704 if (!array_key_exists('type', $curFields[$fieldName])) {
3705 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3709 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3711 if ($this->_customGroupFilters
) {
3712 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3714 if ($this->_customGroupGroupBy
) {
3715 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3721 * Build custom data from clause.
3723 public function customDataFrom() {
3724 if (empty($this->_customGroupExtends
)) {
3727 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3729 foreach ($this->_columns
as $table => $prop) {
3730 if (substr($table, 0, 13) == 'civicrm_value' ||
3731 substr($table, 0, 12) == 'custom_value'
3733 $extendsTable = $mapper[$prop['extends']];
3735 // check field is in params
3736 if (!$this->isFieldSelected($prop)) {
3739 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3741 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3743 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3744 // handle for ContactReference
3745 if (array_key_exists('fields', $prop)) {
3746 foreach ($prop['fields'] as $fieldName => $field) {
3747 if (CRM_Utils_Array
::value('dataType', $field) ==
3750 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3752 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3761 * Check if the field is selected.
3763 * @param string $prop
3767 public function isFieldSelected($prop) {
3772 if (!empty($this->_params
['fields'])) {
3773 foreach (array_keys($prop['fields']) as $fieldAlias) {
3774 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3775 if ($customFieldId) {
3776 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3780 //might be survey response field.
3781 if (!empty($this->_params
['fields']['survey_response']) &&
3782 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3790 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3791 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3792 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3793 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3800 if (!empty($this->_params
['order_bys'])) {
3801 foreach (array_keys($prop['fields']) as $fieldAlias) {
3802 foreach ($this->_params
['order_bys'] as $orderBy) {
3803 if ($fieldAlias == $orderBy['column'] &&
3804 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3812 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3813 foreach ($prop['filters'] as $fieldAlias => $val) {
3822 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3823 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3824 ||
($attach != 'relative' &&
3825 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3831 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3832 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3843 * Check for empty order_by configurations and remove them.
3845 * Also set template to hide them.
3847 * @param array $formValues
3849 public function preProcessOrderBy(&$formValues) {
3850 // Object to show/hide form elements
3851 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3853 $_showHide->addShow('optionField_1');
3855 // Cycle through order_by options; skip any empty ones, and hide them as well
3858 if (!empty($formValues['order_bys'])) {
3859 foreach ($formValues['order_bys'] as $order_by) {
3860 if ($order_by['column'] && $order_by['column'] != '-') {
3861 $_showHide->addShow('optionField_' . $n);
3862 $orderBys[$n] = $order_by;
3867 for ($i = $n; $i <= 5; $i++
) {
3869 $_showHide->addHide('optionField_' . $i);
3873 // overwrite order_by options with modified values
3874 if (!empty($orderBys)) {
3875 $formValues['order_bys'] = $orderBys;
3878 $formValues['order_bys'] = array(1 => array('column' => '-'));
3881 // assign show/hide data to template
3882 $_showHide->addToTemplate();
3886 * Check if table name has columns in SELECT clause.
3888 * @param string $tableName
3889 * Name of table (index of $this->_columns array).
3893 public function isTableSelected($tableName) {
3894 return in_array($tableName, $this->selectedTables());
3898 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3900 * If the array is unset it will be built.
3905 public function selectedTables() {
3906 if (!$this->_selectedTables
) {
3907 $orderByColumns = array();
3908 if (array_key_exists('order_bys', $this->_params
) &&
3909 is_array($this->_params
['order_bys'])
3911 foreach ($this->_params
['order_bys'] as $orderBy) {
3912 $orderByColumns[] = $orderBy['column'];
3916 foreach ($this->_columns
as $tableName => $table) {
3917 if (array_key_exists('fields', $table)) {
3918 foreach ($table['fields'] as $fieldName => $field) {
3919 if (!empty($field['required']) ||
3920 !empty($this->_params
['fields'][$fieldName])
3922 $this->_selectedTables
[] = $tableName;
3927 if (array_key_exists('order_bys', $table)) {
3928 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3929 if (in_array($orderByName, $orderByColumns)) {
3930 $this->_selectedTables
[] = $tableName;
3935 if (array_key_exists('filters', $table)) {
3936 foreach ($table['filters'] as $filterName => $filter) {
3937 if (!empty($this->_params
["{$filterName}_value"]) ||
3938 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3940 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
3943 $this->_selectedTables
[] = $tableName;
3950 return $this->_selectedTables
;
3954 * Add address fields.
3956 * @deprecated - use getAddressColumns which is a more accurate description
3957 * and also accepts an array of options rather than a long list
3959 * adding address fields to construct function in reports
3961 * @param bool $groupBy
3962 * Add GroupBy? Not appropriate for detail report.
3963 * @param bool $orderBy
3964 * Add GroupBy? Not appropriate for detail report.
3965 * @param bool $filters
3966 * @param array $defaults
3969 * address fields for construct clause
3971 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
3972 $addressFields = array(
3973 'civicrm_address' => array(
3974 'dao' => 'CRM_Core_DAO_Address',
3976 'address_name' => array(
3977 'title' => ts('Address Name'),
3978 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3981 'street_address' => array(
3982 'title' => ts('Street Address'),
3983 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3985 'supplemental_address_1' => array(
3986 'title' => ts('Supplementary Address Field 1'),
3987 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3989 'supplemental_address_2' => array(
3990 'title' => ts('Supplementary Address Field 2'),
3991 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3993 'street_number' => array(
3994 'name' => 'street_number',
3995 'title' => ts('Street Number'),
3997 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3999 'street_name' => array(
4000 'name' => 'street_name',
4001 'title' => ts('Street Name'),
4003 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
4005 'street_unit' => array(
4006 'name' => 'street_unit',
4007 'title' => ts('Street Unit'),
4009 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
4012 'title' => ts('City'),
4013 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
4015 'postal_code' => array(
4016 'title' => ts('Postal Code'),
4017 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
4019 'postal_code_suffix' => array(
4020 'title' => ts('Postal Code Suffix'),
4021 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
4023 'country_id' => array(
4024 'title' => ts('Country'),
4025 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
4027 'state_province_id' => array(
4028 'title' => ts('State/Province'),
4029 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
4031 'county_id' => array(
4032 'title' => ts('County'),
4033 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
4036 'grouping' => 'location-fields',
4041 $addressFields['civicrm_address']['filters'] = array(
4042 'street_number' => array(
4043 'title' => ts('Street Number'),
4045 'name' => 'street_number',
4047 'street_name' => array(
4048 'title' => ts('Street Name'),
4049 'name' => 'street_name',
4050 'operator' => 'like',
4052 'postal_code' => array(
4053 'title' => ts('Postal Code'),
4055 'name' => 'postal_code',
4058 'title' => ts('City'),
4059 'operator' => 'like',
4062 'country_id' => array(
4063 'name' => 'country_id',
4064 'title' => ts('Country'),
4065 'type' => CRM_Utils_Type
::T_INT
,
4066 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4067 'options' => CRM_Core_PseudoConstant
::country(),
4069 'state_province_id' => array(
4070 'name' => 'state_province_id',
4071 'title' => ts('State/Province'),
4072 'type' => CRM_Utils_Type
::T_INT
,
4073 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4074 'options' => array(),
4076 'county_id' => array(
4077 'name' => 'county_id',
4078 'title' => ts('County'),
4079 'type' => CRM_Utils_Type
::T_INT
,
4080 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4081 'options' => array(),
4087 $addressFields['civicrm_address']['order_bys'] = array(
4088 'street_name' => array('title' => ts('Street Name')),
4089 'street_number' => array('title' => 'Odd / Even Street Number'),
4090 'street_address' => NULL,
4092 'postal_code' => NULL,
4097 $addressFields['civicrm_address']['group_bys'] = array(
4098 'street_address' => NULL,
4100 'postal_code' => NULL,
4101 'state_province_id' => array(
4102 'title' => ts('State/Province'),
4104 'country_id' => array(
4105 'title' => ts('Country'),
4107 'county_id' => array(
4108 'title' => ts('County'),
4112 return $addressFields;
4116 * Do AlterDisplay processing on Address Fields.
4119 * @param array $rows
4120 * @param int $rowNum
4121 * @param string $baseUrl
4122 * @param string $linkText
4126 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4127 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4128 $entryFound = FALSE;
4130 if (array_key_exists('civicrm_address_country_id', $row)) {
4131 if ($value = $row['civicrm_address_country_id']) {
4132 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4133 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4134 "reset=1&force=1&{$criteriaQueryParams}&" .
4135 "country_id_op=in&country_id_value={$value}",
4136 $this->_absoluteUrl
, $this->_id
4138 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4139 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4140 array(1 => $linkText)
4146 if (array_key_exists('civicrm_address_county_id', $row)) {
4147 if ($value = $row['civicrm_address_county_id']) {
4148 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4149 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4150 "reset=1&force=1&{$criteriaQueryParams}&" .
4151 "county_id_op=in&county_id_value={$value}",
4152 $this->_absoluteUrl
, $this->_id
4154 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4155 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4156 array(1 => $linkText)
4161 // handle state province
4162 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4163 if ($value = $row['civicrm_address_state_province_id']) {
4164 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4166 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4167 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4168 $this->_absoluteUrl
, $this->_id
4170 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4171 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4172 array(1 => $linkText)
4182 * Do AlterDisplay processing on Address Fields.
4185 * @param array $rows
4186 * @param int $rowNum
4187 * @param string $baseUrl
4188 * @param string $linkText
4192 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4193 $entryFound = FALSE;
4194 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4195 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4196 $addLinks = array('gender_id' => 'Gender');
4197 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4198 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4199 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4200 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4201 if (($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4202 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4212 * Adjusts dates passed in to YEAR() for fiscal year.
4214 * @param string $fieldName
4218 public function fiscalYearOffset($fieldName) {
4219 $config = CRM_Core_Config
::singleton();
4220 $fy = $config->fiscalYearStart
;
4221 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4222 ($fy['d'] == 1 && $fy['M'] == 1)
4224 return "YEAR( $fieldName )";
4226 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4227 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4231 * Add Address into From Table if required.
4233 public function addAddressFromClause() {
4234 // include address field if address column is to be included
4235 if ((isset($this->_addressField
) &&
4236 $this->_addressField
4238 $this->isTableSelected('civicrm_address')
4241 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4242 ON ({$this->_aliases['civicrm_contact']}.id =
4243 {$this->_aliases['civicrm_address']}.contact_id) AND
4244 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4249 * Add Phone into From Table if required.
4251 public function addPhoneFromClause() {
4252 // include address field if address column is to be included
4253 if ($this->isTableSelected('civicrm_phone')
4256 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4257 ON ({$this->_aliases['civicrm_contact']}.id =
4258 {$this->_aliases['civicrm_phone']}.contact_id) AND
4259 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4264 * Get phone columns to add to array.
4266 * @param array $options
4267 * - prefix Prefix to add to table (in case of more than one instance of the table)
4268 * - prefix_label Label to give columns from this phone table instance
4271 * phone columns definition
4273 public function getPhoneColumns($options = array()) {
4274 $defaultOptions = array(
4276 'prefix_label' => '',
4279 $options = array_merge($defaultOptions, $options);
4282 $options['prefix'] . 'civicrm_phone' => array(
4283 'dao' => 'CRM_Core_DAO_Phone',
4285 $options['prefix'] . 'phone' => array(
4286 'title' => ts($options['prefix_label'] . 'Phone'),
4296 * Get address columns to add to array.
4298 * @param array $options
4299 * - prefix Prefix to add to table (in case of more than one instance of the table)
4300 * - prefix_label Label to give columns from this address table instance
4303 * address columns definition
4305 public function getAddressColumns($options = array()) {
4308 'prefix_label' => '',
4312 'defaults' => array(),
4314 return $this->addAddressFields(
4315 $options['group_by'],
4316 $options['order_by'],
4317 $options['filters'],
4318 $options['defaults']
4323 * Get a standard set of contact fields.
4327 public function getBasicContactFields() {
4329 'sort_name' => array(
4330 'title' => ts('Contact Name'),
4335 'no_display' => TRUE,
4338 'prefix_id' => array(
4339 'title' => ts('Contact Prefix'),
4341 'first_name' => array(
4342 'title' => ts('First Name'),
4344 'nick_name' => array(
4345 'title' => ts('Nick Name'),
4347 'middle_name' => array(
4348 'title' => ts('Middle Name'),
4350 'last_name' => array(
4351 'title' => ts('Last Name'),
4353 'suffix_id' => array(
4354 'title' => ts('Contact Suffix'),
4356 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4357 'email_greeting_display' => array('title' => ts('Email Greeting')),
4358 'addressee_display' => array('title' => ts('Address Greeting')),
4359 'contact_type' => array(
4360 'title' => ts('Contact Type'),
4362 'contact_sub_type' => array(
4363 'title' => ts('Contact Subtype'),
4365 'gender_id' => array(
4366 'title' => ts('Gender'),
4368 'birth_date' => array(
4369 'title' => ts('Birth Date'),
4372 'title' => ts('Age'),
4373 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4375 'job_title' => array(
4376 'title' => ts('Contact Job title'),
4378 'organization_name' => array(
4379 'title' => ts('Organization Name'),
4381 'external_identifier' => array(
4382 'title' => ts('Contact identifier from external system'),
4388 * Add contact to group.
4390 * @param int $groupID
4392 public function add2group($groupID) {
4393 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4394 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4395 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4397 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4398 $sql = str_replace('WITH ROLLUP', '', $sql);
4399 $dao = CRM_Core_DAO
::executeQuery($sql);
4401 $contact_ids = array();
4402 // Add resulting contacts to group
4403 while ($dao->fetch()) {
4404 if ($dao->addtogroup_contact_id
) {
4405 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4409 if (!empty($contact_ids)) {
4410 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4411 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4414 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4420 * Show charts on print screen.
4422 public static function uploadChartImage() {
4423 // upload strictly for '.png' images
4424 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4425 if (preg_match('/\.png$/', $name)) {
4427 // POST data is usually string data, but we are passing a RAW .png
4428 // so PHP is a bit confused and $_POST is empty. But it has saved
4429 // the raw bits into $HTTP_RAW_POST_DATA
4431 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4433 // prepare the directory
4434 $config = CRM_Core_Config
::singleton();
4436 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4438 if (!file_exists($defaultPath)) {
4439 mkdir($defaultPath, 0777, TRUE);
4442 // full path to the saved image including filename
4443 $destination = $defaultPath . $name;
4446 $jfh = fopen($destination, 'w') or die("can't open file");
4447 fwrite($jfh, $httpRawPostData);
4449 CRM_Utils_System
::civiExit();
4454 * Apply common settings to entityRef fields.
4456 * @param array $field
4457 * @param string $table
4459 private function setEntityRefDefaults(&$field, $table) {
4460 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4461 $field['attributes'] +
= array(
4462 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4464 'placeholder' => ts('- select -'),
4469 * Add link fields to the row.
4471 * Function adds the _link & _hover fields to the row.
4474 * @param string $baseUrl
4475 * @param string $linkText
4476 * @param string $value
4477 * @param string $fieldName
4478 * @param string $tablePrefix
4479 * @param string $fieldLabel
4483 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4484 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4485 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4486 "reset=1&force=1&{$criteriaQueryParams}&" .
4487 $fieldName . "_op=in&{$fieldName}_value={$value}",
4488 $this->_absoluteUrl
, $this->_id
4490 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4491 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4492 array(1 => $linkText, 2 => $fieldLabel)