3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Report_Form
extends CRM_Core_Form
{
36 CONST ROW_COUNT_LIMIT
= 50;
39 * Operator types - used for displaying filter elements
49 OP_MULTISELECT_SEPARATOR
= 66,
53 * The id of the report instance
60 * The id of the report template
64 protected $_templateID;
72 protected $_noFields = FALSE;
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attribues as the value
80 protected $_columns = array();
83 * The set of filters in the report
87 protected $_filters = array();
90 * The set of optional columns in the report
94 protected $_options = array();
96 protected $_defaults = array();
99 * By default most reports hide contact id.
100 * Setting this to true makes it available
102 protected $_exposeContactID = TRUE;
105 * Set of statistic fields
109 protected $_statFields = array();
112 * Set of statistics data
116 protected $_statistics = array();
119 * List of fields not to be repeated during display
123 protected $_noRepeats = array();
126 * List of fields not to be displayed
130 protected $_noDisplay = array();
133 * Object type that a custom group extends
137 protected $_customGroupExtends = NULL;
138 protected $_customGroupFilters = TRUE;
139 protected $_customGroupGroupBy = FALSE;
140 protected $_customGroupJoin = 'LEFT JOIN';
146 protected $_tagFilter = FALSE;
149 * build groups filter
152 protected $_groupFilter = FALSE;
159 public $_navigation = array();
161 public $_drilldownReport = array();
164 * An attribute for checkbox/radio form field layout
168 protected $_fourColumnAttribute = array(
169 '</td><td width="25%">', '</td><td width="25%">',
170 '</td><td width="25%">', '</tr><tr><td>',
173 protected $_force = 1;
175 protected $_params = NULL;
176 protected $_formValues = NULL;
177 protected $_instanceValues = NULL;
179 protected $_instanceForm = FALSE;
180 protected $_criteriaForm = FALSE;
182 protected $_instanceButtonName = NULL;
183 protected $_createNewButtonName = NULL;
184 protected $_printButtonName = NULL;
185 protected $_pdfButtonName = NULL;
186 protected $_csvButtonName = NULL;
187 protected $_groupButtonName = NULL;
188 protected $_chartButtonName = NULL;
189 protected $_csvSupported = TRUE;
190 protected $_add2groupSupported = TRUE;
191 protected $_groups = NULL;
192 protected $_grandFlag = FALSE;
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 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
206 protected $_storeResultSet = FALSE;
209 * When _storeResultSet Flag is set use this var to store result set in form of array
213 protected $_resultSet = array();
216 * To what frequency group-by a date column
220 protected $_groupByDateFreq = array(
222 'YEARWEEK' => 'Week',
223 'QUARTER' => 'Quarter',
228 * Variables to hold the acl inner join and where clause
230 protected $_aclFrom = NULL;
231 protected $_aclWhere = NULL;
234 * Array of DAO tables having columns included in SELECT or ORDER BY clause
238 protected $_selectedTables;
240 public $_having = NULL;
241 public $_select = NULL;
242 public $_columnHeaders = array();
243 public $_orderBy = NULL;
244 public $_orderByFields = array();
245 public $_orderByArray = array();
246 public $_groupBy = NULL;
247 public $_whereClauses = array();
248 public $_havingClauses = array();
251 * Variable to hold the currency alias
253 protected $_currencyColumn = NULL;
258 function __construct() {
259 parent
::__construct();
262 if ($this->_tagFilter
) {
263 $this->buildTagFilter();
265 if ($this->_exposeContactID
) {
266 if (array_key_exists('civicrm_contact', $this->_columns
)) {
267 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
269 'title' => 'Contact ID',
275 if ($this->_groupFilter
) {
276 $this->buildGroupFilter();
279 // Get all custom groups
280 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
282 // Get the custom groupIds for which the user have VIEW permission
283 require_once 'CRM/ACL/API.php';
284 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
286 // do not allow custom data for reports if user don't have
287 // permission to access custom data.
288 if (!empty($this->_customGroupExtends
) && !CRM_Core_Permission
::check('access all custom data') && empty($permCustomGroupIds)) {
289 $this->_customGroupExtends
= array();
292 // merge custom data columns to _columns list, if any
293 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
295 // add / modify display columns, filters ..etc
296 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
298 //assign currencyColumn variable to tpl
299 $this->assign('currencyColumn', $this->_currencyColumn
);
302 function preProcessCommon() {
304 CRM_Utils_Request
::retrieve(
307 CRM_Core_DAO
::$_nullObject
310 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
312 $this->assign('section', $this->_section
);
313 CRM_Core_Region
::instance('page-header')->add(array(
314 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
317 $this->_id
= $this->get('instanceId');
319 $this->_id
= CRM_Report_Utils_Report
::getInstanceID();
321 $this->_id
= CRM_Report_Utils_Report
::getInstanceIDForPath();
325 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
326 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
327 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
330 $this->assign('instanceId', $this->_id
);
331 $params = array('id' => $this->_id
);
332 $this->_instanceValues
= array();
333 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
335 $this->_instanceValues
337 if (empty($this->_instanceValues
)) {
338 CRM_Core_Error
::fatal("Report could not be loaded.");
341 if (!empty($this->_instanceValues
['permission']) &&
342 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
343 CRM_Core_Permission
::check('administer Reports')
346 CRM_Utils_System
::permissionDenied();
347 CRM_Utils_System
::civiExit();
350 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
352 $this->_formValues
= unserialize($formValues);
355 $this->_formValues
= NULL;
358 // lets always do a force if reset is found in the url.
359 if (CRM_Utils_Array
::value('reset', $_REQUEST)) {
364 $this->assign('mode', 'instance');
367 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
368 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
369 if (($instanceCount > 0) && $optionValueID) {
370 $this->assign('instanceUrl',
371 CRM_Utils_System
::url('civicrm/report/list',
372 "reset=1&ovid=$optionValueID"
376 if ($optionValueID) {
377 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
381 $this->assign('mode', 'template');
384 // lets display the Report Settings section
385 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
387 // Do not display Report Settings section if administer Reports permission is absent OR
388 // if report instance is reserved and administer reserved reports absent
389 if (!CRM_Core_Permission
::check('administer Reports') ||
390 ($this->_instanceValues
['is_reserved'] && !CRM_Core_Permission
::check('administer reserved reports'))) {
391 $this->_instanceForm
= FALSE;
394 $this->assign('criteriaForm', FALSE);
395 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
396 if (CRM_Core_Permission
::check('administer Reports') || CRM_Core_Permission
::check('access Report Criteria')) {
397 if (!$this->_instanceValues
['is_reserved'] || CRM_Core_Permission
::check('administer reserved reports')) {
398 $this->assign('criteriaForm', TRUE);
399 $this->_criteriaForm
= TRUE;
403 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
404 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
405 $this->_printButtonName
= $this->getButtonName('submit', 'print');
406 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
407 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
408 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
409 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
412 function addBreadCrumb() {
416 'title' => ts('Report Templates'),
417 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
421 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
424 function preProcess() {
425 $this->preProcessCommon();
428 $this->addBreadCrumb();
431 foreach ($this->_columns
as $tableName => $table) {
433 if (!isset($table['alias'])) {
434 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
437 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
440 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
442 $daoOrBaoName = NULL;
443 // higher preference to bao object
444 if (array_key_exists('bao', $table)) {
445 $daoOrBaoName = $table['bao'];
446 $expFields = $daoOrBaoName::exportableFields( );
448 elseif (array_key_exists('dao', $table)){
449 $daoOrBaoName = $table['dao'];
450 $expFields = $daoOrBaoName::export( );
453 $expFields = array();
456 $doNotCopy = array('required');
458 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
459 foreach ($fieldGroups as $fieldGrp) {
460 if (CRM_Utils_Array
::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
461 foreach ($table[$fieldGrp] as $fieldName => $field) {
462 // $name is the field name used to reference the BAO/DAO export fields array
463 $name = isset($field['name']) ?
$field['name'] : $fieldName;
465 // Sometimes the field name key in the BAO/DAO export fields array is
466 // different from the actual database field name.
467 // Unset $field['name'] so that actual database field name can be obtained
468 // from the BAO/DAO export fields array.
469 unset($field['name']);
471 if (array_key_exists($name, $expFields)) {
472 foreach ($doNotCopy as $dnc) {
473 // unset the values we don't want to be copied.
474 unset($expFields[$name][$dnc]);
477 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
480 foreach ($expFields[$name] as $property => $val) {
481 if (!array_key_exists($property, $field)) {
482 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
489 if (CRM_Utils_Array
::value('no_repeat', $field)) {
490 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
492 if (CRM_Utils_Array
::value('no_display', $field)) {
493 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
496 // set alias = table-name, unless already set
497 $alias = isset($field['alias']) ?
$field['alias'] : (isset($this->_columns
[$tableName]['alias']) ?
498 $this->_columns
[$tableName]['alias'] : $tableName
500 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
502 // set name = fieldName, unless already set
503 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
504 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
507 // set dbAlias = alias.name, unless already set
508 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
509 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
512 // a few auto fills for filters
513 if ($fieldGrp == 'filters') {
514 // fill operator types
515 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
516 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
517 case CRM_Utils_Type
::T_MONEY
:
518 case CRM_Utils_Type
::T_FLOAT
:
519 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
521 case CRM_Utils_Type
::T_INT
:
522 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
524 case CRM_Utils_Type
::T_DATE
:
525 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
527 case CRM_Utils_Type
::T_BOOLEAN
:
528 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
529 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
530 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] =
531 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
536 (array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
537 ||
array_key_exists('enumValues', $this->_columns
[$tableName][$fieldGrp][$fieldName]))
539 // with multiple options operator-type is generally multi-select
540 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
541 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
543 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
554 // copy filters to a separate handy variable
555 if (array_key_exists('filters', $table)) {
556 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
559 if (array_key_exists('group_bys', $table)) {
560 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
563 if (array_key_exists('fields', $table)) {
564 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
569 $this->setDefaultValues(FALSE);
572 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
573 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
574 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
575 CRM_Report_Utils_Get
::processChart($this->_defaults
);
578 $this->_formValues
= $this->_defaults
;
579 $this->postProcess();
583 function setDefaultValues($freeze = TRUE) {
584 $freezeGroup = array();
586 // FIXME: generalizing form field naming conventions would reduce
587 // lots of lines below.
588 foreach ($this->_columns
as $tableName => $table) {
589 if (array_key_exists('fields', $table)) {
590 foreach ($table['fields'] as $fieldName => $field) {
591 if (!array_key_exists('no_display', $field)) {
592 if (isset($field['required'])) {
594 $this->_defaults
['fields'][$fieldName] = 1;
597 // find element object, so that we could use quickform's freeze method
598 // for required elements
599 $obj = $this->getElementFromGroup("fields", $fieldName);
601 $freezeGroup[] = $obj;
605 elseif (isset($field['default'])) {
606 $this->_defaults
['fields'][$fieldName] = $field['default'];
612 if (array_key_exists('group_bys', $table)) {
613 foreach ($table['group_bys'] as $fieldName => $field) {
614 if (isset($field['default'])) {
615 if (CRM_Utils_Array
::value('frequency', $field)) {
616 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
618 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
622 if (array_key_exists('filters', $table)) {
623 foreach ($table['filters'] as $fieldName => $field) {
624 if (isset($field['default'])) {
625 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
626 if(is_array($field['default'])){
627 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
628 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
629 $this->_defaults
["{$fieldName}_relative"] = 0;
632 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
636 $this->_defaults
["{$fieldName}_value"] = $field['default'];
639 //assign default value as "in" for multiselect
640 //operator, To freeze the select element
641 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT
) {
642 $this->_defaults
["{$fieldName}_op"] = 'in';
644 elseif (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
) {
645 $this->_defaults
["{$fieldName}_op"] = 'mhas';
647 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
648 $this->_defaults
["{$fieldName}_op"] = $op;
654 array_key_exists('order_bys', $table) &&
655 is_array($table['order_bys'])
657 if (!array_key_exists('order_bys', $this->_defaults
)) {
658 $this->_defaults
['order_bys'] = array();
660 foreach ($table['order_bys'] as $fieldName => $field) {
662 CRM_Utils_Array
::value('default', $field) ||
663 CRM_Utils_Array
::value('default_order', $field) ||
664 CRM_Utils_Array
::value('default_is_section', $field) ||
665 CRM_Utils_Array
::value('default_weight', $field)
668 'column' => $fieldName,
669 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
670 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
673 if (CRM_Utils_Array
::value('default_weight', $field)) {
674 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
677 array_unshift($this->_defaults
['order_bys'], $order_by);
683 foreach ($this->_options
as $fieldName => $field) {
684 if (isset($field['default'])) {
685 $this->_defaults
['options'][$fieldName] = $field['default'];
690 if (!empty($this->_submitValues
)) {
691 $this->preProcessOrderBy($this->_submitValues
);
694 $this->preProcessOrderBy($this->_defaults
);
697 // lets finish freezing task here itself
698 if (!empty($freezeGroup)) {
699 foreach ($freezeGroup as $elem) {
704 if ($this->_formValues
) {
705 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
708 if ($this->_instanceValues
) {
709 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
712 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
714 return $this->_defaults
;
717 function getElementFromGroup($group, $grpFieldName) {
718 $eleObj = $this->getElement($group);
719 foreach ($eleObj->_elements
as $index => $obj) {
720 if ($grpFieldName == $obj->_attributes
['name']) {
727 function addColumns() {
730 foreach ($this->_columns
as $tableName => $table) {
731 if (array_key_exists('fields', $table)) {
732 foreach ($table['fields'] as $fieldName => $field) {
734 if (!array_key_exists('no_display', $field)) {
735 foreach ( array('table', 'field') as $var) {
736 if (!empty($
{$var}['grouping'])) {
737 if (!is_array($
{$var}['grouping'])) {
738 $tableName = $
{$var}['grouping'];
740 $tableName = array_keys($
{$var}['grouping']);
741 $tableName = $tableName[0];
742 $groupTitle = array_values($
{$var}['grouping']);
743 $groupTitle = $groupTitle[0];
748 if (!$groupTitle && isset($table['group_title'])) {
749 $groupTitle = $table['group_title'];
752 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
753 if ($groupTitle && !CRM_Utils_Array
::value('group_title', $colGroups[$tableName])) {
754 $colGroups[$tableName]['group_title'] = $groupTitle;
757 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
763 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
764 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
766 $this->assign('colGroups', $colGroups);
769 function addFilters() {
770 $options = $filters = array();
772 foreach ($this->_filters
as $table => $attributes) {
773 foreach ($attributes as $fieldName => $field) {
774 // get ready with option value pair
775 // @ 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
777 $operations = $this->getOperationPair(
778 CRM_Utils_Array
::value('operatorType', $field),
781 $filters[$table][$fieldName] = $field;
783 switch (CRM_Utils_Array
::value('operatorType', $field)) {
784 case CRM_Report_Form
::OP_MONTH
:
785 if (!array_key_exists('options', $field) ||
!is_array($field['options']) ||
empty($field['options'])) {
786 // If there's no option list for this filter, define one.
787 $field['options'] = array(
796 9 => ts('September'),
798 11 => ts('November'),
799 12 => ts('December'),
801 // Add this option list to this column _columns. This is
802 // required so that filter statistics show properly.
803 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
805 case CRM_Report_FORM
::OP_MULTISELECT
:
806 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
807 // assume a multi-select field
808 if (!empty($field['options'])) {
809 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
810 if (count($operations) <= 1) {
813 $select = $this->addElement('select', "{$fieldName}_value", NULL,
814 $field['options'], array(
816 'style' => 'min-width:250px',
819 $select->setMultiple(TRUE);
823 case CRM_Report_FORM
::OP_SELECT
:
824 // assume a select field
825 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
826 if (!empty($field['options']))
827 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
830 case CRM_Report_FORM
::OP_DATE
:
831 // build datetime fields
832 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
836 case CRM_Report_FORM
::OP_DATETIME
:
837 // build datetime fields
838 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
842 case CRM_Report_FORM
::OP_INT
:
843 case CRM_Report_FORM
::OP_FLOAT
:
844 // and a min value input box
845 $this->add('text', "{$fieldName}_min", ts('Min'));
846 // and a max value input box
847 $this->add('text', "{$fieldName}_max", ts('Max'));
849 // default type is string
850 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
851 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
853 // we need text box for value input
854 $this->add('text', "{$fieldName}_value", NULL);
859 $this->assign('filters', $filters);
862 function addOptions() {
863 if (!empty($this->_options
)) {
864 // FIXME: For now lets build all elements as checkboxes.
865 // Once we clear with the format we can build elements based on type
868 foreach ($this->_options
as $fieldName => $field) {
869 if ($field['type'] == 'select') {
870 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
872 else if ($field['type'] == 'checkbox') {
873 $options[$field['title']] = $fieldName;
874 $this->addCheckBox($fieldName, NULL,
876 NULL, NULL, NULL, $this->_fourColumnAttribute
881 $this->assign('otherOptions', $this->_options
);
884 function addChartOptions() {
885 if (!empty($this->_charts
)) {
886 $this->addElement('select', "charts", ts('Chart'), $this->_charts
, array('onchange' => 'disablePrintPDFButtons(this.value);'));
887 $this->assign('charts', $this->_charts
);
888 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
892 function addGroupBys() {
893 $options = $freqElements = array();
895 foreach ($this->_columns
as $tableName => $table) {
896 if (array_key_exists('group_bys', $table)) {
897 foreach ($table['group_bys'] as $fieldName => $field) {
898 if (!empty($field)) {
899 $options[$field['title']] = $fieldName;
900 if (CRM_Utils_Array
::value('frequency', $field)) {
901 $freqElements[$field['title']] = $fieldName;
907 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
908 NULL, NULL, NULL, $this->_fourColumnAttribute
910 $this->assign('groupByElements', $options);
912 foreach ($freqElements as $name) {
913 $this->addElement('select', "group_bys_freq[$name]",
914 ts('Frequency'), $this->_groupByDateFreq
919 function addOrderBys() {
921 foreach ($this->_columns
as $tableName => $table) {
923 // Report developer may define any column to order by; include these as order-by options
924 if (array_key_exists('order_bys', $table)) {
925 foreach ($table['order_bys'] as $fieldName => $field) {
926 if (!empty($field)) {
927 $options[$fieldName] = $field['title'];
932 /* Add searchable custom fields as order-by options, if so requested
933 * (These are already indexed, so allowing to order on them is cheap.)
937 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&& array_key_exists('extends', $table) && !empty($table['extends'])) {
938 foreach ($table['fields'] as $fieldName => $field) {
939 if (!array_key_exists('no_display', $field)) {
940 $options[$fieldName] = $field['title'];
948 $this->assign('orderByOptions', $options);
950 if (!empty($options)) {
952 '-' => ' - none - ') +
$options;
953 for ($i = 1; $i <= 5; $i++
) {
954 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
955 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
956 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
961 function buildInstanceAndButtons() {
962 CRM_Report_Form_Instance
::buildForm($this);
964 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
966 $this->addElement('submit', $this->_instanceButtonName
, $label);
967 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
968 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
971 $this->addElement('submit', $this->_createNewButtonName
, ts('Save a Copy') . '...');
973 if ($this->_instanceForm
) {
974 $this->assign('instanceForm', TRUE);
977 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
978 $this->addElement('submit', $this->_printButtonName
, $label);
980 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
981 $this->addElement('submit', $this->_pdfButtonName
, $label);
983 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
985 if ($this->_csvSupported
) {
986 $this->addElement('submit', $this->_csvButtonName
, $label);
989 if (CRM_Core_Permission
::check('administer Reports') && $this->_add2groupSupported
) {
990 $this->addElement('select', 'groups', ts('Group'),
991 array('' => ts('- select group -')) + CRM_Core_PseudoConstant
::staticGroup()
993 $this->assign('group', TRUE);
996 $label = ts('Add these Contacts to Group');
997 $this->addElement('submit', $this->_groupButtonName
, $label, array('onclick' => 'return checkGroup();'));
999 $this->addChartOptions();
1000 $this->addButtons(array(
1003 'name' => ts('Preview Report'),
1004 'isDefault' => TRUE,
1010 function buildQuickForm() {
1011 $this->addColumns();
1013 $this->addFilters();
1015 $this->addOptions();
1017 $this->addGroupBys();
1019 $this->addOrderBys();
1021 $this->buildInstanceAndButtons();
1023 //add form rule for report
1024 if (is_callable(array(
1025 $this, 'formRule'))) {
1026 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1030 // a formrule function to ensure that fields selected in group_by
1031 // (if any) should only be the ones present in display/select fields criteria;
1032 // note: works if and only if any custom field selected in group_by.
1033 function customDataFormRule($fields, $ignoreFields = array( )) {
1035 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&& !empty($fields['group_bys'])) {
1036 foreach ($this->_columns
as $tableName => $table) {
1037 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns
[$tableName]['fields'])) {
1038 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1039 if (array_key_exists($fieldName, $fields['group_bys']) &&
1040 !array_key_exists($fieldName, $fields['fields'])
1042 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1044 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1045 foreach ($fields['fields'] as $fld => $val) {
1046 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1047 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1058 // Note: $fieldName param allows inheriting class to build operationPairs
1059 // specific to a field.
1060 function getOperationPair($type = "string", $fieldName = NULL) {
1061 // FIXME: At some point we should move these key-val pairs
1062 // to option_group and option_value table.
1064 case CRM_Report_FORM
::OP_INT
:
1065 case CRM_Report_FORM
::OP_FLOAT
:
1067 'lte' => ts('Is less than or equal to'),
1068 'gte' => ts('Is greater than or equal to'),
1069 'bw' => ts('Is between'),
1070 'eq' => ts('Is equal to'),
1071 'lt' => ts('Is less than'),
1072 'gt' => ts('Is greater than'),
1073 'neq' => ts('Is not equal to'),
1074 'nbw' => ts('Is not between'),
1075 'nll' => ts('Is empty (Null)'),
1076 'nnll' => ts('Is not empty (Null)'),
1080 case CRM_Report_FORM
::OP_SELECT
:
1082 'eq' => ts('Is equal to'),
1085 case CRM_Report_FORM
::OP_MONTH
:
1086 case CRM_Report_FORM
::OP_MULTISELECT
:
1088 'in' => ts('Is one of'),
1089 'notin' => ts('Is not one of'),
1093 case CRM_Report_FORM
::OP_DATE
:
1095 'nll' => ts('Is empty (Null)'),
1096 'nnll' => ts('Is not empty (Null)'),
1100 case CRM_Report_FORM
::OP_MULTISELECT_SEPARATOR
:
1101 // use this operator for the values, concatenated with separator. For e.g if
1102 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1104 'mhas' => ts('Is one of'),
1110 'has' => ts('Contains'),
1111 'sw' => ts('Starts with'),
1112 'ew' => ts('Ends with'),
1113 'nhas' => ts('Does not contain'),
1114 'eq' => ts('Is equal to'),
1115 'neq' => ts('Is not equal to'),
1116 'nll' => ts('Is empty (Null)'),
1117 'nnll' => ts('Is not empty (Null)'),
1122 function buildTagFilter() {
1123 $contactTags = CRM_Core_BAO_Tag
::getTags();
1124 if (!empty($contactTags)) {
1125 $this->_columns
['civicrm_tag'] = array(
1126 'dao' => 'CRM_Core_DAO_Tag',
1132 'title' => ts('Tag'),
1134 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1135 'options' => $contactTags,
1143 * Adds group filters to _columns (called from _Constuct
1145 function buildGroupFilter() {
1146 $this->_columns
['civicrm_group']['filters'] = array(
1149 'name' => 'group_id',
1150 'title' => ts('Group'),
1151 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1153 'options' => CRM_Core_PseudoConstant
::group(),
1156 if (empty($this->_columns
['civicrm_group']['dao'])) {
1157 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1159 if (empty($this->_columns
['civicrm_group']['alias'])) {
1160 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1164 function getSQLOperator($operator = "like") {
1165 switch ($operator) {
1198 return 'IS NOT NULL';
1206 function whereClause(&$field, $op,
1210 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1216 if (($min !== NULL && strlen($min) > 0) ||
1217 ($max !== NULL && strlen($max) > 0)
1219 $min = CRM_Utils_Type
::escape($min, $type);
1220 $max = CRM_Utils_Type
::escape($max, $type);
1224 $clauses[] = "( {$field['dbAlias']} >= $min )";
1227 $clauses[] = "( {$field['dbAlias']} < $min )";
1232 $clauses[] = "( {$field['dbAlias']} <= $max )";
1235 $clauses[] = "( {$field['dbAlias']} > $max )";
1239 if (!empty($clauses)) {
1241 $clause = implode(' AND ', $clauses);
1244 $clause = implode(' OR ', $clauses);
1252 if ($value !== NULL && strlen($value) > 0) {
1253 $value = CRM_Utils_Type
::escape($value, $type);
1254 if (strpos($value, '%') === FALSE) {
1255 $value = "'%{$value}%'";
1258 $value = "'{$value}'";
1260 $sqlOP = $this->getSQLOperator($op);
1261 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1267 if ($value !== NULL && is_array($value) && count($value) > 0) {
1268 $sqlOP = $this->getSQLOperator($op);
1269 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
1270 //cycle through selections and esacape values
1271 foreach ($value as $key => $selection) {
1272 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1274 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1277 // for numerical values
1278 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1280 if ($op == 'notin') {
1281 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1284 $clause = "( " . $clause . " )";
1290 // mhas == multiple has
1291 if ($value !== NULL && count($value) > 0) {
1292 $sqlOP = $this->getSQLOperator($op);
1293 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1299 if ($value !== NULL && strlen($value) > 0) {
1300 $value = CRM_Utils_Type
::escape($value, $type);
1301 if (strpos($value, '%') === FALSE) {
1303 $value = "'{$value}%'";
1306 $value = "'%{$value}'";
1310 $value = "'{$value}'";
1312 $sqlOP = $this->getSQLOperator($op);
1313 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1319 $sqlOP = $this->getSQLOperator($op);
1320 $clause = "( {$field['dbAlias']} $sqlOP )";
1324 if ($value !== NULL && strlen($value) > 0) {
1325 if (isset($field['clause'])) {
1326 // FIXME: we not doing escape here. Better solution is to use two
1327 // different types - data-type and filter-type
1328 $clause = $field['clause'];
1331 $value = CRM_Utils_Type
::escape($value, $type);
1332 $sqlOP = $this->getSQLOperator($op);
1333 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1334 $value = "'{$value}'";
1336 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1342 if (CRM_Utils_Array
::value('group', $field) && $clause) {
1343 $clause = $this->whereGroupClause($field, $value, $op);
1345 elseif (CRM_Utils_Array
::value('tag', $field) && $clause) {
1346 // not using left join in query because if any contact
1347 // belongs to more than one tag, results duplicate
1349 $clause = $this->whereTagClause($field, $value, $op);
1355 function dateClause($fieldName,
1356 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1359 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
)))) {
1360 $sqlOP = $this->getSQLOperator($relative);
1361 return "( {$fieldName} {$sqlOP} )";
1364 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1367 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1368 $clauses[] = "( {$fieldName} >= $from )";
1372 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1373 $clauses[] = "( {$fieldName} <= {$to} )";
1376 if (!empty($clauses)) {
1377 return implode(' AND ', $clauses);
1383 * @todo - could not find any instances where this is called
1384 * @param unknown_type $relative
1385 * @param String $from
1386 * @param String_type $to
1387 * @return string|NULL
1389 function dateDisplay($relative, $from, $to) {
1390 list($from, $to) = $this->getFromTo($relative, $from, $to);
1393 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1396 $clauses[] = 'Past';
1400 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1403 $clauses[] = 'Today';
1406 if (!empty($clauses)) {
1407 return implode(' - ', $clauses);
1413 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1414 if (empty($totime)) {
1417 //FIX ME not working for relative
1419 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1420 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1421 $from = substr($dateRange['from'], 0, 8);
1422 //Take only Date Part, Sometime Time part is also present in 'to'
1423 $to = substr($dateRange['to'], 0, 8);
1425 $from = CRM_Utils_Date
::processDate($from, $fromtime);
1426 $to = CRM_Utils_Date
::processDate($to, $totime);
1427 return array($from, $to);
1430 function alterDisplay(&$rows) {
1431 // custom code to alter rows
1434 function alterCustomDataDisplay(&$rows) {
1435 // custom code to alter rows having custom values
1436 if (empty($this->_customGroupExtends
)) {
1440 $customFieldIds = array();
1441 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
1442 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
1443 $customFieldIds[$fieldAlias] = $fieldId;
1446 if (empty($customFieldIds)) {
1450 $customFields = $fieldValueMap = array();
1451 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1453 // skip for type date and ContactReference since date format is already handled
1455 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1456 FROM civicrm_custom_field cf
1457 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1458 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1459 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
1460 cg.is_active = 1 AND
1461 cf.is_active = 1 AND
1462 cf.is_searchable = 1 AND
1463 cf.data_type NOT IN ('ContactReference', 'Date') AND
1464 cf.id IN (" . implode(",", $customFieldIds) . ")";
1466 $dao = CRM_Core_DAO
::executeQuery($query);
1467 while ($dao->fetch()) {
1468 foreach ($customFieldCols as $key) {
1469 $customFields[$dao->table_name
. '_custom_' . $dao->id
][$key] = $dao->$key;
1471 if ($dao->option_group_id
) {
1472 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
1477 $entryFound = FALSE;
1478 foreach ($rows as $rowNum => $row) {
1479 foreach ($row as $tableCol => $val) {
1480 if (array_key_exists($tableCol, $customFields)) {
1481 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1486 // skip looking further in rows, if first row itself doesn't
1487 // have the column we need
1494 function formatCustomValues($value, $customField, $fieldValueMap) {
1495 if (CRM_Utils_System
::isNull($value)) {
1499 $htmlType = $customField['html_type'];
1501 switch ($customField['data_type']) {
1503 if ($value == '1') {
1504 $retValue = ts('Yes');
1507 $retValue = ts('No');
1512 $retValue = CRM_Utils_System
::formatWikiURL($value);
1524 if ($htmlType == 'Text') {
1525 $retValue = (float)$value;
1529 if ($htmlType == 'Text') {
1539 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
1544 if (in_array($htmlType, array(
1545 'Text', 'TextArea'))) {
1549 case 'StateProvince':
1552 switch ($htmlType) {
1553 case 'Multi-Select Country':
1554 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1555 $customData = array();
1556 foreach ($value as $val) {
1558 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
1561 $retValue = implode(', ', $customData);
1564 case 'Select Country':
1565 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
1568 case 'Select State/Province':
1569 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
1572 case 'Multi-Select State/Province':
1573 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1574 $customData = array();
1575 foreach ($value as $val) {
1577 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
1580 $retValue = implode(', ', $customData);
1585 case 'Autocomplete-Select':
1586 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1590 case 'AdvMulti-Select':
1591 case 'Multi-Select':
1592 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1593 $customData = array();
1594 foreach ($value as $val) {
1596 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1599 $retValue = implode(', ', $customData);
1614 function removeDuplicates(&$rows) {
1615 if (empty($this->_noRepeats
)) {
1618 $checkList = array();
1620 foreach ($rows as $key => $list) {
1621 foreach ($list as $colName => $colVal) {
1622 if (array_key_exists($colName, $checkList) &&
1623 $checkList[$colName] == $colVal) {
1624 $rows[$key][$colName] = "";
1626 if (in_array($colName, $this->_noRepeats
)) {
1627 $checkList[$colName] = $colVal;
1633 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1634 foreach ($row as $colName => $colVal) {
1635 if (in_array($colName, $fields)) {
1636 $row[$colName] = $row[$colName];
1638 elseif (isset($this->_columnHeaders
[$colName])) {
1640 $row[$colName] = "Subtotal";
1644 unset($row[$colName]);
1650 function grandTotal(&$rows) {
1651 if (!$this->_rollup ||
($this->_rollup
== '') ||
1652 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
1656 $lastRow = array_pop($rows);
1658 foreach ($this->_columnHeaders
as $fld => $val) {
1659 if (!in_array($fld, $this->_statFields
)) {
1660 if (!$this->_grandFlag
) {
1661 $lastRow[$fld] = "Grand Total";
1662 $this->_grandFlag
= TRUE;
1665 $lastRow[$fld] = "";
1670 $this->assign('grandStat', $lastRow);
1674 function formatDisplay(&$rows, $pager = TRUE) {
1675 // set pager based on if any limit was applied in the query.
1680 // allow building charts if any
1681 if (!empty($this->_params
['charts']) && !empty($rows)) {
1682 $this->buildChart($rows);
1683 $this->assign('chartEnabled', TRUE);
1684 $this->_chartId
= "{$this->_params['charts']}_" . ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' . session_id();
1685 $this->assign('chartId', $this->_chartId
);
1688 // unset columns not to be displayed.
1689 foreach ($this->_columnHeaders
as $key => $value) {
1690 if (is_array($value) && isset($value['no_display'])) {
1691 unset($this->_columnHeaders
[$key]);
1695 // unset columns not to be displayed.
1696 if (!empty($rows)) {
1697 foreach ($this->_noDisplay
as $noDisplayField) {
1698 foreach ($rows as $rowNum => $row) {
1699 unset($this->_columnHeaders
[$noDisplayField]);
1704 // build array of section totals
1705 $this->sectionTotals();
1707 // process grand-total row
1708 $this->grandTotal($rows);
1710 // use this method for formatting rows for display purpose.
1711 $this->alterDisplay($rows);
1712 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
1714 // use this method for formatting custom rows for display purpose.
1715 $this->alterCustomDataDisplay($rows);
1718 function buildChart(&$rows) {
1719 // override this method for building charts.
1722 // select() method below has been added recently (v3.3), and many of the report templates might
1723 // still be having their own select() method. We should fix them as and when encountered and move
1724 // towards generalizing the select() method below.
1728 foreach ($this->_columns
as $tableName => $table) {
1729 if (array_key_exists('fields', $table)) {
1730 foreach ($table['fields'] as $fieldName => $field) {
1731 if ($tableName == 'civicrm_address') {
1732 $this->_addressField
= TRUE;
1734 if ($tableName == 'civicrm_email') {
1735 $this->_emailField
= TRUE;
1737 if ($tableName == 'civicrm_phone') {
1738 $this->_phoneField
= TRUE;
1741 if (CRM_Utils_Array
::value('required', $field) ||
1742 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
1745 // 1. In many cases we want select clause to be built in slightly different way
1746 // for a particular field of a particular type.
1747 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1749 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1750 if ($selectClause) {
1751 $select[] = $selectClause;
1755 // include statistics columns only if set
1756 if (CRM_Utils_Array
::value('statistics', $field)) {
1757 foreach ($field['statistics'] as $stat => $label) {
1758 $alias = "{$tableName}_{$fieldName}_{$stat}";
1759 switch (strtolower($stat)) {
1762 $select[] = "$stat({$field['dbAlias']}) as $alias";
1763 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1764 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1765 $this->_statFields
[$label] = $alias;
1766 $this->_selectAliases
[] = $alias;
1770 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1771 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1772 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1773 $this->_statFields
[$label] = $alias;
1774 $this->_selectAliases
[] = $alias;
1777 case 'count_distinct':
1778 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1779 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1780 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
1781 $this->_statFields
[$label] = $alias;
1782 $this->_selectAliases
[] = $alias;
1786 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1787 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1788 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1789 $this->_statFields
[$label] = $alias;
1790 $this->_selectAliases
[] = $alias;
1796 $alias = "{$tableName}_{$fieldName}";
1797 $select[] = "{$field['dbAlias']} as $alias";
1798 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
1799 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
1800 $this->_selectAliases
[] = $alias;
1806 // select for group bys
1807 if (array_key_exists('group_bys', $table)) {
1808 foreach ($table['group_bys'] as $fieldName => $field) {
1810 if ($tableName == 'civicrm_address') {
1811 $this->_addressField
= TRUE;
1813 if ($tableName == 'civicrm_email') {
1814 $this->_emailField
= TRUE;
1816 if ($tableName == 'civicrm_phone') {
1817 $this->_phoneField
= TRUE;
1819 // 1. In many cases we want select clause to be built in slightly different way
1820 // for a particular field of a particular type.
1821 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1823 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1824 if ($selectClause) {
1825 $select[] = $selectClause;
1829 if (!empty($this->_params
['group_bys']) && CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])
1830 && !empty($this->_params
['group_bys_freq'])) {
1831 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1833 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1834 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1835 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1836 $field['title'] = 'Week';
1840 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1841 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1842 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1843 $field['title'] = 'Year';
1847 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1848 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1849 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1850 $field['title'] = 'Month';
1854 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1855 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1856 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1857 $field['title'] = 'Quarter';
1860 // for graphs and charts -
1861 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
1862 $this->_interval
= $field['title'];
1863 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1864 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1865 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
1867 // just to make sure these values are transfered to rows.
1868 // since we 'll need them for calculation purpose,
1869 // e.g making subtotals look nicer or graphs
1870 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1871 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1878 $this->_select
= "SELECT " . implode(', ', $select) . " ";
1881 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1886 $this->storeWhereHavingClauseArray();
1888 if (empty($this->_whereClauses
)) {
1889 $this->_where
= "WHERE ( 1 ) ";
1890 $this->_having
= "";
1893 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
1896 if ($this->_aclWhere
) {
1897 $this->_where
.= " AND {$this->_aclWhere} ";
1900 if (!empty($this->_havingClauses
)) {
1901 // use this clause to construct group by clause.
1902 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
1907 * Store Where clauses into an array - breaking out this step makes
1908 * over-riding more flexible as the clauses can be used in constructing a
1909 * temp table that may not be part of the final where clause or added
1910 * in other functions
1912 function storeWhereHavingClauseArray(){
1913 foreach ($this->_columns
as $tableName => $table) {
1914 if (array_key_exists('filters', $table)) {
1915 foreach ($table['filters'] as $fieldName => $field) {
1916 // respect pseudofield to filter spec so fields can be marked as
1917 // not to be handled here
1918 if(!empty($field['pseudofield'])){
1922 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
1923 if (CRM_Utils_Array
::value('operatorType', $field) == CRM_Report_Form
::OP_MONTH
) {
1924 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1925 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
1926 if (is_array($value) && !empty($value)) {
1927 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
1931 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
1932 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
1933 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
1934 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
1935 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
1936 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
1940 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
1942 $clause = $this->whereClause($field,
1944 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
1945 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
1946 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
1951 if (!empty($clause)) {
1952 if (CRM_Utils_Array
::value('having', $field)) {
1953 $this->_havingClauses
[] = $clause;
1956 $this->_whereClauses
[] = $clause;
1964 function processReportMode() {
1965 $buttonName = $this->controller
->getButtonName();
1967 $output = CRM_Utils_Request
::retrieve(
1970 CRM_Core_DAO
::$_nullObject
1974 CRM_Utils_Request
::retrieve(
1977 CRM_Core_DAO
::$_nullObject
1980 $this->_absoluteUrl
= FALSE;
1982 $this->assign('printOnly', FALSE);
1984 if ($this->_printButtonName
== $buttonName ||
$output == 'print' ||
($this->_sendmail
&& !$output)) {
1985 $this->assign('printOnly', TRUE);
1987 $this->assign('outputMode', 'print');
1988 $this->_outputMode
= 'print';
1989 if ($this->_sendmail
) {
1990 $this->_absoluteUrl
= TRUE;
1993 elseif ($this->_pdfButtonName
== $buttonName ||
$output == 'pdf') {
1994 $this->assign('printOnly', TRUE);
1996 $this->assign('outputMode', 'pdf');
1997 $this->_outputMode
= 'pdf';
1998 $this->_absoluteUrl
= TRUE;
2000 elseif ($this->_csvButtonName
== $buttonName ||
$output == 'csv') {
2001 $this->assign('printOnly', TRUE);
2003 $this->assign('outputMode', 'csv');
2004 $this->_outputMode
= 'csv';
2005 $this->_absoluteUrl
= TRUE;
2007 elseif ($this->_groupButtonName
== $buttonName ||
$output == 'group') {
2008 $this->assign('outputMode', 'group');
2009 $this->_outputMode
= 'group';
2011 elseif ($output == 'create_report' && $this->_criteriaForm
) {
2012 $this->assign('outputMode', 'create_report');
2013 $this->_outputMode
= 'create_report';
2016 $this->assign('outputMode', 'html');
2017 $this->_outputMode
= 'html';
2020 // Get today's date to include in printed reports
2022 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2023 $this->assign('reportDate', $reportDate);
2027 function beginPostProcess() {
2028 $this->_params
= $this->controller
->exportValues($this->_name
);
2030 if (empty($this->_params
) &&
2033 $this->_params
= $this->_formValues
;
2036 // hack to fix params when submitted from dashboard, CRM-8532
2037 // fields array is missing because form building etc is skipped
2038 // in dashboard mode for report
2039 if (!CRM_Utils_Array
::value('fields', $this->_params
) && !$this->_noFields
) {
2040 $this->_params
= $this->_formValues
;
2043 $this->_formValues
= $this->_params
;
2044 if (CRM_Core_Permission
::check('administer Reports') &&
2045 isset($this->_id
) &&
2046 ($this->_instanceButtonName
== $this->controller
->getButtonName() . '_save' ||
2047 $this->_chartButtonName
== $this->controller
->getButtonName()
2050 $this->assign('updateReportButton', TRUE);
2052 $this->processReportMode();
2055 function buildQuery($applyLimit = TRUE) {
2058 $this->customDataFrom();
2063 // order_by columns not selected for display need to be included in SELECT
2064 $unselectedSectionColumns = $this->unselectedSectionColumns();
2065 foreach ($unselectedSectionColumns as $alias => $section) {
2066 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2069 if ($applyLimit && !CRM_Utils_Array
::value('charts', $this->_params
)) {
2072 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2074 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2078 function groupBy() {
2079 $groupBys = array();
2080 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2081 is_array($this->_params
['group_bys']) &&
2082 !empty($this->_params
['group_bys'])
2084 foreach ($this->_columns
as $tableName => $table) {
2085 if (array_key_exists('group_bys', $table)) {
2086 foreach ($table['group_bys'] as $fieldName => $field) {
2087 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2088 $groupBys[] = $field['dbAlias'];
2095 if (!empty($groupBys)) {
2096 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2100 function orderBy() {
2101 $this->_orderBy
= "";
2102 $this->_sections
= array();
2103 $this->storeOrderByArray();
2104 if(!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP'){
2105 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2107 $this->assign('sections', $this->_sections
);
2111 * In some cases other functions want to know which fields are selected for ordering by
2112 * Separating this into a separate function allows it to be called separately from constructing
2113 * the order by clause
2115 function storeOrderByArray() {
2116 $orderBys = array();
2118 if (CRM_Utils_Array
::value('order_bys', $this->_params
) &&
2119 is_array($this->_params
['order_bys']) &&
2120 !empty($this->_params
['order_bys'])
2123 // Proces order_bys in user-specified order
2124 foreach ($this->_params
['order_bys'] as $orderBy) {
2125 $orderByField = array();
2126 foreach ($this->_columns
as $tableName => $table) {
2127 if (array_key_exists('order_bys', $table)) {
2128 // For DAO columns defined in $this->_columns
2129 $fields = $table['order_bys'];
2131 elseif (array_key_exists('extends', $table)) {
2132 // For custom fields referenced in $this->_customGroupExtends
2133 $fields = $table['fields'];
2135 if (!empty($fields) && is_array($fields)) {
2136 foreach ($fields as $fieldName => $field) {
2137 if ($fieldName == $orderBy['column']) {
2138 $orderByField = array_merge($field, $orderBy);
2139 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2146 if (!empty($orderByField)) {
2147 $this->_orderByFields
[] = $orderByField;
2148 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2150 // Record any section headers for assignment to the template
2151 if (CRM_Utils_Array
::value('section', $orderBy)) {
2152 $this->_sections
[$orderByField['tplField']] = $orderByField;
2158 $this->_orderByArray
= $orderBys;
2160 $this->assign('sections', $this->_sections
);
2163 function unselectedSectionColumns() {
2164 $selectColumns = array();
2165 foreach ($this->_columns
as $tableName => $table) {
2166 if (array_key_exists('fields', $table)) {
2167 foreach ($table['fields'] as $fieldName => $field) {
2168 if (CRM_Utils_Array
::value('required', $field) ||
2169 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
2172 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2178 if (is_array($this->_sections
)) {
2179 return array_diff_key($this->_sections
, $selectColumns);
2186 function buildRows($sql, &$rows) {
2187 $dao = CRM_Core_DAO
::executeQuery($sql);
2188 if (!is_array($rows)) {
2192 // use this method to modify $this->_columnHeaders
2193 $this->modifyColumnHeaders();
2195 $unselectedSectionColumns = $this->unselectedSectionColumns();
2197 while ($dao->fetch()) {
2199 foreach ($this->_columnHeaders
as $key => $value) {
2200 if (property_exists($dao, $key)) {
2201 $row[$key] = $dao->$key;
2205 // section headers not selected for display need to be added to row
2206 foreach ($unselectedSectionColumns as $key => $values) {
2207 if (property_exists($dao, $key)) {
2208 $row[$key] = $dao->$key;
2217 * When "order by" fields are marked as sections, this assigns to the template
2218 * an array of total counts for each section. This data is used by the Smarty
2219 * plugin {sectionTotal}
2221 function sectionTotals() {
2223 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2224 if (empty($this->_selectAliases
)) {
2228 if (!empty($this->_sections
)) {
2229 // build the query with no LIMIT clause
2230 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2231 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2233 // pull section aliases out of $this->_sections
2234 $sectionAliases = array_keys($this->_sections
);
2237 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2238 $ifnulls[] = "ifnull($alias, '') as $alias";
2241 /* Group (un-limited) report by all aliases and get counts. This might
2242 * be done more efficiently when the contents of $sql are known, ie. by
2243 * overriding this method in the report class.
2247 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2249 // initialize array of total counts
2251 $dao = CRM_Core_DAO
::executeQuery($query);
2252 while ($dao->fetch()) {
2254 // let $this->_alterDisplay translate any integer ids to human-readable values.
2255 $rows[0] = $dao->toArray();
2256 $this->alterDisplay($rows);
2259 // add totals for all permutations of section values
2262 $aliasCount = count($sectionAliases);
2263 foreach ($sectionAliases as $alias) {
2264 $values[] = $row[$alias];
2265 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2266 if ($i == $aliasCount) {
2267 // the last alias is the lowest-level section header; use count as-is
2268 $totals[$key] = $dao->ct
;
2271 // other aliases are higher level; roll count into their total
2272 $totals[$key] +
= $dao->ct
;
2276 $this->assign('sectionTotals', $totals);
2280 function modifyColumnHeaders() {
2281 // use this method to modify $this->_columnHeaders
2284 function doTemplateAssignment(&$rows) {
2285 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2286 $this->assign_by_ref('rows', $rows);
2287 $this->assign('statistics', $this->statistics($rows));
2290 // override this method to build your own statistics
2291 function statistics(&$rows) {
2292 $statistics = array();
2294 $count = count($rows);
2296 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
2300 $this->countStat($statistics, $count);
2302 $this->groupByStat($statistics);
2304 $this->filterStat($statistics);
2309 function countStat(&$statistics, $count) {
2310 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2314 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
2315 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2316 'value' => $this->_rowsFound
,
2321 function groupByStat(&$statistics) {
2322 if (CRM_Utils_Array
::value('group_bys', $this->_params
) &&
2323 is_array($this->_params
['group_bys']) &&
2324 !empty($this->_params
['group_bys'])
2326 foreach ($this->_columns
as $tableName => $table) {
2327 if (array_key_exists('group_bys', $table)) {
2328 foreach ($table['group_bys'] as $fieldName => $field) {
2329 if (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys'])) {
2330 $combinations[] = $field['title'];
2335 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2336 'value' => implode(' & ', $combinations),
2341 function filterStat(&$statistics) {
2342 foreach ($this->_columns
as $tableName => $table) {
2343 if (array_key_exists('filters', $table)) {
2344 foreach ($table['filters'] as $fieldName => $field) {
2345 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
&& CRM_Utils_Array
::value('operatorType', $field) != CRM_Report_Form
::OP_MONTH
) {
2348 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2349 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
2350 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
2351 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
2352 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
2354 $from_time_format = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
) ?
'h' : 'd';
2355 $from = CRM_Utils_Date
::customFormat($from, null, array($from_time_format));
2357 $to_time_format = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
) ?
'h' : 'd';
2358 $to = CRM_Utils_Date
::customFormat($to, null, array($to_time_format));
2361 $statistics['filters'][] = array(
2362 'title' => $field['title'],
2363 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2366 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
2367 array_keys($this->getOperationPair(CRM_Report_FORM
::OP_DATE
))
2369 $pair = $this->getOperationPair(CRM_Report_FORM
::OP_DATE
);
2370 $statistics['filters'][] = array(
2371 'title' => $field['title'],
2372 'value' => $pair[$rel],
2377 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2380 $pair = $this->getOperationPair(
2381 CRM_Utils_Array
::value('operatorType', $field),
2384 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
2385 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
2386 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2387 if (in_array($op, array(
2388 'bw', 'nbw')) && ($min ||
$max)) {
2389 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2391 elseif ($op == 'nll' ||
$op == 'nnll') {
2392 $value = $pair[$op];
2394 elseif (is_array($val) && (!empty($val))) {
2395 $options = CRM_Utils_Array
::value('options', $field, array());
2396 foreach ($val as $key => $valIds) {
2397 if (isset($options[$valIds])) {
2398 $val[$key] = $options[$valIds];
2401 $pair[$op] = (count($val) == 1) ?
(($op == 'notin') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
2402 $val = implode(', ', $val);
2403 $value = "{$pair[$op]} " . $val;
2405 elseif (!is_array($val) && (!empty($val) ||
$val == '0') && isset($field['options']) &&
2406 is_array($field['options']) && !empty($field['options'])
2408 $value = CRM_Utils_Array
::value($op, $pair) . " " . CRM_Utils_Array
::value($val, $field['options'], $val);
2411 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
2415 $statistics['filters'][] = array('title' => CRM_Utils_Array
::value('title', $field),
2425 function endPostProcess(&$rows = NULL) {
2426 if ( $this->_storeResultSet
) {
2427 $this->_resultSet
= $rows;
2430 if ($this->_outputMode
== 'print' ||
2431 $this->_outputMode
== 'pdf' ||
2435 $content = $this->compileContent();
2436 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
2440 if ($this->_sendmail
) {
2441 $config = CRM_Core_Config
::singleton();
2442 $attachments = array();
2444 if ($this->_outputMode
== 'csv') {
2445 $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'];
2447 $csvFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.csv');
2448 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
2449 file_put_contents($csvFullFilename, $csvContent);
2450 $attachments[] = array(
2451 'fullPath' => $csvFullFilename,
2452 'mime_type' => 'text/csv',
2453 'cleanName' => 'CiviReport.csv',
2456 if ($this->_outputMode
== 'pdf') {
2457 // generate PDF content
2458 $pdfFullFilename = $config->templateCompileDir
. CRM_Utils_File
::makeFileName('CiviReport.pdf');
2459 file_put_contents($pdfFullFilename,
2460 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
2461 TRUE, array('orientation' => 'landscape')
2464 // generate Email Content
2465 $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'];
2467 $attachments[] = array(
2468 'fullPath' => $pdfFullFilename,
2469 'mime_type' => 'application/pdf',
2470 'cleanName' => 'CiviReport.pdf',
2474 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
2475 $this->_outputMode
, $attachments
2477 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2480 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2483 CRM_Utils_System
::redirect(CRM_Utils_System
::url(CRM_Utils_System
::currentPath(), 'reset=1'));
2485 elseif ($this->_outputMode
== 'print') {
2489 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
2490 $config = CRM_Core_Config
::singleton();
2491 //get chart image name
2492 $chartImg = $this->_chartId
. '.png';
2493 //get image url path
2494 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) . 'openFlashChart/';
2495 $uploadUrl .= $chartImg;
2496 //get image doc path to overwrite
2497 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) . 'openFlashChart/' . $chartImg;
2499 $chart = imagecreatefrompng($uploadUrl);
2500 //convert it into formattd png
2501 header('Content-type: image/png');
2502 //overwrite with same image
2503 imagepng($chart, $uploadImg);
2505 imagedestroy($chart);
2507 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2509 CRM_Utils_System
::civiExit();
2511 elseif ($this->_outputMode
== 'csv') {
2512 CRM_Report_Utils_Report
::export2csv($this, $rows);
2514 elseif ($this->_outputMode
== 'group') {
2515 $group = $this->_params
['groups'];
2516 $this->add2group($group);
2518 elseif ($this->_instanceButtonName
== $this->controller
->getButtonName()) {
2519 CRM_Report_Form_Instance
::postProcess($this);
2521 elseif ($this->_createNewButtonName
== $this->controller
->getButtonName() ||
2522 $this->_outputMode
== 'create_report' ) {
2523 $this->_createNew
= TRUE;
2524 CRM_Report_Form_Instance
::postProcess($this);
2528 function storeResultSet() {
2529 $this->_storeResultSet
= TRUE;
2532 function getResultSet() {
2533 return $this->_resultSet
;
2537 * Get Template file name - use default form template if a specific one has not been set up for this report
2540 function getTemplateFileName(){
2541 $defaultTpl = parent
::getTemplateFileName();
2542 $template = CRM_Core_Smarty
::singleton();
2543 if (!$template->template_exists($defaultTpl)) {
2544 $defaultTpl = 'CRM/Report/Form.tpl';
2550 * Compile the report content
2552 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2554 function compileContent(){
2555 $templateFile = $this->getHookedTemplateFileName();
2556 return $this->_formValues
['report_header'] . CRM_Core_Form
::$_template->fetch($templateFile) . $this->_formValues
['report_footer'];
2560 function postProcess() {
2561 // get ready with post process params
2562 $this->beginPostProcess();
2565 $sql = $this->buildQuery();
2567 // build array of result based on column headers. This method also allows
2568 // modifying column headers before using it to build result set i.e $rows.
2570 $this->buildRows($sql, $rows);
2572 // format result set.
2573 $this->formatDisplay($rows);
2575 // assign variables to templates
2576 $this->doTemplateAssignment($rows);
2578 // do print / pdf / instance stuff if needed
2579 $this->endPostProcess($rows);
2582 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
2583 // lets do the pager if in html mode
2584 $this->_limit
= NULL;
2585 if ($this->_outputMode
== 'html' ||
$this->_outputMode
== 'group') {
2586 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
2588 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
2590 if (!$pageId && !empty($_POST)) {
2591 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2592 $pageId = max((int)@$_POST['crmPID_B'], 1);
2594 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2595 $pageId = max((int)@$_POST['crmPID'], 1);
2597 unset($_POST['crmPID_B'], $_POST['crmPID']);
2600 $pageId = $pageId ?
$pageId : 1;
2601 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
2602 $offset = ($pageId - 1) * $rowCount;
2604 $this->_limit
= " LIMIT $offset, " . $rowCount;
2605 return array($offset, $rowCount);
2609 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
2610 if ($this->_limit
&& ($this->_limit
!= '')) {
2611 $sql = "SELECT FOUND_ROWS();";
2612 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
2614 'total' => $this->_rowsFound
,
2615 'rowCount' => $rowCount,
2616 'status' => ts('Records') . ' %%StatusMessage%%',
2617 'buttonBottom' => 'PagerBottomButton',
2618 'buttonTop' => 'PagerTopButton',
2619 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
2622 $pager = new CRM_Utils_Pager($params);
2623 $this->assign_by_ref('pager', $pager);
2627 function whereGroupClause($field, $value, $op) {
2629 $smartGroupQuery = "";
2631 $group = new CRM_Contact_DAO_Group();
2632 $group->is_active
= 1;
2634 $smartGroups = array();
2635 while ($group->fetch()) {
2636 if (in_array($group->id
, $this->_params
['gid_value']) && $group->saved_search_id
) {
2637 $smartGroups[] = $group->id
;
2641 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
2643 $smartGroupQuery = '';
2644 if (!empty($smartGroups)) {
2645 $smartGroups = implode(',', $smartGroups);
2646 $smartGroupQuery = " UNION DISTINCT
2647 SELECT DISTINCT smartgroup_contact.contact_id
2648 FROM civicrm_group_contact_cache smartgroup_contact
2649 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2652 $sqlOp = $this->getSQLOperator($op);
2653 if (!is_array($value)) {
2654 $value = array($value);
2656 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2658 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2659 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2660 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2661 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2662 {$smartGroupQuery} ) ";
2665 function whereTagClause($field, $value, $op) {
2666 // not using left join in query because if any contact
2667 // belongs to more than one tag, results duplicate
2669 $sqlOp = $this->getSQLOperator($op);
2670 if (!is_array($value)) {
2671 $value = array($value);
2673 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2675 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2676 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2677 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2678 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2681 function buildACLClause($tableAlias = 'contact_a') {
2682 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
2685 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2686 if (empty($this->_customGroupExtends
)) {
2689 if (!is_array($this->_customGroupExtends
)) {
2690 $this->_customGroupExtends
= array($this->_customGroupExtends
);
2692 $customGroupWhere = '';
2693 if (!empty($permCustomGroupIds)) {
2694 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2697 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2698 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2699 FROM civicrm_custom_group cg
2700 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2701 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2703 cg.is_active = 1 AND
2704 cf.is_active = 1 AND
2705 cf.is_searchable = 1
2706 ORDER BY cg.weight, cf.weight";
2707 $customDAO = CRM_Core_DAO
::executeQuery($sql);
2710 while ($customDAO->fetch()) {
2711 if ($customDAO->table_name
!= $curTable) {
2712 $curTable = $customDAO->table_name
;
2713 $curFields = $curFilters = array();
2716 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2717 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
2718 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
2719 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
2722 'fields', 'filters', 'group_bys') as $colKey) {
2723 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
2724 $this->_columns
[$curTable][$colKey] = array();
2728 $fieldName = 'custom_' . $customDAO->cf_id
;
2731 // this makes aliasing work in favor
2732 $curFields[$fieldName] = array(
2733 'name' => $customDAO->column_name
,
2734 'title' => $customDAO->label
,
2735 'dataType' => $customDAO->data_type
,
2736 'htmlType' => $customDAO->html_type
,
2739 if ($this->_customGroupFilters
) {
2740 // this makes aliasing work in favor
2741 $curFilters[$fieldName] = array(
2742 'name' => $customDAO->column_name
,
2743 'title' => $customDAO->label
,
2744 'dataType' => $customDAO->data_type
,
2745 'htmlType' => $customDAO->html_type
,
2749 switch ($customDAO->data_type
) {
2752 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
2753 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
2754 // CRM-6946, show time part for datetime date fields
2755 if ($customDAO->time_format
) {
2756 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
2761 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
2762 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2766 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2770 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
2771 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
2775 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2776 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
2780 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
2781 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
2785 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2787 if (!empty($customDAO->option_group_id
)) {
2788 if (in_array($customDAO->html_type
, array(
2789 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2790 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2793 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2795 if ($this->_customGroupFilters
) {
2796 $curFilters[$fieldName]['options'] = array();
2797 $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')));
2798 while ($ogDAO->fetch()) {
2799 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
2805 case 'StateProvince':
2806 if (in_array($customDAO->html_type
, array(
2807 'Multi-Select State/Province'))) {
2808 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2811 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2813 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
2817 if (in_array($customDAO->html_type
, array(
2818 'Multi-Select Country'))) {
2819 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
2822 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
2824 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
2827 case 'ContactReference':
2828 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2829 $curFilters[$fieldName]['name'] = 'display_name';
2830 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2832 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2833 $curFields[$fieldName]['name'] = 'display_name';
2834 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2838 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2839 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
2842 if (!array_key_exists('type', $curFields[$fieldName])) {
2843 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
2847 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
2849 if ($this->_customGroupFilters
) {
2850 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
2852 if ($this->_customGroupGroupBy
) {
2853 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
2858 function customDataFrom() {
2859 if (empty($this->_customGroupExtends
)) {
2862 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
2864 foreach ($this->_columns
as $table => $prop) {
2865 if (substr($table, 0, 13) == 'civicrm_value' ||
substr($table, 0, 12) == 'custom_value') {
2866 $extendsTable = $mapper[$prop['extends']];
2868 // check field is in params
2869 if (!$this->isFieldSelected($prop)) {
2873 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
2875 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$this->_aliases[$extendsTable]}.id";
2876 // handle for ContactReference
2877 if (array_key_exists('fields', $prop)) {
2878 foreach ($prop['fields'] as $fieldName => $field) {
2879 if (CRM_Utils_Array
::value('dataType', $field) == 'ContactReference') {
2880 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
2882 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2890 function isFieldSelected($prop) {
2895 if (!empty($this->_params
['fields'])) {
2896 foreach (array_keys($prop['fields']) as $fieldAlias) {
2897 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
2898 if ($customFieldId) {
2899 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
2903 //might be survey response field.
2904 if (CRM_Utils_Array
::value('survey_response', $this->_params
['fields']) &&
2905 CRM_Utils_Array
::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
2913 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
2914 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
2915 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2921 if (!empty($this->_params
['order_bys'])) {
2922 foreach (array_keys($prop['fields']) as $fieldAlias) {
2923 foreach ($this->_params
['order_bys'] as $orderBy) {
2924 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2931 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
2932 foreach ($prop['filters'] as $fieldAlias => $val) {
2934 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
2935 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
2936 (!empty($this->_params
[$fieldAlias . '_' . $attach])
2937 ||
($attach != 'relative' && $this->_params
[$fieldAlias . '_' . $attach] == '0')
2943 if (CRM_Utils_Array
::value($fieldAlias . '_op', $this->_params
) &&
2944 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
2955 * Check for empty order_by configurations and remove them; also set
2956 * template to hide them.
2958 function preProcessOrderBy(&$formValues) {
2959 // Object to show/hide form elements
2960 $_showHide = new CRM_Core_ShowHideBlocks('', '');
2962 $_showHide->addShow('optionField_1');
2964 // Cycle through order_by options; skip any empty ones, and hide them as well
2967 if (!empty($formValues['order_bys'])) {
2968 foreach ($formValues['order_bys'] as $order_by) {
2969 if ($order_by['column'] && $order_by['column'] != '-') {
2970 $_showHide->addShow('optionField_' . $n);
2971 $orderBys[$n] = $order_by;
2976 for ($i = $n; $i <= 5; $i++
) {
2978 $_showHide->addHide('optionField_' . $i);
2982 // overwrite order_by options with modified values
2983 if (!empty($orderBys)) {
2984 $formValues['order_bys'] = $orderBys;
2987 $formValues['order_bys'] = array(1 => array('column' => '-'));
2990 // assign show/hide data to template
2991 $_showHide->addToTemplate();
2995 * Does table name have columns in SELECT clause?
2997 * @param string $tableName Name of table (index of $this->_columns array)
3001 function isTableSelected($tableName) {
3002 return in_array($tableName, $this->selectedTables());
3006 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3007 * (building the array if it's unset)
3009 * @return Array $this->_selectedTables
3011 function selectedTables() {
3012 if (!$this->_selectedTables
) {
3013 $orderByColumns = array();
3014 if (array_key_exists('order_bys', $this->_params
) && is_array($this->_params
['order_bys'])) {
3015 foreach ($this->_params
['order_bys'] as $orderBy) {
3016 $orderByColumns[] = $orderBy['column'];
3020 foreach ($this->_columns
as $tableName => $table) {
3021 if (array_key_exists('fields', $table)) {
3022 foreach ($table['fields'] as $fieldName => $field) {
3023 if (CRM_Utils_Array
::value('required', $field) ||
3024 CRM_Utils_Array
::value($fieldName, $this->_params
['fields'])
3026 $this->_selectedTables
[] = $tableName;
3031 if (array_key_exists('order_bys', $table)) {
3032 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3033 if (in_array($orderByName, $orderByColumns)) {
3034 $this->_selectedTables
[] = $tableName;
3039 if (array_key_exists('filters', $table)) {
3040 foreach ($table['filters'] as $filterName => $filter) {
3041 if (CRM_Utils_Array
::value("{$filterName}_value", $this->_params
) ||
3042 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nll' ||
3043 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) == 'nnll'
3045 $this->_selectedTables
[] = $tableName;
3052 return $this->_selectedTables
;
3056 * @deprecated - use getAddressColumns which is a more accurate description
3057 * and also accepts an array of options rather than a long list
3059 * function for adding address fields to construct function in reports
3060 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3061 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3062 * @return array address fields for construct clause
3064 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3065 'country_id' => TRUE)) {
3066 $addressFields = array(
3067 'civicrm_address' =>
3069 'dao' => 'CRM_Core_DAO_Address',
3073 array('title' => ts('Address Name'),
3074 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
3077 array('title' => ts('Street Address'),
3078 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
3080 'supplemental_address_1' =>
3081 array('title' => ts('Supplementary Address Field 1'),
3082 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
3084 'supplemental_address_2' =>
3085 array('title' => ts('Supplementary Address Field 2'),
3086 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
3090 'name' => 'street_number',
3091 'title' => ts('Street Number'),
3093 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
3097 'name' => 'street_name',
3098 'title' => ts('Street Name'),
3100 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
3104 'name' => 'street_unit',
3105 'title' => ts('Street Unit'),
3107 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
3110 array('title' => ts('City'),
3111 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
3114 array('title' => ts('Postal Code'),
3115 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
3118 array('title' => ts('County'),
3119 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
3121 'state_province_id' =>
3122 array('title' => ts('State/Province'),
3123 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
3126 array('title' => ts('Country'),
3127 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
3130 'grouping' => 'location-fields',
3135 $addressFields['civicrm_address']['filters'] = array(
3136 'street_number' => array('title' => ts('Street Number'),
3138 'name' => 'street_number',
3140 'street_name' => array('title' => ts('Street Name'),
3141 'name' => 'street_name',
3142 'operator' => 'like',
3144 'postal_code' => array('title' => ts('Postal Code'),
3146 'name' => 'postal_code',
3148 'city' => array('title' => ts('City'),
3149 'operator' => 'like',
3152 'county_id' => array(
3153 'name' => 'county_id',
3154 'title' => ts('County'),
3155 'type' => CRM_Utils_Type
::T_INT
,
3157 CRM_Report_Form
::OP_MULTISELECT
,
3159 CRM_Core_PseudoConstant
::county(),
3161 'state_province_id' => array(
3162 'name' => 'state_province_id',
3163 'title' => ts('State/Province'),
3164 'type' => CRM_Utils_Type
::T_INT
,
3166 CRM_Report_Form
::OP_MULTISELECT
,
3168 CRM_Core_PseudoConstant
::stateProvince(),
3170 'country_id' => array(
3171 'name' => 'country_id',
3172 'title' => ts('Country'),
3173 'type' => CRM_Utils_Type
::T_INT
,
3175 CRM_Report_Form
::OP_MULTISELECT
,
3177 CRM_Core_PseudoConstant
::country(),
3183 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3184 'street_number' => array('title' => 'Odd / Even Street Number'),
3185 'street_address' => NULL,
3187 'postal_code' => NULL,
3192 $addressFields['civicrm_address']['group_bys'] = array(
3193 'street_address' => NULL,
3195 'postal_code' => NULL,
3196 'state_province_id' =>
3197 array('title' => ts('State/Province'),
3200 array('title' => ts('Country'),
3203 array('title' => ts('County'),
3207 return $addressFields;
3211 * Do AlterDisplay processing on Address Fields
3213 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3214 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
3215 $entryFound = FALSE;
3217 if (array_key_exists('civicrm_address_country_id', $row)) {
3218 if ($value = $row['civicrm_address_country_id']) {
3219 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
3220 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3221 "reset=1&force=1&{$criteriaQueryParams}&" .
3222 "country_id_op=in&country_id_value={$value}",
3223 $this->_absoluteUrl
, $this->_id
3225 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3226 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3233 if (array_key_exists('civicrm_address_county_id', $row)) {
3234 if ($value = $row['civicrm_address_county_id']) {
3235 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
3236 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3237 "reset=1&force=1&{$criteriaQueryParams}&" .
3238 "county_id_op=in&county_id_value={$value}",
3239 $this->_absoluteUrl
, $this->_id
3241 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3242 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3248 // handle state province
3249 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3250 if ($value = $row['civicrm_address_state_province_id']) {
3251 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
3253 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
3254 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3255 $this->_absoluteUrl
, $this->_id
3257 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3258 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3269 * Adjusts dates passed in to YEAR() for fiscal year.
3271 function fiscalYearOffset($fieldName) {
3272 $config = CRM_Core_Config
::singleton();
3273 $fy = $config->fiscalYearStart
;
3274 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
($fy['d'] == 1 && $fy['M'] == 1)) {
3275 return "YEAR( $fieldName )";
3277 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3281 * Add Address into From Table if required
3283 function addAddressFromClause() {
3284 // include address field if address column is to be included
3285 if ((isset($this->_addressField
) &&
3286 $this->_addressField
3288 $this->isTableSelected('civicrm_address')
3291 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3292 ON ({$this->_aliases['civicrm_contact']}.id =
3293 {$this->_aliases['civicrm_address']}.contact_id) AND
3294 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3299 * Add Phone into From Table if required
3301 function addPhoneFromClause() {
3302 // include address field if address column is to be included
3303 if ($this->isTableSelected('civicrm_phone')
3306 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3307 ON ({$this->_aliases['civicrm_contact']}.id =
3308 {$this->_aliases['civicrm_phone']}.contact_id) AND
3309 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3314 * Get phone columns to add to array
3315 * @param array $options
3316 * - prefix Prefix to add to table (in case of more than one instance of the table)
3317 * - prefix_label Label to give columns from this phone table instance
3318 * @return array phone columns definition
3320 function getPhoneColumns($options = array()){
3321 $defaultOptions = array(
3323 'prefix_label' => '',
3326 $options = array_merge($defaultOptions,$options);
3329 $options['prefix'] . 'civicrm_phone' => array(
3330 'dao' => 'CRM_Core_DAO_Phone',
3332 $options['prefix'] . 'phone' => array(
3333 'title' => ts($options['prefix_label'] . 'Phone'),
3343 * Get address columns to add to array
3344 * @param array $options
3345 * - prefix Prefix to add to table (in case of more than one instance of the table)
3346 * - prefix_label Label to give columns from this address table instance
3347 * @return array address columns definition
3349 function getAddressColumns($options = array()){
3350 $defaultOptions = array(
3352 'prefix_label' => '',
3356 'defaults' => array(
3359 $options = array_merge($defaultOptions,$options);
3360 return $this->addAddressFields(
3361 $options['group_by'],
3362 $options['order_by'],
3363 $options['filters'],
3364 $options['defaults']
3369 function add2group($groupID) {
3370 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
3371 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3372 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
3374 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3375 $dao = CRM_Core_DAO
::executeQuery($sql);
3377 $contact_ids = array();
3378 // Add resulting contacts to group
3379 while ($dao->fetch()) {
3380 if ($dao->addtogroup_contact_id
) {
3381 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
3385 if ( !empty($contact_ids) ) {
3386 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
3387 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3390 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
3395 /* function used for showing charts on print screen */
3396 static function uploadChartImage() {
3397 // upload strictly for '.png' images
3398 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
3399 if (preg_match('/\.png$/', $name)) {
3401 // POST data is usually string data, but we are passing a RAW .png
3402 // so PHP is a bit confused and $_POST is empty. But it has saved
3403 // the raw bits into $HTTP_RAW_POST_DATA
3405 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3407 // prepare the directory
3408 $config = CRM_Core_Config
::singleton();
3409 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir
) . '/openFlashChart/';
3410 if (!file_exists($defaultPath)) {
3411 mkdir($defaultPath, 0777, TRUE);
3414 // full path to the saved image including filename
3415 $destination = $defaultPath . $name;
3418 $jfh = fopen($destination, 'w') or die("can't open file");
3419 fwrite($jfh, $httpRawPostData);
3421 CRM_Utils_System
::civiExit();