5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
33 * @copyright CiviCRM LLC (c) 2004-2013
37 class CRM_Report_Form
extends CRM_Core_Form
{
38 CONST ROW_COUNT_LIMIT
= 50;
41 * Operator types - used for displaying filter elements
51 OP_MULTISELECT_SEPARATOR
= 66,
55 * The id of the report instance
62 * The id of the report template
66 protected $_templateID;
74 protected $_noFields = FALSE;
77 * The set of all columns in the report. An associative array
78 * with column name as the key and attribues as the value
82 protected $_columns = array();
85 * The set of filters in the report
89 protected $_filters = array();
92 * The set of optional columns in the report
96 protected $_options = array();
98 protected $_defaults = array();
101 * By default most reports hide contact id.
102 * Setting this to true makes it available
104 protected $_exposeContactID = TRUE;
107 * Set of statistic fields
111 protected $_statFields = array();
114 * Set of statistics data
118 protected $_statistics = array();
121 * List of fields not to be repeated during display
125 protected $_noRepeats = array();
128 * List of fields not to be displayed
132 protected $_noDisplay = array();
135 * Object type that a custom group extends
139 protected $_customGroupExtends = NULL;
140 protected $_customGroupFilters = TRUE;
141 protected $_customGroupGroupBy = FALSE;
147 protected $_tagFilter = FALSE;
150 * build groups filter
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * An attribute for checkbox/radio form field layout
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
174 protected $_force = 1;
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_rowsFound = NULL;
194 protected $_selectAliases = array();
195 protected $_rollup = NULL;
196 protected $_limit = NULL;
197 protected $_sections = NULL;
198 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
199 protected $_absoluteUrl = FALSE;
202 * To what frequency group-by a date column
206 protected $_groupByDateFreq = array(
208 'YEARWEEK' => 'Week',
209 'QUARTER' => 'Quarter',
214 * Variables to hold the acl inner join and where clause
216 protected $_aclFrom = NULL;
217 protected $_aclWhere = NULL;
220 * Array of DAO tables having columns included in SELECT or ORDER BY clause
224 protected $_selectedTables;
226 public $_having = NULL;
227 public $_select = NULL;
228 public $_columnHeaders = array();
229 public $_orderBy = NULL;
230 public $_groupBy = NULL;
231 public $_whereClauses = array();
232 public $_havingClauses = array();
235 * Variable to hold the currency alias
237 protected $_currencyColumn = NULL;
242 function __construct() {
243 parent
::__construct();
246 if ($this->_tagFilter
) {
247 $this->buildTagFilter();
249 if ($this->_exposeContactID
) {
250 if (array_key_exists('civicrm_contact', $this->_columns
)) {
251 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
253 'title' => 'Contact ID',
259 if ($this->_groupFilter
) {
260 $this->buildGroupFilter();
263 // Get all custom groups
264 $allGroups = CRM_Core_PseudoConstant
::customGroup();
266 // Get the custom groupIds for which the user have VIEW permission
267 require_once 'CRM/ACL/API.php';
268 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
270 // do not allow custom data for reports if user don't have
271 // permission to access custom data.
272 if (!empty($this->_customGroupExtends
) && !CRM_Core_Permission
::check('access all custom data') && empty($permCustomGroupIds)) {
273 $this->_customGroupExtends
= array();
276 // merge custom data columns to _columns list, if any
277 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
279 // add / modify display columns, filters ..etc
280 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
282 //assign currencyColumn variable to tpl
283 $this->assign('currencyColumn', $this->_currencyColumn
);
286 function preProcessCommon() {
288 CRM_Utils_Request
::retrieve(
291 CRM_Core_DAO
::$_nullObject
294 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
296 $this->assign('section', $this->_section
);
297 CRM_Core_Region
::instance('page-header')->add(array(
298 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
301 $this->_id
= $this->get('instanceId');
303 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
305 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
309 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
310 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
311 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
314 $this->assign('instanceId', $this->_id
);
315 $params = array('id' => $this->_id
);
316 $this->_instanceValues
= array();
317 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_Instance',
319 $this->_instanceValues
321 if (empty($this->_instanceValues
)) {
322 CRM_Core_Error
::fatal("Report could not be loaded.");
325 if (!empty($this->_instanceValues
['permission']) &&
326 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
327 CRM_Core_Permission
::check('administer Reports')
330 CRM_Utils_System
::permissionDenied();
331 CRM_Utils_System
::civiExit();
334 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
336 $this->_formValues
= unserialize($formValues);
339 $this->_formValues
= NULL;
342 // lets always do a force if reset is found in the url.
343 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
348 $this->assign('mode', 'instance');
351 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
352 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
353 if (($instanceCount > 0) && $optionValueID) {
354 $this->assign('instanceUrl',
355 CRM_Utils_System
::url('civicrm/report/list',
356 "reset=1&ovid=$optionValueID"
360 if ($optionValueID) {
361 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
365 $this->assign('mode', 'template');
368 // lets display the Report Settings section
369 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
371 // Do not display Report Settings section if administer Reports permission is absent OR
372 // if report instance is reserved and administer reserved reports absent
373 if (!CRM_Core_Permission
::check('administer Reports') ||
374 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
375 $this->_instanceForm
= FALSE;
378 $this->assign('criteriaForm', FALSE);
379 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
380 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
381 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
382 $this->assign('criteriaForm', TRUE);
383 $this->_criteriaForm
= TRUE;
387 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
388 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
389 $this->_printButtonName
= $this->getButtonName('submit', 'print');
390 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
391 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
392 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
393 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
396 function addBreadCrumb() {
400 'title' => ts('Report Templates'),
401 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
405 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
408 function preProcess() {
409 $this->preProcessCommon();
412 $this->addBreadCrumb();
415 foreach ($this->_columns
as $tableName => $table) {
417 if (!isset($table['alias'])) {
418 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
421 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
424 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
426 // higher preference to bao object
427 if (array_key_exists('bao', $table)) {
428 require_once str_replace('_', DIRECTORY_SEPARATOR
, $table['bao'] . '.php');
429 eval("\$expFields = {$table['bao']}::exportableFields( );");
431 elseif (array_key_exists('dao', $table)){
432 require_once str_replace('_', DIRECTORY_SEPARATOR
, $table['dao'] . '.php');
433 eval("\$expFields = {$table['dao']}::export( );");
436 $expFields = array();
439 $doNotCopy = array('required');
441 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
442 foreach ($fieldGroups as $fieldGrp) {
443 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
444 foreach ($table[$fieldGrp] as $fieldName => $field) {
445 // $name is the field name used to reference the BAO/DAO export fields array
446 $name = isset($field['name']) ?
$field['name'] : $fieldName;
448 // Sometimes the field name key in the BAO/DAO export fields array is
449 // different from the actual database field name.
450 // Unset $field['name'] so that actual database field name can be obtained
451 // from the BAO/DAO export fields array.
452 unset($field['name']);
454 if (array_key_exists($name, $expFields)) {
455 foreach ($doNotCopy as $dnc) {
456 // unset the values we don't want to be copied.
457 unset($expFields[$name][$dnc]);
460 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
463 foreach ($expFields[$name] as $property => $val) {
464 if (!array_key_exists($property, $field)) {
465 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
472 if (CRM_Utils_Array
::value('no_repeat', $field)) {
473 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
475 if (CRM_Utils_Array
::value('no_display', $field)) {
476 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
479 // set alias = table-name, unless already set
480 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
481 $this->_columns
[$tableName]['alias'] : $tableName
483 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
485 // set name = fieldName, unless already set
486 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
487 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
490 // set dbAlias = alias.name, unless already set
491 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
492 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
495 if (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName]) &&
496 !isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'])
498 if (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
499 array(CRM_Utils_Type
::T_MONEY
, CRM_Utils_Type
::T_FLOAT
)
501 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
503 elseif (in_array($this->_columns
[$tableName][$fieldGrp][$fieldName]['type'],
504 array(CRM_Utils_Type
::T_INT
)
506 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
513 // copy filters to a separate handy variable
514 if (array_key_exists('filters', $table)) {
515 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
518 if (array_key_exists('group_bys', $table)) {
519 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
522 if (array_key_exists('fields', $table)) {
523 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
528 $this->setDefaultValues(FALSE);
531 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
532 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
533 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
534 CRM_Report_Utils_Get
::processChart($this->_defaults
);
537 $this->_formValues
= $this->_defaults
;
538 $this->postProcess();
542 function setDefaultValues($freeze = TRUE) {
543 $freezeGroup = array();
545 // FIXME: generalizing form field naming conventions would reduce
546 // lots of lines below.
547 foreach ($this->_columns
as $tableName => $table) {
548 if (array_key_exists('fields', $table)) {
549 foreach ($table['fields'] as $fieldName => $field) {
550 if (!array_key_exists('no_display', $field)) {
551 if (isset($field['required'])) {
553 $this->_defaults
['fields'][$fieldName] = 1;
556 // find element object, so that we could use quickform's freeze method
557 // for required elements
558 $obj = $this->getElementFromGroup("fields", $fieldName);
560 $freezeGroup[] = $obj;
564 elseif (isset($field['default'])) {
565 $this->_defaults
['fields'][$fieldName] = $field['default'];
571 if (array_key_exists('group_bys', $table)) {
572 foreach ($table['group_bys'] as $fieldName => $field) {
573 if (isset($field['default'])) {
574 if (CRM_Utils_Array
::value('frequency', $field)) {
575 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
577 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
581 if (array_key_exists('filters', $table)) {
582 foreach ($table['filters'] as $fieldName => $field) {
583 if (isset($field['default'])) {
584 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
585 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
588 $this->_defaults
["{$fieldName}_value"] = $field['default'];
591 //assign default value as "in" for multiselect
592 //operator, To freeze the select element
593 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
594 $this->_defaults
["{$fieldName}_op"] = 'in';
596 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
597 $this->_defaults
["{$fieldName}_op"] = 'mhas';
599 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
600 $this->_defaults
["{$fieldName}_op"] = $op;
606 array_key_exists('order_bys', $table) &&
607 is_array($table['order_bys'])
609 if (!array_key_exists('order_bys', $this->_defaults
)) {
610 $this->_defaults
['order_bys'] = array();
612 foreach ($table['order_bys'] as $fieldName => $field) {
614 CRM_Utils_Array
::value('default', $field) ||
615 CRM_Utils_Array
::value('default_order', $field) ||
616 CRM_Utils_Array
::value('default_is_section', $field) ||
617 CRM_Utils_Array
::value('default_weight', $field)
620 'column' => $fieldName,
621 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
622 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
625 if (CRM_Utils_Array
::value('default_weight', $field)) {
626 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
629 array_unshift($this->_defaults
['order_bys'], $order_by);
635 foreach ($this->_options
as $fieldName => $field) {
636 if (isset($field['default'])) {
637 $this->_defaults
['options'][$fieldName] = $field['default'];
642 if (!empty($this->_submitValues
)) {
643 $this->preProcessOrderBy($this->_submitValues
);
646 $this->preProcessOrderBy($this->_defaults
);
649 // lets finish freezing task here itself
650 if (!empty($freezeGroup)) {
651 foreach ($freezeGroup as $elem) {
656 if ($this->_formValues
) {
657 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
660 if ($this->_instanceValues
) {
661 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
664 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
666 return $this->_defaults
;
669 function getElementFromGroup($group, $grpFieldName) {
670 $eleObj = $this->getElement($group);
671 foreach ($eleObj->_elements
as $index => $obj) {
672 if ($grpFieldName == $obj->_attributes
['name']) {
679 function addColumns() {
682 foreach ($this->_columns
as $tableName => $table) {
683 if (array_key_exists('fields', $table)) {
684 foreach ($table['fields'] as $fieldName => $field) {
685 if (!array_key_exists('no_display', $field)) {
686 if (isset($field['grouping'])) {
687 $tableName = $field['grouping'];
689 elseif (isset($table['grouping'])) {
690 $tableName = $table['grouping'];
692 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
694 if (isset($table['group_title'])) {
695 $colGroups[$tableName]['group_title'] = $table['group_title'];
698 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
704 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
705 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
707 $this->assign('colGroups', $colGroups);
710 function addFilters() {
711 $options = $filters = array();
713 foreach ($this->_filters
as $table => $attributes) {
714 foreach ($attributes as $fieldName => $field) {
715 // get ready with option value pair
716 // @ 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
718 $operations = $this->getOperationPair(
719 CRM_Utils_Array
::value('operatorType', $field),
722 $filters[$table][$fieldName] = $field;
724 switch (CRM_Utils_Array
::value('operatorType', $field)) {
725 case CRM_Report_Form
::OP_MONTH
:
726 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
727 // If there's no option list for this filter, define one.
728 $field['options'] = array(
737 9 => ts('September'),
739 11 => ts('November'),
740 12 => ts('December'),
742 // Add this option list to this column _columns. This is
743 // required so that filter statistics show properly.
744 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
746 case CRM_Report_FORM
::OP_MULTISELECT
:
747 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
748 // assume a multi-select field
749 if (!empty($field['options'])) {
750 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
751 if (count($operations) <= 1) {
754 $select = $this->addElement('select', "{$fieldName}_value", NULL,
755 $field['options'], array(
757 'style' => 'min-width:250px',
760 $select->setMultiple(TRUE);
764 case CRM_Report_FORM
::OP_SELECT
:
765 // assume a select field
766 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
767 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
770 case CRM_Report_FORM
::OP_DATE
:
771 // build datetime fields
772 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
776 case CRM_Report_FORM
::OP_DATETIME
:
777 // build datetime fields
778 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
782 case CRM_Report_FORM
::OP_INT
:
783 case CRM_Report_FORM
::OP_FLOAT
:
784 // and a min value input box
785 $this->add('text', "{$fieldName}_min", ts('Min'));
786 // and a max value input box
787 $this->add('text', "{$fieldName}_max", ts('Max'));
789 // default type is string
790 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
791 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
793 // we need text box for value input
794 $this->add('text', "{$fieldName}_value", NULL);
799 $this->assign('filters', $filters);
802 function addOptions() {
803 if (!empty($this->_options
)) {
804 // FIXME: For now lets build all elements as checkboxes.
805 // Once we clear with the format we can build elements based on type
808 foreach ($this->_options
as $fieldName => $field) {
809 if ($field['type'] == 'select') {
810 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
812 else if ($field['type'] == 'checkbox') {
813 $options[$field['title']] = $fieldName;
814 $this->addCheckBox($fieldName, NULL,
816 NULL, NULL, NULL, $this->_fourColumnAttribute
821 $this->assign('otherOptions', $this->_options
);
824 function addChartOptions() {
825 if (!empty($this->_charts
)) {
826 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
827 $this->assign('charts', $this->_charts
);
828 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
832 function addGroupBys() {
833 $options = $freqElements = array();
835 foreach ($this->_columns
as $tableName => $table) {
836 if (array_key_exists('group_bys', $table)) {
837 foreach ($table['group_bys'] as $fieldName => $field) {
838 if (!empty($field)) {
839 $options[$field['title']] = $fieldName;
840 if (CRM_Utils_Array
::value('frequency', $field)) {
841 $freqElements[$field['title']] = $fieldName;
847 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
848 NULL, NULL, NULL, $this->_fourColumnAttribute
850 $this->assign('groupByElements', $options);
852 foreach ($freqElements as $name) {
853 $this->addElement('select', "group_bys_freq[$name]",
854 ts('Frequency'), $this->_groupByDateFreq
859 function addOrderBys() {
861 foreach ($this->_columns
as $tableName => $table) {
863 // Report developer may define any column to order by; include these as order-by options
864 if (array_key_exists('order_bys', $table)) {
865 foreach ($table['order_bys'] as $fieldName => $field) {
866 if (!empty($field)) {
867 $options[$fieldName] = $field['title'];
872 /* Add searchable custom fields as order-by options, if so requested
873 * (These are already indexed, so allowing to order on them is cheap.)
877 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
878 foreach ($table['fields'] as $fieldName => $field) {
879 if (!array_key_exists('no_display', $field)) {
880 $options[$fieldName] = $field['title'];
888 $this->assign('orderByOptions', $options);
890 if (!empty($options)) {
892 '-' => ' - none - ') +
$options;
893 for ($i = 1; $i <= 5; $i++
) {
894 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
895 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
896 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
901 function buildInstanceAndButtons() {
902 CRM_Report_Form_Instance
::buildForm($this);
904 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
906 $this->addElement('submit', $this->_instanceButtonName
, $label);
907 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
908 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
911 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
913 if ($this->_instanceForm
) {
914 $this->assign('instanceForm', TRUE);
917 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
918 $this->addElement('submit', $this->_printButtonName
, $label);
920 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
921 $this->addElement('submit', $this->_pdfButtonName
, $label);
923 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
925 if ($this->_csvSupported
) {
926 $this->addElement('submit', $this->_csvButtonName
, $label);
929 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
930 $this->addElement('select', 'groups', ts('Group'),
931 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
933 $this->assign('group', TRUE);
936 $label = ts('Add these Contacts to Group');
937 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
939 $this->addChartOptions();
940 $this->addButtons(array(
943 'name' => ts('Preview Report'),
950 function buildQuickForm() {
957 $this->addGroupBys();
959 $this->addOrderBys();
961 $this->buildInstanceAndButtons();
963 //add form rule for report
964 if (is_callable(array(
965 $this, 'formRule'))) {
966 $this->addFormRule(array(get_class($this), 'formRule'), $this);
970 // a formrule function to ensure that fields selected in group_by
971 // (if any) should only be the ones present in display/select fields criteria;
972 // note: works if and only if any custom field selected in group_by.
973 function customDataFormRule($fields, $ignoreFields = array( )) {
975 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
976 foreach ($this->_columns
as $tableName => $table) {
977 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
978 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
979 if (array_key_exists($fieldName, $fields['group_bys']) &&
980 !array_key_exists($fieldName, $fields['fields'])
982 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
984 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
985 foreach ($fields['fields'] as $fld => $val) {
986 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
987 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
998 // Note: $fieldName param allows inheriting class to build operationPairs
999 // specific to a field.
1000 function getOperationPair($type = "string", $fieldName = NULL) {
1001 // FIXME: At some point we should move these key-val pairs
1002 // to option_group and option_value table.
1004 case CRM_Report_FORM
::OP_INT
:
1005 case CRM_Report_FORM
::OP_FLOAT
:
1007 'lte' => ts('Is less than or equal to'),
1008 'gte' => ts('Is greater than or equal to'),
1009 'bw' => ts('Is between'),
1010 'eq' => ts('Is equal to'),
1011 'lt' => ts('Is less than'),
1012 'gt' => ts('Is greater than'),
1013 'neq' => ts('Is not equal to'),
1014 'nbw' => ts('Is not between'),
1015 'nll' => ts('Is empty (Null)'),
1016 'nnll' => ts('Is not empty (Null)'),
1020 case CRM_Report_FORM
::OP_SELECT
:
1022 'eq' => ts('Is equal to'),
1025 case CRM_Report_FORM
::OP_MONTH
:
1026 case CRM_Report_FORM
::OP_MULTISELECT
:
1028 'in' => ts('Is one of'),
1029 'notin' => ts('Is not one of'),
1033 case CRM_Report_FORM
::OP_DATE
:
1035 'nll' => ts('Is empty (Null)'),
1036 'nnll' => ts('Is not empty (Null)'),
1040 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1041 // use this operator for the values, concatenated with separator. For e.g if
1042 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1044 'mhas' => ts('Is one of'),
1050 'has' => ts('Contains'),
1051 'sw' => ts('Starts with'),
1052 'ew' => ts('Ends with'),
1053 'nhas' => ts('Does not contain'),
1054 'eq' => ts('Is equal to'),
1055 'neq' => ts('Is not equal to'),
1056 'nll' => ts('Is empty (Null)'),
1057 'nnll' => ts('Is not empty (Null)'),
1062 function buildTagFilter() {
1063 $contactTags = CRM_Core_BAO_Tag
::getTags();
1064 if (!empty($contactTags)) {
1065 $this->_columns
['civicrm_tag'] = array(
1066 'dao' => 'CRM_Core_DAO_Tag',
1072 'title' => ts('Tag'),
1074 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1075 'options' => $contactTags,
1083 * Adds group filters to _columns (called from _Constuct
1085 function buildGroupFilter() {
1086 $this->_columns
['civicrm_group']['filters'] = array(
1089 'name' => 'group_id',
1090 'title' => ts('Group'),
1091 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1093 'options' => CRM_Core_PseudoConstant
::group(),
1096 if (empty($this->_columns
['civicrm_group']['dao'])) {
1097 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1099 if (empty($this->_columns
['civicrm_group']['alias'])) {
1100 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1104 function getSQLOperator($operator = "like") {
1105 switch ($operator) {
1138 return 'IS NOT NULL';
1146 function whereClause(&$field, $op,
1150 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1156 if (($min !== NULL && strlen($min) > 0) ||
1157 ($max !== NULL && strlen($max) > 0)
1159 $min = CRM_Utils_Type
::escape($min, $type);
1160 $max = CRM_Utils_Type
::escape($max, $type);
1164 $clauses[] = "( {$field['dbAlias']} >= $min )";
1167 $clauses[] = "( {$field['dbAlias']} < $min )";
1172 $clauses[] = "( {$field['dbAlias']} <= $max )";
1175 $clauses[] = "( {$field['dbAlias']} > $max )";
1179 if (!empty($clauses)) {
1181 $clause = implode(' AND ', $clauses);
1184 $clause = implode(' OR ', $clauses);
1192 if ($value !== NULL && strlen($value) > 0) {
1193 $value = CRM_Utils_Type
::escape($value, $type);
1194 if (strpos($value, '%') === FALSE) {
1195 $value = "'%{$value}%'";
1198 $value = "'{$value}'";
1200 $sqlOP = $this->getSQLOperator($op);
1201 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1207 if ($value !== NULL && is_array($value) && count($value) > 0) {
1208 $sqlOP = $this->getSQLOperator($op);
1209 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1210 //cycle through selections and esacape values
1211 foreach ($value as $key => $selection) {
1212 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1214 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1217 // for numerical values
1218 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1220 if ($op == 'notin') {
1221 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1224 $clause = "( " . $clause . " )";
1230 // mhas == multiple has
1231 if ($value !== NULL && count($value) > 0) {
1232 $sqlOP = $this->getSQLOperator($op);
1233 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1239 if ($value !== NULL && strlen($value) > 0) {
1240 $value = CRM_Utils_Type
::escape($value, $type);
1241 if (strpos($value, '%') === FALSE) {
1243 $value = "'{$value}%'";
1246 $value = "'%{$value}'";
1250 $value = "'{$value}'";
1252 $sqlOP = $this->getSQLOperator($op);
1253 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1259 $sqlOP = $this->getSQLOperator($op);
1260 $clause = "( {$field['dbAlias']} $sqlOP )";
1264 if ($value !== NULL && strlen($value) > 0) {
1265 if (isset($field['clause'])) {
1266 // FIXME: we not doing escape here. Better solution is to use two
1267 // different types - data-type and filter-type
1268 eval("\$clause = \"{$field['clause']}\";");
1271 $value = CRM_Utils_Type
::escape($value, $type);
1272 $sqlOP = $this->getSQLOperator($op);
1273 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1274 $value = "'{$value}'";
1276 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1282 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1283 $clause = $this->whereGroupClause($field, $value, $op);
1285 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1286 // not using left join in query because if any contact
1287 // belongs to more than one tag, results duplicate
1289 $clause = $this->whereTagClause($field, $value, $op);
1295 function dateClause($fieldName,
1296 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1299 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1300 $sqlOP = $this->getSQLOperator($relative);
1301 return "( {$fieldName} {$sqlOP} )";
1304 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1307 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1308 $clauses[] = "( {$fieldName} >= $from )";
1312 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1313 $clauses[] = "( {$fieldName} <= {$to} )";
1316 if (!empty($clauses)) {
1317 return implode(' AND ', $clauses);
1323 * @todo - could not find any instances where this is called
1324 * @param unknown_type $relative
1325 * @param String $from
1326 * @param String_type $to
1327 * @return string|NULL
1329 function dateDisplay($relative, $from, $to) {
1330 list($from, $to) = $this->getFromTo($relative, $from, $to);
1333 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1336 $clauses[] = 'Past';
1340 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1343 $clauses[] = 'Today';
1346 if (!empty($clauses)) {
1347 return implode(' - ', $clauses);
1353 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1354 if (empty($totime)) {
1357 //FIX ME not working for relative
1359 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1360 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1361 $from = substr($dateRange['from'], 0, 8);
1362 //Take only Date Part, Sometime Time part is also present in 'to'
1363 $to = substr($dateRange['to'], 0, 8);
1365 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1366 $to = CRM_Utils_Date
::processDate($to, $totime);
1367 return array($from, $to);
1370 function alterDisplay(&$rows) {
1371 // custom code to alter rows
1374 function alterCustomDataDisplay(&$rows) {
1375 // custom code to alter rows having custom values
1376 if (empty($this->_customGroupExtends
)) {
1380 $customFieldIds = array();
1381 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1382 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1383 $customFieldIds[$fieldAlias] = $fieldId;
1386 if (empty($customFieldIds)) {
1390 $customFields = $fieldValueMap = array();
1391 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1393 // skip for type date and ContactReference since date format is already handled
1395 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1396 FROM civicrm_custom_field cf
1397 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1398 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1399 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1400 cg.is_active = 1 AND
1401 cf.is_active = 1 AND
1402 cf.is_searchable = 1 AND
1403 cf.data_type NOT IN ('ContactReference', 'Date') AND
1404 cf.id IN (" . implode(",", $customFieldIds) . ")";
1406 $dao = CRM_Core_DAO
::executeQuery($query);
1407 while ($dao->fetch()) {
1408 foreach ($customFieldCols as $key) {
1409 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1411 if ($dao->option_group_id
) {
1412 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1417 $entryFound = FALSE;
1418 foreach ($rows as $rowNum => $row) {
1419 foreach ($row as $tableCol => $val) {
1420 if (array_key_exists($tableCol, $customFields)) {
1421 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1426 // skip looking further in rows, if first row itself doesn't
1427 // have the column we need
1434 function formatCustomValues($value, $customField, $fieldValueMap) {
1435 if (CRM_Utils_System
::isNull($value)) {
1439 $htmlType = $customField['html_type'];
1441 switch ($customField['data_type']) {
1443 if ($value == '1') {
1444 $retValue = ts('Yes');
1447 $retValue = ts('No');
1452 $retValue = CRM_Utils_System
::formatWikiURL($value);
1464 if ($htmlType == 'Text') {
1465 $retValue = (float)$value;
1469 if ($htmlType == 'Text') {
1479 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1484 if (in_array($htmlType, array(
1485 'Text', 'TextArea'))) {
1489 case 'StateProvince':
1492 switch ($htmlType) {
1493 case 'Multi-Select Country':
1494 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1495 $customData = array();
1496 foreach ($value as $val) {
1498 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1501 $retValue = implode(', ', $customData);
1504 case 'Select Country':
1505 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1508 case 'Select State/Province':
1509 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1512 case 'Multi-Select State/Province':
1513 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1514 $customData = array();
1515 foreach ($value as $val) {
1517 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1520 $retValue = implode(', ', $customData);
1525 case 'Autocomplete-Select':
1526 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1530 case 'AdvMulti-Select':
1531 case 'Multi-Select':
1532 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1533 $customData = array();
1534 foreach ($value as $val) {
1536 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1539 $retValue = implode(', ', $customData);
1554 function removeDuplicates(&$rows) {
1555 if (empty($this->_noRepeats
)) {
1558 $checkList = array();
1560 foreach ($rows as $key => $list) {
1561 foreach ($list as $colName => $colVal) {
1562 if (array_key_exists($colName, $checkList) &&
1563 $checkList[$colName] == $colVal) {
1564 $rows[$key][$colName] = "";
1566 if (in_array($colName, $this->_noRepeats
)) {
1567 $checkList[$colName] = $colVal;
1573 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1574 foreach ($row as $colName => $colVal) {
1575 if (in_array($colName, $fields)) {
1576 $row[$colName] = $row[$colName];
1578 elseif (isset($this->_columnHeaders
[$colName])) {
1580 $row[$colName] = "Subtotal";
1584 unset($row[$colName]);
1590 function grandTotal(&$rows) {
1591 if (!$this->_rollup ||
($this->_rollup
== '') ||
1592 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1596 $lastRow = array_pop($rows);
1598 $this->_grandFlag
= FALSE;
1599 foreach ($this->_columnHeaders
as $fld => $val) {
1600 if (!in_array($fld, $this->_statFields
)) {
1601 if (!$this->_grandFlag
) {
1602 $lastRow[$fld] = "Grand Total";
1603 $this->_grandFlag
= TRUE;
1606 $lastRow[$fld] = "";
1611 $this->assign('grandStat', $lastRow);
1615 function formatDisplay(&$rows, $pager = TRUE) {
1616 // set pager based on if any limit was applied in the query.
1621 // allow building charts if any
1622 if (!empty($this->_params
['charts']) && !empty($rows)) {
1623 $this->buildChart($rows);
1624 $this->assign('chartEnabled', TRUE);
1625 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1626 $this->assign('chartId', $this->_chartId
);
1629 // unset columns not to be displayed.
1630 foreach ($this->_columnHeaders
as $key => $value) {
1631 if (is_array($value) && isset($value['no_display'])) {
1632 unset($this->_columnHeaders
[$key]);
1636 // unset columns not to be displayed.
1637 if (!empty($rows)) {
1638 foreach ($this->_noDisplay
as $noDisplayField) {
1639 foreach ($rows as $rowNum => $row) {
1640 unset($this->_columnHeaders
[$noDisplayField]);
1645 // build array of section totals
1646 $this->sectionTotals();
1648 // process grand-total row
1649 $this->grandTotal($rows);
1651 // use this method for formatting rows for display purpose.
1652 $this->alterDisplay($rows);
1653 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1655 // use this method for formatting custom rows for display purpose.
1656 $this->alterCustomDataDisplay($rows);
1659 function buildChart(&$rows) {
1660 // override this method for building charts.
1663 // select() method below has been added recently (v3.3), and many of the report templates might
1664 // still be having their own select() method. We should fix them as and when encountered and move
1665 // towards generalizing the select() method below.
1669 foreach ($this->_columns
as $tableName => $table) {
1670 if (array_key_exists('fields', $table)) {
1671 foreach ($table['fields'] as $fieldName => $field) {
1672 if ($tableName == 'civicrm_address') {
1673 $this->_addressField
= TRUE;
1675 if ($tableName == 'civicrm_email') {
1676 $this->_emailField
= TRUE;
1678 if ($tableName == 'civicrm_phone') {
1679 $this->_phoneField
= TRUE;
1682 if (CRM_Utils_Array
::value('required', $field) ||
1683 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1686 // 1. In many cases we want select clause to be built in slightly different way
1687 // for a particular field of a particular type.
1688 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1690 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1691 if ($selectClause) {
1692 $select[] = $selectClause;
1696 // include statistics columns only if set
1697 if (CRM_Utils_Array
::value('statistics', $field)) {
1698 foreach ($field['statistics'] as $stat => $label) {
1699 $alias = "{$tableName}_{$fieldName}_{$stat}";
1700 switch (strtolower($stat)) {
1703 $select[] = "$stat({$field['dbAlias']}) as $alias";
1704 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1705 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1706 $this->_statFields
[] = $alias;
1707 $this->_selectAliases
[] = $alias;
1711 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1712 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1713 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1714 $this->_statFields
[] = $alias;
1715 $this->_selectAliases
[] = $alias;
1719 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1720 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1721 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1722 $this->_statFields
[] = $alias;
1723 $this->_selectAliases
[] = $alias;
1729 $alias = "{$tableName}_{$fieldName}";
1730 $select[] = "{$field['dbAlias']} as $alias";
1731 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1732 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1733 $this->_selectAliases
[] = $alias;
1739 // select for group bys
1740 if (array_key_exists('group_bys', $table)) {
1741 foreach ($table['group_bys'] as $fieldName => $field) {
1743 if ($tableName == 'civicrm_address') {
1744 $this->_addressField
= TRUE;
1746 if ($tableName == 'civicrm_email') {
1747 $this->_emailField
= TRUE;
1749 if ($tableName == 'civicrm_phone') {
1750 $this->_phoneField
= TRUE;
1752 // 1. In many cases we want select clause to be built in slightly different way
1753 // for a particular field of a particular type.
1754 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1756 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1757 if ($selectClause) {
1758 $select[] = $selectClause;
1762 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1763 && !empty($this->_params
['group_bys_freq'])) {
1764 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1766 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1767 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1768 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1769 $field['title'] = 'Week';
1773 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1774 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1775 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1776 $field['title'] = 'Year';
1780 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1781 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1782 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1783 $field['title'] = 'Month';
1787 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1788 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1789 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1790 $field['title'] = 'Quarter';
1793 // for graphs and charts -
1794 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1795 $this->_interval
= $field['title'];
1796 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1797 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1798 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1800 // just to make sure these values are transfered to rows.
1801 // since we 'll need them for calculation purpose,
1802 // e.g making subtotals look nicer or graphs
1803 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1804 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1811 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1814 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1819 $this->storeWhereHavingClauseArray();
1821 if (empty($this->_whereClauses
)) {
1822 $this->_where
= "WHERE ( 1 ) ";
1823 $this->_having
= "";
1826 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1829 if ($this->_aclWhere
) {
1830 $this->_where
.= " AND {$this->_aclWhere} ";
1833 if (!empty($this->_havingClauses
)) {
1834 // use this clause to construct group by clause.
1835 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1840 * Store Where clauses into an array - breaking out this step makes
1841 * over-riding more flexible as the clauses can be used in constructing a
1842 * temp table that may not be part of the final where clause or added
1843 * in other functions
1845 function storeWhereHavingClauseArray(){
1846 foreach ($this->_columns
as $tableName => $table) {
1847 if (array_key_exists('filters', $table)) {
1848 foreach ($table['filters'] as $fieldName => $field) {
1849 // respect pseudofield to filter spec so fields can be marked as
1850 // not to be handled here
1851 if(!empty($field['pseudofield'])){
1855 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1856 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1857 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1858 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1859 if (is_array($value) && !empty($value)) {
1860 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1864 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1865 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1866 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1867 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1868 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1869 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1873 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1875 $clause = $this->whereClause($field,
1877 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1878 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1879 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1884 if (!empty($clause)) {
1885 if (CRM_Utils_Array
::value('having', $field)) {
1886 $this->_havingClauses
[] = $clause;
1889 $this->_whereClauses
[] = $clause;
1897 function processReportMode() {
1898 $buttonName = $this->controller
->getButtonName();
1900 $output = CRM_Utils_Request
::retrieve(
1903 CRM_Core_DAO
::$_nullObject
1907 CRM_Utils_Request
::retrieve(
1910 CRM_Core_DAO
::$_nullObject
1913 $this->_absoluteUrl
= FALSE;
1915 $this->assign('printOnly', FALSE);
1917 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1918 $this->assign('printOnly', TRUE);
1920 $this->assign('outputMode', 'print');
1921 $this->_outputMode
= 'print';
1922 if ($this->_sendmail
) {
1923 $this->_absoluteUrl
= TRUE;
1926 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1927 $this->assign('printOnly', TRUE);
1929 $this->assign('outputMode', 'pdf');
1930 $this->_outputMode
= 'pdf';
1931 $this->_absoluteUrl
= TRUE;
1933 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
1934 $this->assign('printOnly', TRUE);
1936 $this->assign('outputMode', 'csv');
1937 $this->_outputMode
= 'csv';
1938 $this->_absoluteUrl
= TRUE;
1940 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
1941 $this->assign('outputMode', 'group');
1942 $this->_outputMode
= 'group';
1944 elseif ($output == 'create_report' && $this->_criteriaForm
) {
1945 $this->assign('outputMode', 'create_report');
1946 $this->_outputMode
= 'create_report';
1949 $this->assign('outputMode', 'html');
1950 $this->_outputMode
= 'html';
1953 // Get today's date to include in printed reports
1955 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
1956 $this->assign('reportDate', $reportDate);
1960 function beginPostProcess() {
1961 $this->_params
= $this->controller
->exportValues($this->_name
);
1963 if (empty($this->_params
) &&
1966 $this->_params
= $this->_formValues
;
1969 // hack to fix params when submitted from dashboard, CRM-8532
1970 // fields array is missing because form building etc is skipped
1971 // in dashboard mode for report
1972 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
1973 $this->_params
= $this->_formValues
;
1976 $this->_formValues
= $this->_params
;
1977 if (CRM_Core_Permission
::check('administer Reports') &&
1978 isset($this->_id
) &&
1979 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
1980 $this->_chartButtonName
== $this->controller
->getButtonName()
1983 $this->assign('updateReportButton', TRUE);
1985 $this->processReportMode();
1988 function buildQuery($applyLimit = TRUE) {
1991 $this->customDataFrom();
1996 // order_by columns not selected for display need to be included in SELECT
1997 $unselectedSectionColumns = $this->unselectedSectionColumns();
1998 foreach ($unselectedSectionColumns as $alias => $section) {
1999 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2002 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2005 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2007 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2011 function groupBy() {
2012 $groupBys = array();
2013 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2014 is_array($this->_params
['group_bys']) &&
2015 !empty($this->_params
['group_bys'])
2017 foreach ($this->_columns
as $tableName => $table) {
2018 if (array_key_exists('group_bys', $table)) {
2019 foreach ($table['group_bys'] as $fieldName => $field) {
2020 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2021 $groupBys[] = $field['dbAlias'];
2028 if (!empty($groupBys)) {
2029 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2033 function orderBy() {
2034 $this->_orderBy
= "";
2035 $this->_sections
= array();
2036 $this->storeOrderByArray();
2037 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2038 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2040 $this->assign('sections', $this->_sections
);
2043 * In some cases other functions want to know which fields are selected for ordering by
2044 * Separating this into a separate function allows it to be called separately from constructing
2045 * the order by clause
2047 function storeOrderByArray() {
2048 $orderBys = array();
2050 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2051 is_array($this->_params
['order_bys']) &&
2052 !empty($this->_params
['order_bys'])
2055 // Proces order_bys in user-specified order
2056 foreach ($this->_params
['order_bys'] as $orderBy) {
2057 $orderByField = array();
2058 foreach ($this->_columns
as $tableName => $table) {
2059 if (array_key_exists('order_bys', $table)) {
2060 // For DAO columns defined in $this->_columns
2061 $fields = $table['order_bys'];
2063 elseif (array_key_exists('extends', $table)) {
2064 // For custom fields referenced in $this->_customGroupExtends
2065 $fields = $table['fields'];
2067 if (!empty($fields) && is_array($fields)) {
2068 foreach ($fields as $fieldName => $field) {
2069 if ($fieldName == $orderBy['column']) {
2070 $orderByField = $field;
2071 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2078 if (!empty($orderByField)) {
2079 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2081 // Record any section headers for assignment to the template
2082 if (CRM_Utils_Array
::value('section', $orderBy)) {
2083 $this->_sections
[$orderByField['tplField']] = $orderByField;
2089 $this->_orderByArray
= $orderBys;
2091 $this->assign('sections', $this->_sections
);
2094 function unselectedSectionColumns() {
2095 $selectColumns = array();
2096 foreach ($this->_columns
as $tableName => $table) {
2097 if (array_key_exists('fields', $table)) {
2098 foreach ($table['fields'] as $fieldName => $field) {
2099 if (CRM_Utils_Array
::value('required', $field) ||
2100 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2103 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2108 if (is_array($this->_sections
)) {
2109 return array_diff_key($this->_sections
, $selectColumns);
2116 function buildRows($sql, &$rows) {
2117 $dao = CRM_Core_DAO
::executeQuery($sql);
2118 if (!is_array($rows)) {
2122 // use this method to modify $this->_columnHeaders
2123 $this->modifyColumnHeaders();
2125 $unselectedSectionColumns = $this->unselectedSectionColumns();
2127 while ($dao->fetch()) {
2129 foreach ($this->_columnHeaders
as $key => $value) {
2130 if (property_exists($dao, $key)) {
2131 $row[$key] = $dao->$key;
2135 // section headers not selected for display need to be added to row
2136 foreach ($unselectedSectionColumns as $key => $values) {
2137 if (property_exists($dao, $key)) {
2138 $row[$key] = $dao->$key;
2147 * When "order by" fields are marked as sections, this assigns to the template
2148 * an array of total counts for each section. This data is used by the Smarty
2149 * plugin {sectionTotal}
2151 function sectionTotals() {
2153 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2154 if (empty($this->_selectAliases
)) {
2158 if (!empty($this->_sections
)) {
2159 // build the query with no LIMIT clause
2160 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2161 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2163 // pull section aliases out of $this->_sections
2164 $sectionAliases = array_keys($this->_sections
);
2167 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2168 $ifnulls[] = "ifnull($alias, '') as $alias";
2171 /* Group (un-limited) report by all aliases and get counts. This might
2172 * be done more efficiently when the contents of $sql are known, ie. by
2173 * overriding this method in the report class.
2177 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2179 // initialize array of total counts
2181 $dao = CRM_Core_DAO
::executeQuery($query);
2182 while ($dao->fetch()) {
2184 // let $this->_alterDisplay translate any integer ids to human-readable values.
2185 $rows[0] = $dao->toArray();
2186 $this->alterDisplay($rows);
2189 // add totals for all permutations of section values
2192 $aliasCount = count($sectionAliases);
2193 foreach ($sectionAliases as $alias) {
2194 $values[] = $row[$alias];
2195 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2196 if ($i == $aliasCount) {
2197 // the last alias is the lowest-level section header; use count as-is
2198 $totals[$key] = $dao->ct
;
2201 // other aliases are higher level; roll count into their total
2202 $totals[$key] +
= $dao->ct
;
2206 $this->assign('sectionTotals', $totals);
2210 function modifyColumnHeaders() {
2211 // use this method to modify $this->_columnHeaders
2214 function doTemplateAssignment(&$rows) {
2215 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2216 $this->assign_by_ref('rows', $rows);
2217 $this->assign('statistics', $this->statistics($rows));
2220 // override this method to build your own statistics
2221 function statistics(&$rows) {
2222 $statistics = array();
2224 $count = count($rows);
2226 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2230 $this->countStat($statistics, $count);
2232 $this->groupByStat($statistics);
2234 $this->filterStat($statistics);
2239 function countStat(&$statistics, $count) {
2240 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2244 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2245 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2246 'value' => $this->_rowsFound
,
2251 function groupByStat(&$statistics) {
2252 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2253 is_array($this->_params
['group_bys']) &&
2254 !empty($this->_params
['group_bys'])
2256 foreach ($this->_columns
as $tableName => $table) {
2257 if (array_key_exists('group_bys', $table)) {
2258 foreach ($table['group_bys'] as $fieldName => $field) {
2259 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2260 $combinations[] = $field['title'];
2265 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2266 'value' => implode(' & ', $combinations),
2271 function filterStat(&$statistics) {
2272 foreach ($this->_columns
as $tableName => $table) {
2273 if (array_key_exists('filters', $table)) {
2274 foreach ($table['filters'] as $fieldName => $field) {
2275 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2278 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2279 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2280 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2281 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2282 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2284 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2285 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2287 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2288 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2291 $statistics['filters'][] = array(
2292 'title' => $field['title'],
2293 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2296 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2297 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2299 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2300 $statistics['filters'][] = array(
2301 'title' => $field['title'],
2302 'value' => $pair[$rel],
2307 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2310 $pair = $this->getOperationPair(
2311 CRM_Utils_Array
::value('operatorType', $field),
2314 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2315 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2316 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2317 if (in_array($op, array(
2318 'bw', 'nbw')) && ($min ||
$max)) {
2319 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2321 elseif ($op == 'nll' ||
$op == 'nnll') {
2322 $value = $pair[$op];
2324 elseif (is_array($val) && (!empty($val))) {
2325 $options = $field['options'];
2326 foreach ($val as $key => $valIds) {
2327 if (isset($options[$valIds])) {
2328 $val[$key] = $options[$valIds];
2331 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : $pair[$op];
2332 $val = implode(', ', $val);
2333 $value = "{$pair[$op]} " . $val;
2335 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2336 is_array($field['options']) && !empty($field['options'])
2338 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2341 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2345 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2355 function endPostProcess(&$rows = NULL) {
2356 if ($this->_outputMode
== 'print' ||
2357 $this->_outputMode
== 'pdf' ||
2361 $content = $this->compileContent();
2362 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2366 if ($this->_sendmail
) {
2367 $config = CRM_Core_Config
::singleton();
2368 $attachments = array();
2370 if ($this->_outputMode
== 'csv') {
2371 $content = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') . ": {$url}</p>" . '<p>' . ts('The report is attached as a CSV file.') . '</p>' . $this->_formValues
['report_footer'];
2373 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2374 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2375 file_put_contents($csvFullFilename, $csvContent);
2376 $attachments[] = array(
2377 'fullPath' => $csvFullFilename,
2378 'mime_type' => 'text/csv',
2379 'cleanName' => 'CiviReport.csv',
2382 if ($this->_outputMode
== 'pdf') {
2383 // generate PDF content
2384 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2385 file_put_contents($pdfFullFilename,
2386 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2387 TRUE, array('orientation' => 'landscape')
2390 // generate Email Content
2391 $content = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') . ": {$url}</p>" . '<p>' . ts('The report is attached as a PDF file.') . '</p>' . $this->_formValues
['report_footer'];
2393 $attachments[] = array(
2394 'fullPath' => $pdfFullFilename,
2395 'mime_type' => 'application/pdf',
2396 'cleanName' => 'CiviReport.pdf',
2400 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2401 $this->_outputMode
, $attachments
2403 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2406 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2409 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2411 elseif ($this->_outputMode
== 'print') {
2415 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2416 $config = CRM_Core_Config
::singleton();
2417 //get chart image name
2418 $chartImg = $this->_chartId
. '.png';
2419 //get image url path
2420 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2421 $uploadUrl .= $chartImg;
2422 //get image doc path to overwrite
2423 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2425 $chart = imagecreatefrompng($uploadUrl);
2426 //convert it into formattd png
2427 header('Content-type: image/png');
2428 //overwrite with same image
2429 imagepng($chart, $uploadImg);
2431 imagedestroy($chart);
2433 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2435 CRM_Utils_System
::civiExit();
2437 elseif ($this->_outputMode
== 'csv') {
2438 CRM_Report_Utils_Report
::export2csv($this, $rows);
2440 elseif ($this->_outputMode
== 'group') {
2441 $group = $this->_params
['groups'];
2442 $this->add2group($group);
2444 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2445 CRM_Report_Form_Instance
::postProcess($this);
2447 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2448 $this->_outputMode
== 'create_report' ) {
2449 $this->_createNew
= TRUE;
2450 CRM_Report_Form_Instance
::postProcess($this);
2455 * Get Template file name - use default form template if a specific one has not been set up for this report
2458 function getTemplateFileName(){
2459 $defaultTpl = parent
::getTemplateFileName();
2460 $template = CRM_Core_Smarty
::singleton();
2461 if (!$template->template_exists($defaultTpl)) {
2462 $defaultTpl = 'CRM/Report/Form.tpl';
2468 * Compile the report content
2470 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2472 function compileContent(){
2473 $templateFile = $this->getTemplateFileName();
2474 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2478 function postProcess() {
2479 // get ready with post process params
2480 $this->beginPostProcess();
2483 $sql = $this->buildQuery();
2485 // build array of result based on column headers. This method also allows
2486 // modifying column headers before using it to build result set i.e $rows.
2488 $this->buildRows($sql, $rows);
2490 // format result set.
2491 $this->formatDisplay($rows);
2493 // assign variables to templates
2494 $this->doTemplateAssignment($rows);
2496 // do print / pdf / instance stuff if needed
2497 $this->endPostProcess($rows);
2500 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2501 // lets do the pager if in html mode
2502 $this->_limit
= NULL;
2503 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2504 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2506 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2508 if (!$pageId && !empty($_POST)) {
2509 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2510 $pageId = max((int)@$_POST['crmPID_B'], 1);
2512 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2513 $pageId = max((int)@$_POST['crmPID'], 1);
2515 unset($_POST['crmPID_B'], $_POST['crmPID']);
2518 $pageId = $pageId ?
$pageId : 1;
2519 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2520 $offset = ($pageId - 1) * $rowCount;
2522 $this->_limit
= " LIMIT $offset, " . $rowCount;
2523 return array($offset, $rowCount);
2527 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2528 if ($this->_limit
&& ($this->_limit
!= '')) {
2529 $sql = "SELECT FOUND_ROWS();";
2530 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2532 'total' => $this->_rowsFound
,
2533 'rowCount' => $rowCount,
2534 'status' => ts('Records') . ' %%StatusMessage%%',
2535 'buttonBottom' => 'PagerBottomButton',
2536 'buttonTop' => 'PagerTopButton',
2537 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2540 $pager = new CRM_Utils_Pager($params);
2541 $this->assign_by_ref('pager', $pager);
2545 function whereGroupClause($field, $value, $op) {
2547 $smartGroupQuery = "";
2549 $group = new CRM_Contact_DAO_Group();
2550 $group->is_active
= 1;
2552 $smartGroups = array();
2553 while ($group->fetch()) {
2554 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2555 $smartGroups[] = $group->id
;
2559 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2561 $smartGroupQuery = '';
2562 if (!empty($smartGroups)) {
2563 $smartGroups = implode(',', $smartGroups);
2564 $smartGroupQuery = " UNION DISTINCT
2565 SELECT DISTINCT smartgroup_contact.contact_id
2566 FROM civicrm_group_contact_cache smartgroup_contact
2567 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2570 $sqlOp = $this->getSQLOperator($op);
2571 if (!is_array($value)) {
2572 $value = array($value);
2574 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2576 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2577 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2578 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2579 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2580 {$smartGroupQuery} ) ";
2583 function whereTagClause($field, $value, $op) {
2584 // not using left join in query because if any contact
2585 // belongs to more than one tag, results duplicate
2587 $sqlOp = $this->getSQLOperator($op);
2588 if (!is_array($value)) {
2589 $value = array($value);
2591 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2593 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2594 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2595 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2596 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2599 function buildACLClause($tableAlias = 'contact_a') {
2600 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2603 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2604 if (empty($this->_customGroupExtends
)) {
2607 if (!is_array($this->_customGroupExtends
)) {
2608 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2610 $customGroupWhere = '';
2611 if (!empty($permCustomGroupIds)) {
2612 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2615 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2616 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2617 FROM civicrm_custom_group cg
2618 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2619 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2621 cg.is_active = 1 AND
2622 cf.is_active = 1 AND
2623 cf.is_searchable = 1
2624 ORDER BY cg.weight, cf.weight";
2625 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2628 while ($customDAO->fetch()) {
2629 if ($customDAO->table_name
!= $curTable) {
2630 $curTable = $customDAO->table_name
;
2631 $curFields = $curFilters = array();
2634 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2635 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2636 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2637 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2640 'fields', 'filters', 'group_bys') as $colKey) {
2641 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2642 $this->_columns
[$curTable][$colKey] = array();
2646 $fieldName = 'custom_' . $customDAO->cf_id
;
2649 // this makes aliasing work in favor
2650 $curFields[$fieldName] = array(
2651 'name' => $customDAO->column_name
,
2652 'title' => $customDAO->label
,
2653 'dataType' => $customDAO->data_type
,
2654 'htmlType' => $customDAO->html_type
,
2657 if ($this->_customGroupFilters
) {
2658 // this makes aliasing work in favor
2659 $curFilters[$fieldName] = array(
2660 'name' => $customDAO->column_name
,
2661 'title' => $customDAO->label
,
2662 'dataType' => $customDAO->data_type
,
2663 'htmlType' => $customDAO->html_type
,
2667 switch ($customDAO->data_type
) {
2670 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2671 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2672 // CRM-6946, show time part for datetime date fields
2673 if ($customDAO->time_format
) {
2674 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2679 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2680 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2684 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2688 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2689 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2693 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2694 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2698 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2699 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2703 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2705 if (!empty($customDAO->option_group_id
)) {
2706 if (in_array($customDAO->html_type
, array(
2707 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2708 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2711 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2713 if ($this->_customGroupFilters
) {
2714 $curFilters[$fieldName]['options'] = array();
2715 $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(1 => array($customDAO->option_group_id
, 'Integer')));
2716 while ($ogDAO->fetch()) {
2717 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2723 case 'StateProvince':
2724 if (in_array($customDAO->html_type
, array(
2725 'Multi-Select State/Province'))) {
2726 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2729 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2731 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2735 if (in_array($customDAO->html_type
, array(
2736 'Multi-Select Country'))) {
2737 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2740 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2742 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2745 case 'ContactReference':
2746 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2747 $curFilters[$fieldName]['name'] = 'display_name';
2748 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2750 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2751 $curFields[$fieldName]['name'] = 'display_name';
2752 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2756 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2757 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2760 if (!array_key_exists('type', $curFields[$fieldName])) {
2761 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2765 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2767 if ($this->_customGroupFilters
) {
2768 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2770 if ($this->_customGroupGroupBy
) {
2771 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2776 function customDataFrom() {
2777 if (empty($this->_customGroupExtends
)) {
2780 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2782 foreach ($this->_columns
as $table => $prop) {
2783 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2784 $extendsTable = $mapper[$prop['extends']];
2786 // check field is in params
2787 if (!$this->isFieldSelected($prop)) {
2792 LEFT JOIN $table {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2793 // handle for ContactReference
2794 if (array_key_exists('fields', $prop)) {
2795 foreach ($prop['fields'] as $fieldName => $field) {
2796 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2797 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2799 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2807 function isFieldSelected($prop) {
2812 if (!empty($this->_params
['fields'])) {
2813 foreach (array_keys($prop['fields']) as $fieldAlias) {
2814 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2815 if ($customFieldId) {
2816 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2820 //might be survey response field.
2821 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2822 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2830 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2831 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2832 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2838 if (!empty($this->_params
['order_bys'])) {
2839 foreach (array_keys($prop['fields']) as $fieldAlias) {
2840 foreach ($this->_params
['order_bys'] as $orderBy) {
2841 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2848 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2849 foreach ($prop['filters'] as $fieldAlias => $val) {
2851 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2852 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2853 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2854 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2860 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2861 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2872 * Check for empty order_by configurations and remove them; also set
2873 * template to hide them.
2875 function preProcessOrderBy(&$formValues) {
2876 // Object to show/hide form elements
2877 $_showHide = &new CRM_Core_ShowHideBlocks('', '');
2879 $_showHide->addShow('optionField_1');
2881 // Cycle through order_by options; skip any empty ones, and hide them as well
2884 if (!empty($formValues['order_bys'])) {
2885 foreach ($formValues['order_bys'] as $order_by) {
2886 if ($order_by['column'] && $order_by['column'] != '-') {
2887 $_showHide->addShow('optionField_' . $n);
2888 $orderBys[$n] = $order_by;
2893 for ($i = $n; $i <= 5; $i++
) {
2895 $_showHide->addHide('optionField_' . $i);
2899 // overwrite order_by options with modified values
2900 if (!empty($orderBys)) {
2901 $formValues['order_bys'] = $orderBys;
2904 $formValues['order_bys'] = array(1 => array('column' => '-'));
2907 // assign show/hide data to template
2908 $_showHide->addToTemplate();
2912 * Does table name have columns in SELECT clause?
2914 * @param string $tableName Name of table (index of $this->_columns array)
2918 function isTableSelected($tableName) {
2919 return in_array($tableName, $this->selectedTables());
2923 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
2924 * (building the array if it's unset)
2926 * @return Array $this->_selectedTables
2928 function selectedTables() {
2929 if (!$this->_selectedTables
) {
2930 $orderByColumns = array();
2931 if (is_array($this->_params
['order_bys'])) {
2932 foreach ($this->_params
['order_bys'] as $orderBy) {
2933 $orderByColumns[] = $orderBy['column'];
2937 foreach ($this->_columns
as $tableName => $table) {
2938 if (array_key_exists('fields', $table)) {
2939 foreach ($table['fields'] as $fieldName => $field) {
2940 if (CRM_Utils_Array
::value('required', $field) ||
2941 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2943 $this->_selectedTables
[] = $tableName;
2948 if (array_key_exists('order_bys', $table)) {
2949 foreach ($table['order_bys'] as $orderByName => $orderBy) {
2950 if (in_array($orderByName, $orderByColumns)) {
2951 $this->_selectedTables
[] = $tableName;
2956 if (array_key_exists('filters', $table)) {
2957 foreach ($table['filters'] as $filterName => $filter) {
2958 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
2959 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
2960 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
2962 $this->_selectedTables
[] = $tableName;
2969 return $this->_selectedTables
;
2973 * @deprecated - use getAddressColumns which is a more accurate description
2974 * and also accepts an array of options rather than a long list
2976 * function for adding address fields to construct function in reports
2977 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
2978 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
2979 * @return array address fields for construct clause
2981 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
2982 'country_id' => TRUE)) {
2983 $addressFields = array(
2984 'civicrm_address' =>
2986 'dao' => 'CRM_Core_DAO_Address',
2990 array('title' => ts('Address Name'),
2991 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
2994 array('title' => ts('Street Address'),
2995 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
2997 'supplemental_address_1' =>
2998 array('title' => ts('Supplementary Address Field 1'),
2999 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3001 'supplemental_address_2' =>
3002 array('title' => ts('Supplementary Address Field 2'),
3003 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3007 'name' => 'street_number',
3008 'title' => ts('Street Number'),
3010 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3014 'name' => 'street_name',
3015 'title' => ts('Street Name'),
3017 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3021 'name' => 'street_unit',
3022 'title' => ts('Street Unit'),
3024 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3027 array('title' => ts('City'),
3028 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3031 array('title' => ts('Postal Code'),
3032 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3035 array('title' => ts('County'),
3036 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3038 'state_province_id' =>
3039 array('title' => ts('State/Province'),
3040 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3043 array('title' => ts('Country'),
3044 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3047 'grouping' => 'location-fields',
3052 $addressFields['civicrm_address']['filters'] = array(
3053 'street_number' => array('title' => ts('Street Number'),
3055 'name' => 'street_number',
3057 'street_name' => array('title' => ts('Street Name'),
3058 'name' => 'street_name',
3059 'operator' => 'like',
3061 'postal_code' => array('title' => ts('Postal Code'),
3063 'name' => 'postal_code',
3065 'city' => array('title' => ts('City'),
3066 'operator' => 'like',
3069 'county_id' => array(
3070 'name' => 'county_id',
3071 'title' => ts('County'),
3072 'type' => CRM_Utils_Type
::T_INT
,
3074 CRM_Report_Form
::OP_MULTISELECT
,
3076 CRM_Core_PseudoConstant
::county(),
3078 'state_province_id' => array(
3079 'name' => 'state_province_id',
3080 'title' => ts('State/Province'),
3081 'type' => CRM_Utils_Type
::T_INT
,
3083 CRM_Report_Form
::OP_MULTISELECT
,
3085 CRM_Core_PseudoConstant
::stateProvince(),
3087 'country_id' => array(
3088 'name' => 'country_id',
3089 'title' => ts('Country'),
3090 'type' => CRM_Utils_Type
::T_INT
,
3092 CRM_Report_Form
::OP_MULTISELECT
,
3094 CRM_Core_PseudoConstant
::country(),
3100 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3101 'street_number' => array('title' => 'Odd / Even Street Number'),
3102 'street_address' => NULL,
3104 'postal_code' => NULL,
3109 $addressFields['civicrm_address']['group_bys'] = array(
3110 'street_address' => NULL,
3112 'postal_code' => NULL,
3113 'state_province_id' =>
3114 array('title' => ts('State/Province'),
3117 array('title' => ts('Country'),
3120 array('title' => ts('County'),
3124 return $addressFields;
3128 * Do AlterDisplay processing on Address Fields
3130 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3131 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3132 $entryFound = FALSE;
3134 if (array_key_exists('civicrm_address_country_id', $row)) {
3135 if ($value = $row['civicrm_address_country_id']) {
3136 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3137 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3138 "reset=1&force=1&{$criteriaQueryParams}&" .
3139 "country_id_op=in&country_id_value={$value}",
3140 $this->_absoluteUrl
, $this->_id
3142 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3143 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3150 if (array_key_exists('civicrm_address_county_id', $row)) {
3151 if ($value = $row['civicrm_address_county_id']) {
3152 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3153 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3154 "reset=1&force=1&{$criteriaQueryParams}&" .
3155 "county_id_op=in&county_id_value={$value}",
3156 $this->_absoluteUrl
, $this->_id
3158 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3159 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3165 // handle state province
3166 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3167 if ($value = $row['civicrm_address_state_province_id']) {
3168 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3170 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3171 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3172 $this->_absoluteUrl
, $this->_id
3174 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3175 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3186 * Adjusts dates passed in to YEAR() for fiscal year.
3188 function fiscalYearOffset($fieldName) {
3189 $config = CRM_Core_Config
::singleton();
3190 $fy = $config->fiscalYearStart
;
3191 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3192 return "YEAR( $fieldName )";
3194 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3198 * Add Address into From Table if required
3200 function addAddressFromClause() {
3201 // include address field if address column is to be included
3202 if ((isset($this->_addressField
) &&
3203 $this->_addressField
3205 $this->isTableSelected('civicrm_address')
3208 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3209 ON ({$this->_aliases['civicrm_contact']}.id =
3210 {$this->_aliases['civicrm_address']}.contact_id) AND
3211 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3216 * Add Phone into From Table if required
3218 function addPhoneFromClause() {
3219 // include address field if address column is to be included
3220 if ($this->isTableSelected('civicrm_phone')
3223 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3224 ON ({$this->_aliases['civicrm_contact']}.id =
3225 {$this->_aliases['civicrm_phone']}.contact_id) AND
3226 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3231 * Get phone columns to add to array
3232 * @param array $options
3233 * - prefix Prefix to add to table (in case of more than one instance of the table)
3234 * - prefix_label Label to give columns from this phone table instance
3235 * @return array phone columns definition
3237 function getPhoneColumns($options = array()){
3238 $defaultOptions = array(
3240 'prefix_label' => '',
3243 $options = array_merge($defaultOptions,$options);
3246 $options['prefix'] . 'civicrm_phone' => array(
3247 'dao' => 'CRM_Core_DAO_Phone',
3249 $options['prefix'] . 'phone' => array(
3250 'title' => ts($options['prefix_label'] . 'Phone'),
3260 * Get address columns to add to array
3261 * @param array $options
3262 * - prefix Prefix to add to table (in case of more than one instance of the table)
3263 * - prefix_label Label to give columns from this address table instance
3264 * @return array address columns definition
3266 function getAddressColumns($options = array()){
3267 $defaultOptions = array(
3269 'prefix_label' => '',
3273 'defaults' => array(
3276 $options = array_merge($defaultOptions,$options);
3277 return $this->addAddressFields(
3278 $options['group_by'],
3279 $options['order_by'],
3280 $options['filters'],
3281 $options['defaults']
3286 function add2group($groupID) {
3287 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3288 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3289 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3291 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3292 $dao = CRM_Core_DAO
::executeQuery($sql);
3294 $contact_ids = array();
3295 // Add resulting contacts to group
3296 while ($dao->fetch()) {
3297 if ($dao->addtogroup_contact_id
) {
3298 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3302 if ( !empty($contact_ids) ) {
3303 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3304 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3307 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));