3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Report_Form
31 class CRM_Report_Form
extends CRM_Core_Form
{
32 const ROW_COUNT_LIMIT
= 50;
35 * Operator types - used for displaying filter elements
45 OP_MULTISELECT_SEPARATOR
= 66,
50 * The id of the report instance
57 * The id of the report template
61 protected $_templateID;
69 protected $_noFields = FALSE;
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
77 protected $_columns = array();
80 * The set of filters in the report
84 protected $_filters = array();
87 * The set of optional columns in the report
91 protected $_options = array();
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
97 protected $_exposeContactID = TRUE;
100 * Set of statistic fields
104 protected $_statFields = array();
107 * Set of statistics data
111 protected $_statistics = array();
114 * List of fields not to be repeated during display
118 protected $_noRepeats = array();
121 * List of fields not to be displayed
125 protected $_noDisplay = array();
128 * Object type that a custom group extends
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
141 protected $_tagFilter = FALSE;
144 * specify entity table for tags filter
146 protected $_tagFilterTable = 'civicrm_contact';
149 * Build groups filter.
153 protected $_groupFilter = FALSE;
160 public $_navigation = array();
162 public $_drilldownReport = array();
165 * Array of tabs to display on report.
167 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
169 * $this->tabs['OrderBy'] = array(
170 * 'title' => ts('Sorting'),
171 * 'tpl' => 'OrderBy',
172 * 'div_label' => 'order-by',
177 protected $tabs = array();
180 * Should we add paging.
184 protected $addPaging = TRUE;
187 * An attribute for checkbox/radio form field layout
191 protected $_fourColumnAttribute = array(
192 '</td><td width="25%">',
193 '</td><td width="25%">',
194 '</td><td width="25%">',
198 protected $_force = 1;
200 protected $_params = NULL;
201 protected $_formValues = NULL;
202 protected $_instanceValues = NULL;
204 protected $_instanceForm = FALSE;
205 protected $_criteriaForm = FALSE;
207 protected $_instanceButtonName = NULL;
208 protected $_createNewButtonName = NULL;
209 protected $_printButtonName = NULL;
210 protected $_pdfButtonName = NULL;
211 protected $_csvButtonName = NULL;
212 protected $_groupButtonName = NULL;
213 protected $_chartButtonName = NULL;
214 protected $_csvSupported = TRUE;
215 protected $_add2groupSupported = TRUE;
216 protected $_groups = NULL;
217 protected $_grandFlag = FALSE;
218 protected $_rowsFound = NULL;
219 protected $_selectAliases = array();
220 protected $_rollup = NULL;
225 protected $_aliases = array();
241 protected $_limit = NULL;
244 * This can be set to specify a limit to the number of rows
245 * Since it is currently envisaged as part of the api usage it is only being applied
246 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
247 * of the code (see limit() fn.
251 protected $_limitValue = NULL;
254 * This can be set to specify row offset
255 * See notes on _limitValue
258 protected $_offsetValue = NULL;
262 protected $_sections = NULL;
263 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
264 protected $_absoluteUrl = FALSE;
267 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
271 protected $_storeResultSet = FALSE;
274 * When _storeResultSet Flag is set use this var to store result set in form of array
278 protected $_resultSet = array();
281 * To what frequency group-by a date column
285 protected $_groupByDateFreq = array(
287 'YEARWEEK' => 'Week',
288 'QUARTER' => 'Quarter',
293 * Variables to hold the acl inner join and where clause
295 protected $_aclFrom = NULL;
296 protected $_aclWhere = NULL;
299 * Array of DAO tables having columns included in SELECT or ORDER BY clause
303 protected $_selectedTables;
306 * Output mode e.g 'print', 'csv', 'pdf'.
310 protected $_outputMode;
313 * Format of any chart in use.
315 * (it's unclear if this could be merged with outputMode at this stage)
321 public $_having = NULL;
322 public $_select = NULL;
323 public $_selectClauses = array();
324 public $_columnHeaders = array();
325 public $_orderBy = NULL;
326 public $_orderByFields = array();
327 public $_orderByArray = array();
328 public $_groupBy = NULL;
329 public $_whereClauses = array();
330 public $_havingClauses = array();
333 * DashBoardRowCount Dashboard row count
336 public $_dashBoardRowCount;
339 * Is this being called without a form controller (ie. the report is being render outside the normal form
340 * - e.g the api is retrieving the rows
343 public $noController = FALSE;
346 * Variable to hold the currency alias
348 protected $_currencyColumn = NULL;
353 protected $_interval;
358 protected $_sendmail;
371 * @var string Report description.
373 public $_description;
376 * @var bool Is an address field selected.
377 * This was intended to determine if the address table should be joined in
378 * The isTableSelected function is now preferred for this purpose
380 protected $_addressField;
383 * @var bool Is an email field selected.
384 * This was intended to determine if the email table should be joined in
385 * The isTableSelected function is now preferred for this purpose
387 protected $_emailField;
390 * @var bool Is a phone field selected.
391 * This was intended to determine if the phone table should be joined in
392 * The isTableSelected function is now preferred for this purpose
394 protected $_phoneField;
397 * @var bool Create new report instance? (or update existing) on save.
399 protected $_createNew;
402 * SQL being run in this report.
404 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
413 public function __construct() {
414 parent
::__construct();
416 $this->addClass('crm-report-form');
418 if ($this->_tagFilter
) {
419 $this->buildTagFilter();
421 if ($this->_exposeContactID
) {
422 if (array_key_exists('civicrm_contact', $this->_columns
)) {
423 $this->_columns
['civicrm_contact']['fields']['exposed_id'] = array(
425 'title' => 'Contact ID',
431 if ($this->_groupFilter
) {
432 $this->buildGroupFilter();
435 // Get all custom groups
436 $allGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id');
438 // Get the custom groupIds for which the user has VIEW permission
439 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
440 // and addCustomDataToColumns() will allow access to all custom groups.
441 $permCustomGroupIds = array();
442 if (!CRM_Core_Permission
::check('access all custom data')) {
443 $permCustomGroupIds = CRM_ACL_API
::group(CRM_Core_Permission
::VIEW
, NULL, 'civicrm_custom_group', $allGroups, NULL);
444 // do not allow custom data for reports if user doesn't have
445 // permission to access custom data.
446 if (!empty($this->_customGroupExtends
) && empty($permCustomGroupIds)) {
447 $this->_customGroupExtends
= array();
451 // merge custom data columns to _columns list, if any
452 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
454 // add / modify display columns, filters ..etc
455 CRM_Utils_Hook
::alterReportVar('columns', $this->_columns
, $this);
457 //assign currencyColumn variable to tpl
458 $this->assign('currencyColumn', $this->_currencyColumn
);
462 * Shared pre-process function.
464 * If overriding preProcess function this should still be called.
468 public function preProcessCommon() {
470 = CRM_Utils_Request
::retrieve(
473 CRM_Core_DAO
::$_nullObject
476 $this->_dashBoardRowCount
477 = CRM_Utils_Request
::retrieve(
480 CRM_Core_DAO
::$_nullObject
483 $this->_section
= CRM_Utils_Request
::retrieve('section', 'Integer', CRM_Core_DAO
::$_nullObject);
485 $this->assign('section', $this->_section
);
486 CRM_Core_Region
::instance('page-header')->add(array(
487 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
489 if (!$this->noController
) {
490 $this->setID($this->get('instanceId'));
493 $this->setID(CRM_Report_Utils_Report
::getInstanceID());
495 $this->setID(CRM_Report_Utils_Report
::getInstanceIDForPath());
499 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
500 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
501 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
505 $this->assign('instanceId', $this->_id
);
506 $params = array('id' => $this->_id
);
507 $this->_instanceValues
= array();
508 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
510 $this->_instanceValues
512 if (empty($this->_instanceValues
)) {
513 CRM_Core_Error
::fatal("Report could not be loaded.");
515 $this->_title
= $this->_instanceValues
['title'];
516 if (!empty($this->_instanceValues
['permission']) &&
517 (!(CRM_Core_Permission
::check($this->_instanceValues
['permission']) ||
518 CRM_Core_Permission
::check('administer Reports')
521 CRM_Utils_System
::permissionDenied();
522 CRM_Utils_System
::civiExit();
525 $formValues = CRM_Utils_Array
::value('form_values', $this->_instanceValues
);
527 $this->_formValues
= unserialize($formValues);
530 $this->_formValues
= NULL;
533 $this->setOutputMode();
535 if ($this->_outputMode
== 'copy') {
536 $this->_createNew
= TRUE;
537 $this->_params
= $this->_formValues
;
538 $this->_params
['view_mode'] = 'criteria';
539 $this->_params
['title'] = ts('(copy)') . $this->getTitle();
540 // Do not pass go. Do not collect another chance to re-run the same query.
541 CRM_Report_Form_Instance
::postProcess($this);
544 // lets always do a force if reset is found in the url.
545 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
546 // in the comment line above these 2.
547 if (!empty($_REQUEST['reset'])
548 && !in_array(CRM_Utils_Request
::retrieve('output', 'String'), array('save', 'criteria'))) {
553 $this->assign('mode', 'instance');
555 elseif (!$this->noController
) {
556 list($optionValueID, $optionValue) = CRM_Report_Utils_Report
::getValueIDFromUrl();
557 $instanceCount = CRM_Report_Utils_Report
::getInstanceCount($optionValue);
558 if (($instanceCount > 0) && $optionValueID) {
559 $this->assign('instanceUrl',
560 CRM_Utils_System
::url('civicrm/report/list',
561 "reset=1&ovid=$optionValueID"
565 if ($optionValueID) {
566 $this->_description
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
570 $this->assign('mode', 'template');
573 // lets display the Report Settings section
574 $this->_instanceForm
= $this->_force ||
$this->_id ||
(!empty($_POST));
576 // Do not display Report Settings section if administer Reports permission is absent OR
577 // if report instance is reserved and administer reserved reports absent
578 if (!CRM_Core_Permission
::check('administer Reports') ||
579 ($this->_instanceValues
['is_reserved'] &&
580 !CRM_Core_Permission
::check('administer reserved reports'))
582 $this->_instanceForm
= FALSE;
585 $this->assign('criteriaForm', FALSE);
586 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
587 if (CRM_Core_Permission
::check('administer Reports') ||
588 CRM_Core_Permission
::check('access Report Criteria')
590 if (!$this->_instanceValues
['is_reserved'] ||
591 CRM_Core_Permission
::check('administer reserved reports')
593 $this->assign('criteriaForm', TRUE);
594 $this->_criteriaForm
= TRUE;
598 $this->_instanceButtonName
= $this->getButtonName('submit', 'save');
599 $this->_createNewButtonName
= $this->getButtonName('submit', 'next');
600 $this->_printButtonName
= $this->getButtonName('submit', 'print');
601 $this->_pdfButtonName
= $this->getButtonName('submit', 'pdf');
602 $this->_csvButtonName
= $this->getButtonName('submit', 'csv');
603 $this->_groupButtonName
= $this->getButtonName('submit', 'group');
604 $this->_chartButtonName
= $this->getButtonName('submit', 'chart');
610 public function addBreadCrumb() {
614 'title' => ts('Report Templates'),
615 'url' => CRM_Utils_System
::url('civicrm/admin/report/template/list', 'reset=1'),
619 CRM_Utils_System
::appendBreadCrumb($breadCrumbs);
623 * Pre process function.
625 * Called prior to build form.
627 public function preProcess() {
628 $this->preProcessCommon();
631 $this->addBreadCrumb();
634 foreach ($this->_columns
as $tableName => $table) {
636 if (!isset($table['alias'])) {
637 $this->_columns
[$tableName]['alias'] = substr($tableName, 8) .
641 $this->_columns
[$tableName]['alias'] = $table['alias'] . '_civireport';
644 $this->_aliases
[$tableName] = $this->_columns
[$tableName]['alias'];
646 $daoOrBaoName = NULL;
647 // higher preference to bao object
648 if (array_key_exists('bao', $table)) {
649 $daoOrBaoName = $table['bao'];
650 $expFields = $daoOrBaoName::exportableFields();
652 elseif (array_key_exists('dao', $table)) {
653 $daoOrBaoName = $table['dao'];
654 $expFields = $daoOrBaoName::export();
657 $expFields = array();
660 $doNotCopy = array('required');
662 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
663 foreach ($fieldGroups as $fieldGrp) {
664 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
665 foreach ($table[$fieldGrp] as $fieldName => $field) {
666 // $name is the field name used to reference the BAO/DAO export fields array
667 $name = isset($field['name']) ?
$field['name'] : $fieldName;
669 // Sometimes the field name key in the BAO/DAO export fields array is
670 // different from the actual database field name.
671 // Unset $field['name'] so that actual database field name can be obtained
672 // from the BAO/DAO export fields array.
673 unset($field['name']);
675 if (array_key_exists($name, $expFields)) {
676 foreach ($doNotCopy as $dnc) {
677 // unset the values we don't want to be copied.
678 unset($expFields[$name][$dnc]);
681 $this->_columns
[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
684 foreach ($expFields[$name] as $property => $val) {
685 if (!array_key_exists($property, $field)) {
686 $this->_columns
[$tableName][$fieldGrp][$fieldName][$property] = $val;
693 if (!empty($field['no_repeat'])) {
694 $this->_noRepeats
[] = "{$tableName}_{$fieldName}";
696 if (!empty($field['no_display'])) {
697 $this->_noDisplay
[] = "{$tableName}_{$fieldName}";
700 // set alias = table-name, unless already set
701 $alias = isset($field['alias']) ?
$field['alias'] : (
702 isset($this->_columns
[$tableName]['alias']) ?
$this->_columns
[$tableName]['alias'] : $tableName
704 $this->_columns
[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
706 // set name = fieldName, unless already set
707 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['name'])) {
708 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'] = $name;
711 // set dbAlias = alias.name, unless already set
712 if (!isset($this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
713 $this->_columns
[$tableName][$fieldGrp][$fieldName]['dbAlias']
715 $this->_columns
[$tableName][$fieldGrp][$fieldName]['name'];
718 // a few auto fills for filters
719 if ($fieldGrp == 'filters') {
720 // fill operator types
721 if (!array_key_exists('operatorType', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
722 switch (CRM_Utils_Array
::value('type', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
723 case CRM_Utils_Type
::T_MONEY
:
724 case CRM_Utils_Type
::T_FLOAT
:
725 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
728 case CRM_Utils_Type
::T_INT
:
729 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
732 case CRM_Utils_Type
::T_DATE
:
733 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
736 case CRM_Utils_Type
::T_BOOLEAN
:
737 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
738 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
739 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options']
750 array_key_exists('pseudoconstant', $this->_columns
[$tableName][$fieldGrp][$fieldName])
752 // with multiple options operator-type is generally multi-select
753 $this->_columns
[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
754 if (!array_key_exists('options', $this->_columns
[$tableName][$fieldGrp][$fieldName])) {
756 $this->_columns
[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant
::get($daoOrBaoName, $fieldName);
767 // copy filters to a separate handy variable
768 if (array_key_exists('filters', $table)) {
769 $this->_filters
[$tableName] = $this->_columns
[$tableName]['filters'];
772 if (array_key_exists('group_bys', $table)) {
773 $groupBys[$tableName] = $this->_columns
[$tableName]['group_bys'];
776 if (array_key_exists('fields', $table)) {
777 $reportFields[$tableName] = $this->_columns
[$tableName]['fields'];
782 $this->setDefaultValues(FALSE);
785 CRM_Report_Utils_Get
::processFilter($this->_filters
, $this->_defaults
);
786 CRM_Report_Utils_Get
::processGroupBy($groupBys, $this->_defaults
);
787 CRM_Report_Utils_Get
::processFields($reportFields, $this->_defaults
);
788 CRM_Report_Utils_Get
::processChart($this->_defaults
);
791 $this->_formValues
= $this->_defaults
;
792 $this->postProcess();
797 * Set default values.
799 * @param bool $freeze
803 public function setDefaultValues($freeze = TRUE) {
804 $freezeGroup = array();
806 // FIXME: generalizing form field naming conventions would reduce
807 // Lots of lines below.
808 foreach ($this->_columns
as $tableName => $table) {
809 if (array_key_exists('fields', $table)) {
810 foreach ($table['fields'] as $fieldName => $field) {
811 if (empty($field['no_display'])) {
812 if (isset($field['required'])) {
814 $this->_defaults
['fields'][$fieldName] = 1;
817 // find element object, so that we could use quickform's freeze method
818 // for required elements
819 $obj = $this->getElementFromGroup("fields", $fieldName);
821 $freezeGroup[] = $obj;
825 elseif (isset($field['default'])) {
826 $this->_defaults
['fields'][$fieldName] = $field['default'];
832 if (array_key_exists('group_bys', $table)) {
833 foreach ($table['group_bys'] as $fieldName => $field) {
834 if (isset($field['default'])) {
835 if (!empty($field['frequency'])) {
836 $this->_defaults
['group_bys_freq'][$fieldName] = 'MONTH';
838 $this->_defaults
['group_bys'][$fieldName] = $field['default'];
842 if (array_key_exists('filters', $table)) {
843 foreach ($table['filters'] as $fieldName => $field) {
844 if (isset($field['default'])) {
845 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
847 if (is_array($field['default'])) {
848 $this->_defaults
["{$fieldName}_from"] = CRM_Utils_Array
::value('from', $field['default']);
849 $this->_defaults
["{$fieldName}_to"] = CRM_Utils_Array
::value('to', $field['default']);
850 $this->_defaults
["{$fieldName}_relative"] = 0;
853 $this->_defaults
["{$fieldName}_relative"] = $field['default'];
857 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_INT
) && is_array($field['default'])) {
858 $this->_defaults
["{$fieldName}_min"] = CRM_Utils_Array
::value('min', $field['default']);
859 $this->_defaults
["{$fieldName}_max"] = CRM_Utils_Array
::value('max', $field['default']);
861 $this->_defaults
["{$fieldName}_value"] = $field['default'];
864 //assign default value as "in" for multiselect
865 //operator, To freeze the select element
866 if (CRM_Utils_Array
::value('operatorType', $field) ==
867 CRM_Report_Form
::OP_MULTISELECT
869 $this->_defaults
["{$fieldName}_op"] = 'in';
871 if (CRM_Utils_Array
::value('operatorType', $field) ==
872 CRM_Report_Form
::OP_ENTITYREF
874 $this->_defaults
["{$fieldName}_op"] = 'in';
876 elseif (CRM_Utils_Array
::value('operatorType', $field) ==
877 CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
879 $this->_defaults
["{$fieldName}_op"] = 'mhas';
881 elseif ($op = CRM_Utils_Array
::value('default_op', $field)) {
882 $this->_defaults
["{$fieldName}_op"] = $op;
888 empty($this->_formValues
['order_bys']) &&
889 (array_key_exists('order_bys', $table) &&
890 is_array($table['order_bys']))
892 if (!array_key_exists('order_bys', $this->_defaults
)) {
893 $this->_defaults
['order_bys'] = array();
895 foreach ($table['order_bys'] as $fieldName => $field) {
896 if (!empty($field['default']) ||
!empty($field['default_order']) ||
897 CRM_Utils_Array
::value('default_is_section', $field) ||
898 !empty($field['default_weight'])
901 'column' => $fieldName,
902 'order' => CRM_Utils_Array
::value('default_order', $field, 'ASC'),
903 'section' => CRM_Utils_Array
::value('default_is_section', $field, 0),
906 if (!empty($field['default_weight'])) {
907 $this->_defaults
['order_bys'][(int) $field['default_weight']] = $order_by;
910 array_unshift($this->_defaults
['order_bys'], $order_by);
916 foreach ($this->_options
as $fieldName => $field) {
917 if (isset($field['default'])) {
918 $this->_defaults
['options'][$fieldName] = $field['default'];
923 if (!empty($this->_submitValues
)) {
924 $this->preProcessOrderBy($this->_submitValues
);
927 $this->preProcessOrderBy($this->_defaults
);
930 // lets finish freezing task here itself
931 if (!empty($freezeGroup)) {
932 foreach ($freezeGroup as $elem) {
937 if ($this->_formValues
) {
938 $this->_defaults
= array_merge($this->_defaults
, $this->_formValues
);
941 if ($this->_instanceValues
) {
942 $this->_defaults
= array_merge($this->_defaults
, $this->_instanceValues
);
945 CRM_Report_Form_Instance
::setDefaultValues($this, $this->_defaults
);
947 return $this->_defaults
;
951 * Get element from group.
953 * @param string $group
954 * @param string $grpFieldName
958 public function getElementFromGroup($group, $grpFieldName) {
959 $eleObj = $this->getElement($group);
960 foreach ($eleObj->_elements
as $index => $obj) {
961 if ($grpFieldName == $obj->_attributes
['name']) {
969 * Setter for $_params.
971 * @param array $params
973 public function setParams($params) {
974 $this->_params
= $params;
980 * @param int $instanceID
982 public function setID($instanceID) {
983 $this->_id
= $instanceID;
987 * Setter for $_force.
989 * @param bool $isForce
991 public function setForce($isForce) {
992 $this->_force
= $isForce;
996 * Setter for $_limitValue.
998 * @param int $_limitValue
1000 public function setLimitValue($_limitValue) {
1001 $this->_limitValue
= $_limitValue;
1005 * Setter for $_offsetValue.
1007 * @param int $_offsetValue
1009 public function setOffsetValue($_offsetValue) {
1010 $this->_offsetValue
= $_offsetValue;
1014 * Setter for $addPaging.
1016 * @param bool $value
1018 public function setAddPaging($value) {
1019 $this->addPaging
= $value;
1023 * Getter for $_defaultValues.
1027 public function getDefaultValues() {
1028 return $this->_defaults
;
1032 * Add columns to report.
1034 public function addColumns() {
1037 foreach ($this->_columns
as $tableName => $table) {
1038 if (array_key_exists('fields', $table)) {
1039 foreach ($table['fields'] as $fieldName => $field) {
1041 if (empty($field['no_display'])) {
1042 foreach (array('table', 'field') as $var) {
1043 if (!empty($
{$var}['grouping'])) {
1044 if (!is_array($
{$var}['grouping'])) {
1045 $tableName = $
{$var}['grouping'];
1048 $tableName = array_keys($
{$var}['grouping']);
1049 $tableName = $tableName[0];
1050 $groupTitle = array_values($
{$var}['grouping']);
1051 $groupTitle = $groupTitle[0];
1056 if (!$groupTitle && isset($table['group_title'])) {
1057 $groupTitle = $table['group_title'];
1058 // Having a group_title is secret code for being a custom group
1059 // which cryptically translates to needing an accordion.
1060 // here we make that explicit.
1061 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1064 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array
::value('title', $field);
1065 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1066 $colGroups[$tableName]['group_title'] = $groupTitle;
1068 $options[$fieldName] = CRM_Utils_Array
::value('title', $field);
1074 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1075 NULL, NULL, NULL, $this->_fourColumnAttribute
, TRUE
1077 if (!empty($colGroups)) {
1078 $this->tabs
['FieldSelection'] = array(
1079 'title' => ts('Columns'),
1080 'tpl' => 'FieldSelection',
1081 'div_label' => 'col-groups',
1084 // Note this assignment is only really required in buildForm. It is being 'over-called'
1085 // to reduce risk of being missed due to overridden functions.
1086 $this->assign('tabs', $this->tabs
);
1089 $this->assign('colGroups', $colGroups);
1093 * Add filters to report.
1095 public function addFilters() {
1096 $filters = $filterGroups = array();
1099 foreach ($this->_filters
as $table => $attributes) {
1100 if (isset($this->_columns
[$table]['group_title'])) {
1101 // The presence of 'group_title' is secret code for 'is_a_custom_table'
1102 // which magically means to 'display in an accordian'
1103 // here we make this explicit.
1104 $filterGroups[$table] = array(
1105 'group_title' => $this->_columns
[$table]['group_title'],
1106 'use_accordian_for_field_selection' => TRUE,
1110 foreach ($attributes as $fieldName => $field) {
1111 // get ready with option value pair
1112 // @ 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
1114 $operations = $this->getOperationPair(
1115 CRM_Utils_Array
::value('operatorType', $field),
1118 $filters[$table][$fieldName] = $field;
1120 switch (CRM_Utils_Array
::value('operatorType', $field)) {
1121 case CRM_Report_Form
::OP_MONTH
:
1122 if (!array_key_exists('options', $field) ||
1123 !is_array($field['options']) ||
empty($field['options'])
1125 // If there's no option list for this filter, define one.
1126 $field['options'] = array(
1128 2 => ts('February'),
1135 9 => ts('September'),
1136 10 => ts('October'),
1137 11 => ts('November'),
1138 12 => ts('December'),
1140 // Add this option list to this column _columns. This is
1141 // required so that filter statistics show properly.
1142 $this->_columns
[$table]['filters'][$fieldName]['options'] = $field['options'];
1144 case CRM_Report_Form
::OP_MULTISELECT
:
1145 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1146 // assume a multi-select field
1147 if (!empty($field['options']) ||
1148 $fieldName == 'state_province_id' ||
$fieldName == 'county_id'
1150 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1151 if (count($operations) <= 1) {
1154 if ($fieldName == 'state_province_id' ||
1155 $fieldName == 'county_id'
1157 $this->addChainSelect($fieldName . '_value', array(
1164 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], array(
1165 'style' => 'min-width:250px',
1166 'class' => 'crm-select2 huge',
1168 'placeholder' => ts('- select -'),
1174 case CRM_Report_Form
::OP_SELECT
:
1175 // assume a select field
1176 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1177 if (!empty($field['options'])) {
1178 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1182 case CRM_Report_Form
::OP_ENTITYREF
:
1183 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1184 $this->setEntityRefDefaults($field, $table);
1185 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1188 case CRM_Report_Form
::OP_DATE
:
1189 // build datetime fields
1190 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations);
1194 case CRM_Report_Form
::OP_DATETIME
:
1195 // build datetime fields
1196 CRM_Core_Form_Date
::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', TRUE);
1200 case CRM_Report_Form
::OP_INT
:
1201 case CRM_Report_Form
::OP_FLOAT
:
1202 // and a min value input box
1203 $this->add('text', "{$fieldName}_min", ts('Min'));
1204 // and a max value input box
1205 $this->add('text', "{$fieldName}_max", ts('Max'));
1207 // default type is string
1208 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1209 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1211 // we need text box for value input
1212 $this->add('text', "{$fieldName}_value", NULL, array('class' => 'huge'));
1217 if (!empty($filters)) {
1218 $this->tabs
['Filters'] = array(
1219 'title' => ts('Filters'),
1221 'div_label' => 'set-filters',
1224 $this->assign('filters', $filters);
1225 $this->assign('filterGroups', $filterGroups);
1229 * Function to assign the tabs to the template in the correct order.
1231 * We want the tabs to wind up in this order (if not overridden).
1239 protected function assignTabs() {
1247 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs
);
1248 $order = array_merge($order, $this->tabs
);
1249 $this->assign('tabs', $order);
1253 * The intent is to add a tab for developers to view the sql.
1255 * Currently using dpm.
1257 * @param string $sql
1259 protected function addToDeveloperTab($sql) {
1260 if (!CRM_Core_Permission
::check('view report sql')) {
1263 $this->tabs
['Developer'] = array(
1264 'title' => ts('Developer'),
1265 'tpl' => 'Developer',
1266 'div_label' => 'set-developer',
1269 $this->assignTabs();
1270 foreach (array('LEFT JOIN') as $term) {
1271 $sql = str_replace($term, '<br>  ' . $term, $sql);
1273 foreach (array('FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';') as $term) {
1274 $sql = str_replace($term, '<br><br>' . $term, $sql);
1276 $this->sql
.= $sql . "<br>";
1278 $this->assign('sql', $this->sql
);
1282 * Add options defined in $this->_options to the report.
1284 public function addOptions() {
1285 if (!empty($this->_options
)) {
1286 // FIXME: For now lets build all elements as checkboxes.
1287 // Once we clear with the format we can build elements based on type
1289 foreach ($this->_options
as $fieldName => $field) {
1292 if ($field['type'] == 'select') {
1293 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1295 elseif ($field['type'] == 'checkbox') {
1296 $options[$field['title']] = $fieldName;
1297 $this->addCheckBox($fieldName, NULL,
1299 NULL, NULL, NULL, $this->_fourColumnAttribute
1304 if (!empty($this->_options
)) {
1305 $this->tabs
['ReportOptions'] = array(
1306 'title' => ts('Display Options'),
1307 'tpl' => 'ReportOptions',
1308 'div_label' => 'other-options',
1311 $this->assign('otherOptions', $this->_options
);
1315 * Add chart options to the report.
1317 public function addChartOptions() {
1318 if (!empty($this->_charts
)) {
1319 $this->addElement('select', "charts", ts('Chart'), $this->_charts
);
1320 $this->assign('charts', $this->_charts
);
1321 $this->addElement('submit', $this->_chartButtonName
, ts('View'));
1326 * Add group by options to the report.
1328 public function addGroupBys() {
1329 $options = $freqElements = array();
1331 foreach ($this->_columns
as $tableName => $table) {
1332 if (array_key_exists('group_bys', $table)) {
1333 foreach ($table['group_bys'] as $fieldName => $field) {
1334 if (!empty($field)) {
1335 $options[$field['title']] = $fieldName;
1336 if (!empty($field['frequency'])) {
1337 $freqElements[$field['title']] = $fieldName;
1343 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1344 NULL, NULL, NULL, $this->_fourColumnAttribute
1346 $this->assign('groupByElements', $options);
1347 if (!empty($options)) {
1348 $this->tabs
['GroupBy'] = array(
1349 'title' => ts('Grouping'),
1351 'div_label' => 'group-by-elements',
1355 foreach ($freqElements as $name) {
1356 $this->addElement('select', "group_bys_freq[$name]",
1357 ts('Frequency'), $this->_groupByDateFreq
1363 * Add data for order by tab.
1365 public function addOrderBys() {
1367 foreach ($this->_columns
as $tableName => $table) {
1369 // Report developer may define any column to order by; include these as order-by options.
1370 if (array_key_exists('order_bys', $table)) {
1371 foreach ($table['order_bys'] as $fieldName => $field) {
1372 if (!empty($field)) {
1373 $options[$fieldName] = $field['title'];
1378 // Add searchable custom fields as order-by options, if so requested
1379 // (These are already indexed, so allowing to order on them is cheap.)
1381 if ($this->_autoIncludeIndexedFieldsAsOrderBys
&&
1382 array_key_exists('extends', $table) && !empty($table['extends'])
1384 foreach ($table['fields'] as $fieldName => $field) {
1385 if (empty($field['no_display'])) {
1386 $options[$fieldName] = $field['title'];
1394 $this->assign('orderByOptions', $options);
1395 if (!empty($options)) {
1396 $this->tabs
['OrderBy'] = array(
1397 'title' => ts('Sorting'),
1399 'div_label' => 'order-by-elements',
1403 if (!empty($options)) {
1405 '-' => ' - none - ',
1407 for ($i = 1; $i <= 5; $i++
) {
1408 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1409 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array(
1410 'ASC' => 'Ascending',
1411 'DESC' => 'Descending',
1413 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1414 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
1420 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1422 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1423 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1426 public function buildInstanceAndButtons() {
1427 CRM_Report_Form_Instance
::buildForm($this);
1429 $label = $this->_id ?
ts('Update Report') : ts('Create Report');
1431 $this->addElement('submit', $this->_instanceButtonName
, $label);
1432 $this->addElement('submit', $this->_printButtonName
, ts('Print Report'));
1433 $this->addElement('submit', $this->_pdfButtonName
, ts('PDF'));
1436 $this->addElement('submit', $this->_createNewButtonName
,
1437 ts('Save a Copy') . '...');
1439 $this->assign('instanceForm', $this->_instanceForm
);
1441 $label = $this->_id ?
ts('Print Report') : ts('Print Preview');
1442 $this->addElement('submit', $this->_printButtonName
, $label);
1444 $label = $this->_id ?
ts('PDF') : ts('Preview PDF');
1445 $this->addElement('submit', $this->_pdfButtonName
, $label);
1447 $label = $this->_id ?
ts('Export to CSV') : ts('Preview CSV');
1449 if ($this->_csvSupported
) {
1450 $this->addElement('submit', $this->_csvButtonName
, $label);
1453 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1454 $permission = CRM_Core_Permission
::getPermission();
1455 if ($permission == CRM_Core_Permission
::EDIT
&&
1456 $this->_add2groupSupported
1458 $this->addElement('select', 'groups', ts('Group'),
1459 array('' => ts('Add Contacts to Group')) +
1460 CRM_Core_PseudoConstant
::nestedGroup(),
1461 array('class' => 'crm-select2 crm-action-menu fa-plus huge')
1463 $this->assign('group', TRUE);
1466 $this->addElement('submit', $this->_groupButtonName
, '', array('style' => 'display: none;'));
1468 $this->addChartOptions();
1469 $this->addButtons(array(
1472 'name' => ts('Preview Report'),
1473 'isDefault' => TRUE,
1480 * Main build form function.
1482 public function buildQuickForm() {
1483 $this->addColumns();
1485 $this->addFilters();
1487 $this->addOptions();
1489 $this->addGroupBys();
1491 $this->addOrderBys();
1493 $this->buildInstanceAndButtons();
1495 // Add form rule for report.
1496 if (is_callable(array(
1500 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1502 $this->assignTabs();
1506 * A form rule function for custom data.
1508 * The rule ensures that fields selected in group_by if any) should only be the ones
1509 * present in display/select fields criteria;
1510 * note: works if and only if any custom field selected in group_by.
1512 * @param array $fields
1513 * @param array $ignoreFields
1517 public function customDataFormRule($fields, $ignoreFields = array()) {
1519 if (!empty($this->_customGroupExtends
) && $this->_customGroupGroupBy
&&
1520 !empty($fields['group_bys'])
1522 foreach ($this->_columns
as $tableName => $table) {
1523 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1524 substr($tableName, 0, 12) == 'custom_value') &&
1525 !empty($this->_columns
[$tableName]['fields'])
1527 foreach ($this->_columns
[$tableName]['fields'] as $fieldName => $field) {
1528 if (array_key_exists($fieldName, $fields['group_bys']) &&
1529 !array_key_exists($fieldName, $fields['fields'])
1531 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1533 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1534 foreach ($fields['fields'] as $fld => $val) {
1535 if (!array_key_exists($fld, $fields['group_bys']) &&
1536 !in_array($fld, $ignoreFields)
1538 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1550 * Get operators to display on form.
1552 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1554 * @param string $type
1555 * @param string $fieldName
1559 public function getOperationPair($type = "string", $fieldName = NULL) {
1560 // FIXME: At some point we should move these key-val pairs
1561 // to option_group and option_value table.
1563 case CRM_Report_Form
::OP_INT
:
1564 case CRM_Report_Form
::OP_FLOAT
:
1567 'lte' => ts('Is less than or equal to'),
1568 'gte' => ts('Is greater than or equal to'),
1569 'bw' => ts('Is between'),
1570 'eq' => ts('Is equal to'),
1571 'lt' => ts('Is less than'),
1572 'gt' => ts('Is greater than'),
1573 'neq' => ts('Is not equal to'),
1574 'nbw' => ts('Is not between'),
1575 'nll' => ts('Is empty (Null)'),
1576 'nnll' => ts('Is not empty (Null)'),
1580 case CRM_Report_Form
::OP_SELECT
:
1582 'eq' => ts('Is equal to'),
1586 case CRM_Report_Form
::OP_MONTH
:
1587 case CRM_Report_Form
::OP_MULTISELECT
:
1588 case CRM_Report_Form
::OP_ENTITYREF
:
1591 'in' => ts('Is one of'),
1592 'notin' => ts('Is not one of'),
1596 case CRM_Report_Form
::OP_DATE
:
1599 'nll' => ts('Is empty (Null)'),
1600 'nnll' => ts('Is not empty (Null)'),
1604 case CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
:
1605 // use this operator for the values, concatenated with separator. For e.g if
1606 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1608 'mhas' => ts('Is one of'),
1609 'mnot' => ts('Is not one of'),
1616 'has' => ts('Contains'),
1617 'sw' => ts('Starts with'),
1618 'ew' => ts('Ends with'),
1619 'nhas' => ts('Does not contain'),
1620 'eq' => ts('Is equal to'),
1621 'neq' => ts('Is not equal to'),
1622 'nll' => ts('Is empty (Null)'),
1623 'nnll' => ts('Is not empty (Null)'),
1630 * Build the tag filter field to display on the filters tab.
1632 public function buildTagFilter() {
1633 $contactTags = CRM_Core_BAO_Tag
::getTags($this->_tagFilterTable
);
1634 if (!empty($contactTags)) {
1635 $this->_columns
['civicrm_tag'] = array(
1636 'dao' => 'CRM_Core_DAO_Tag',
1640 'title' => ts('Tag'),
1642 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1643 'options' => $contactTags,
1651 * Adds group filters to _columns (called from _Construct).
1653 public function buildGroupFilter() {
1654 $this->_columns
['civicrm_group']['filters'] = array(
1656 'name' => 'group_id',
1657 'title' => ts('Group'),
1658 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
1660 'options' => CRM_Core_PseudoConstant
::nestedGroup(),
1663 if (empty($this->_columns
['civicrm_group']['dao'])) {
1664 $this->_columns
['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1666 if (empty($this->_columns
['civicrm_group']['alias'])) {
1667 $this->_columns
['civicrm_group']['alias'] = 'cgroup';
1672 * Get SQL operator from form text version.
1674 * @param string $operator
1678 public function getSQLOperator($operator = "like") {
1679 switch ($operator) {
1712 return 'IS NOT NULL';
1721 * Generate where clause.
1723 * This can be overridden in reports for special treatment of a field
1725 * @param array $field Field specifications
1726 * @param string $op Query operator (not an exact match to sql)
1727 * @param mixed $value
1731 * @return null|string
1733 public function whereClause(&$field, $op, $value, $min, $max) {
1735 $type = CRM_Utils_Type
::typeToString(CRM_Utils_Array
::value('type', $field));
1741 if (($min !== NULL && strlen($min) > 0) ||
1742 ($max !== NULL && strlen($max) > 0)
1744 $min = CRM_Utils_Type
::escape($min, $type);
1745 $max = CRM_Utils_Type
::escape($max, $type);
1749 $clauses[] = "( {$field['dbAlias']} >= $min )";
1752 $clauses[] = "( {$field['dbAlias']} < $min )";
1757 $clauses[] = "( {$field['dbAlias']} <= $max )";
1760 $clauses[] = "( {$field['dbAlias']} > $max )";
1764 if (!empty($clauses)) {
1766 $clause = implode(' AND ', $clauses);
1769 $clause = implode(' OR ', $clauses);
1777 if ($value !== NULL && strlen($value) > 0) {
1778 $value = CRM_Utils_Type
::escape($value, $type);
1779 if (strpos($value, '%') === FALSE) {
1780 $value = "'%{$value}%'";
1783 $value = "'{$value}'";
1785 $sqlOP = $this->getSQLOperator($op);
1786 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1792 if (is_string($value) && strlen($value)) {
1793 $value = explode(',', $value);
1795 if ($value !== NULL && is_array($value) && count($value) > 0) {
1796 $sqlOP = $this->getSQLOperator($op);
1797 if (CRM_Utils_Array
::value('type', $field) ==
1798 CRM_Utils_Type
::T_STRING
1800 //cycle through selections and escape values
1801 foreach ($value as $key => $selection) {
1802 $value[$key] = CRM_Utils_Type
::escape($selection, $type);
1805 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
1809 // for numerical values
1810 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1813 if ($op == 'notin') {
1814 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1817 $clause = "( " . $clause . " )";
1824 // multiple has or multiple not
1825 if ($value !== NULL && count($value) > 0) {
1826 $value = CRM_Utils_Type
::escapeAll($value, $type);
1827 $operator = $op == 'mnot' ?
'NOT' : '';
1828 $regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', (array) $value) . "[[:cntrl:]]*";
1829 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
1835 if ($value !== NULL && strlen($value) > 0) {
1836 $value = CRM_Utils_Type
::escape($value, $type);
1837 if (strpos($value, '%') === FALSE) {
1839 $value = "'{$value}%'";
1842 $value = "'%{$value}'";
1846 $value = "'{$value}'";
1848 $sqlOP = $this->getSQLOperator($op);
1849 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1855 $sqlOP = $this->getSQLOperator($op);
1856 $clause = "( {$field['dbAlias']} $sqlOP )";
1860 if ($value !== NULL && strlen($value) > 0) {
1861 if (isset($field['clause'])) {
1862 // FIXME: we not doing escape here. Better solution is to use two
1863 // different types - data-type and filter-type
1864 $clause = $field['clause'];
1867 $value = CRM_Utils_Type
::escape($value, $type);
1868 $sqlOP = $this->getSQLOperator($op);
1869 if ($field['type'] == CRM_Utils_Type
::T_STRING
) {
1870 $value = "'{$value}'";
1872 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1878 if (!empty($field['group']) && $clause) {
1879 $clause = $this->whereGroupClause($field, $value, $op);
1881 elseif (!empty($field['tag']) && $clause) {
1882 // not using left join in query because if any contact
1883 // belongs to more than one tag, results duplicate
1885 $clause = $this->whereTagClause($field, $value, $op);
1887 elseif (!empty($field['membership_org']) && $clause) {
1888 $clause = $this->whereMembershipOrgClause($value, $op);
1890 elseif (!empty($field['membership_type']) && $clause) {
1891 $clause = $this->whereMembershipTypeClause($value, $op);
1897 * Get SQL where clause for a date field.
1899 * @param string $fieldName
1900 * @param string $relative
1901 * @param string $from
1903 * @param string $type
1904 * @param string $fromTime
1905 * @param string $toTime
1907 * @return null|string
1909 public function dateClause(
1911 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1914 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
)))) {
1915 $sqlOP = $this->getSQLOperator($relative);
1916 return "( {$fieldName} {$sqlOP} )";
1919 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1922 $from = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($from, 0, 8) : $from;
1923 $clauses[] = "( {$fieldName} >= $from )";
1927 $to = ($type == CRM_Utils_Type
::T_DATE
) ?
substr($to, 0, 8) : $to;
1928 $clauses[] = "( {$fieldName} <= {$to} )";
1931 if (!empty($clauses)) {
1932 return implode(' AND ', $clauses);
1939 * Possibly unused function.
1941 * @todo - could not find any instances where this is called
1943 * @param bool $relative
1944 * @param string $from
1947 * @return string|NULL
1949 public function dateDisplay($relative, $from, $to) {
1950 list($from, $to) = $this->getFromTo($relative, $from, $to);
1953 $clauses[] = CRM_Utils_Date
::customFormat($from, NULL, array('m', 'M'));
1956 $clauses[] = 'Past';
1960 $clauses[] = CRM_Utils_Date
::customFormat($to, NULL, array('m', 'M'));
1963 $clauses[] = 'Today';
1966 if (!empty($clauses)) {
1967 return implode(' - ', $clauses);
1974 * Get values for from and to for date ranges.
1976 * @param bool $relative
1977 * @param string $from
1979 * @param string $fromTime
1980 * @param string $toTime
1984 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1985 if (empty($toTime)) {
1988 //FIX ME not working for relative
1990 list($term, $unit) = CRM_Utils_System
::explode('.', $relative, 2);
1991 $dateRange = CRM_Utils_Date
::relativeToAbsolute($term, $unit);
1992 $from = substr($dateRange['from'], 0, 8);
1993 //Take only Date Part, Sometime Time part is also present in 'to'
1994 $to = substr($dateRange['to'], 0, 8);
1996 $from = CRM_Utils_Date
::processDate($from, $fromTime);
1997 $to = CRM_Utils_Date
::processDate($to, $toTime);
1998 return array($from, $to);
2002 * Alter display of rows.
2004 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2005 * such as rendering contacts as links.
2007 * @param array $rows
2008 * Rows generated by SQL, with an array for each row.
2010 public function alterDisplay(&$rows) {
2014 * Alter the way in which custom data fields are displayed.
2016 * @param array $rows
2018 public function alterCustomDataDisplay(&$rows) {
2019 // custom code to alter rows having custom values
2020 if (empty($this->_customGroupExtends
)) {
2024 $customFieldIds = array();
2025 foreach ($this->_params
['fields'] as $fieldAlias => $value) {
2026 if ($fieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)) {
2027 $customFieldIds[$fieldAlias] = $fieldId;
2030 if (empty($customFieldIds)) {
2034 $customFields = $fieldValueMap = array();
2035 $customFieldCols = array(
2043 // skip for type date and ContactReference since date format is already handled
2045 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
2046 FROM civicrm_custom_field cf
2047 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2048 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
2049 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
2050 cg.is_active = 1 AND
2051 cf.is_active = 1 AND
2052 cf.is_searchable = 1 AND
2053 cf.data_type NOT IN ('ContactReference', 'Date') AND
2054 cf.id IN (" . implode(",", $customFieldIds) . ")";
2056 $dao = CRM_Core_DAO
::executeQuery($query);
2057 while ($dao->fetch()) {
2058 foreach ($customFieldCols as $key) {
2059 $customFields[$dao->table_name
. '_custom_' .
2060 $dao->id
][$key] = $dao->$key;
2062 if ($dao->option_group_id
) {
2063 $fieldValueMap[$dao->option_group_id
][$dao->value
] = $dao->label
;
2068 $entryFound = FALSE;
2069 foreach ($rows as $rowNum => $row) {
2070 foreach ($row as $tableCol => $val) {
2071 if (array_key_exists($tableCol, $customFields)) {
2072 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
2077 // skip looking further in rows, if first row itself doesn't
2078 // have the column we need
2086 * Format custom values.
2088 * @param mixed $value
2089 * @param array $customField
2090 * @param array $fieldValueMap
2092 * @return float|string|void
2094 public function formatCustomValues($value, $customField, $fieldValueMap) {
2095 if (CRM_Utils_System
::isNull($value)) {
2099 $htmlType = $customField['html_type'];
2101 switch ($customField['data_type']) {
2103 if ($value == '1') {
2104 $retValue = ts('Yes');
2107 $retValue = ts('No');
2112 $retValue = CRM_Utils_System
::formatWikiURL($value);
2124 if ($htmlType == 'Text') {
2125 $retValue = (float) $value;
2129 if ($htmlType == 'Text') {
2130 $retValue = CRM_Utils_Money
::format($value, NULL, '%a');
2135 if (in_array($htmlType, array(
2142 case 'StateProvince':
2145 switch ($htmlType) {
2146 case 'Multi-Select Country':
2147 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2148 $customData = array();
2149 foreach ($value as $val) {
2151 $customData[] = CRM_Core_PseudoConstant
::country($val, FALSE);
2154 $retValue = implode(', ', $customData);
2157 case 'Select Country':
2158 $retValue = CRM_Core_PseudoConstant
::country($value, FALSE);
2161 case 'Select State/Province':
2162 $retValue = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
2165 case 'Multi-Select State/Province':
2166 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2167 $customData = array();
2168 foreach ($value as $val) {
2170 $customData[] = CRM_Core_PseudoConstant
::stateProvince($val, FALSE);
2173 $retValue = implode(', ', $customData);
2178 case 'Autocomplete-Select':
2179 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2183 case 'AdvMulti-Select':
2184 case 'Multi-Select':
2185 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2186 $customData = array();
2187 foreach ($value as $val) {
2189 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2192 $retValue = implode(', ', $customData);
2208 * Remove duplicate rows.
2210 * @param array $rows
2212 public function removeDuplicates(&$rows) {
2213 if (empty($this->_noRepeats
)) {
2216 $checkList = array();
2218 foreach ($rows as $key => $list) {
2219 foreach ($list as $colName => $colVal) {
2220 if (array_key_exists($colName, $checkList) &&
2221 $checkList[$colName] == $colVal
2223 $rows[$key][$colName] = "";
2225 if (in_array($colName, $this->_noRepeats
)) {
2226 $checkList[$colName] = $colVal;
2233 * Fix subtotal display.
2236 * @param array $fields
2237 * @param bool $subtotal
2239 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2240 foreach ($row as $colName => $colVal) {
2241 if (in_array($colName, $fields)) {
2243 elseif (isset($this->_columnHeaders
[$colName])) {
2245 $row[$colName] = "Subtotal";
2249 unset($row[$colName]);
2256 * Calculate grant total.
2258 * @param array $rows
2262 public function grandTotal(&$rows) {
2263 if (!$this->_rollup ||
($this->_rollup
== '') ||
2264 ($this->_limit
&& count($rows) >= self
::ROW_COUNT_LIMIT
)
2268 $lastRow = array_pop($rows);
2270 foreach ($this->_columnHeaders
as $fld => $val) {
2271 if (!in_array($fld, $this->_statFields
)) {
2272 if (!$this->_grandFlag
) {
2273 $lastRow[$fld] = "Grand Total";
2274 $this->_grandFlag
= TRUE;
2277 $lastRow[$fld] = "";
2282 $this->assign('grandStat', $lastRow);
2287 * Format display output.
2289 * @param array $rows
2290 * @param bool $pager
2292 public function formatDisplay(&$rows, $pager = TRUE) {
2293 // set pager based on if any limit was applied in the query.
2298 // allow building charts if any
2299 if (!empty($this->_params
['charts']) && !empty($rows)) {
2300 $this->buildChart($rows);
2301 $this->assign('chartEnabled', TRUE);
2302 $this->_chartId
= "{$this->_params['charts']}_" .
2303 ($this->_id ?
$this->_id
: substr(get_class($this), 16)) . '_' .
2305 $this->assign('chartId', $this->_chartId
);
2308 // unset columns not to be displayed.
2309 foreach ($this->_columnHeaders
as $key => $value) {
2310 if (!empty($value['no_display'])) {
2311 unset($this->_columnHeaders
[$key]);
2315 // unset columns not to be displayed.
2316 if (!empty($rows)) {
2317 foreach ($this->_noDisplay
as $noDisplayField) {
2318 foreach ($rows as $rowNum => $row) {
2319 unset($this->_columnHeaders
[$noDisplayField]);
2324 // build array of section totals
2325 $this->sectionTotals();
2327 // process grand-total row
2328 $this->grandTotal($rows);
2330 // use this method for formatting rows for display purpose.
2331 $this->alterDisplay($rows);
2332 CRM_Utils_Hook
::alterReportVar('rows', $rows, $this);
2334 // use this method for formatting custom rows for display purpose.
2335 $this->alterCustomDataDisplay($rows);
2341 * @param array $rows
2343 public function buildChart(&$rows) {
2344 // override this method for building charts.
2347 // select() method below has been added recently (v3.3), and many of the report templates might
2348 // still be having their own select() method. We should fix them as and when encountered and move
2349 // towards generalizing the select() method below.
2352 * Generate the SELECT clause and set class variable $_select.
2354 public function select() {
2355 $select = $this->_selectAliases
= array();
2357 foreach ($this->_columns
as $tableName => $table) {
2358 if (array_key_exists('fields', $table)) {
2359 foreach ($table['fields'] as $fieldName => $field) {
2360 if ($tableName == 'civicrm_address') {
2361 $this->_addressField
= TRUE;
2363 if ($tableName == 'civicrm_email') {
2364 $this->_emailField
= TRUE;
2366 if ($tableName == 'civicrm_phone') {
2367 $this->_phoneField
= TRUE;
2370 if (!empty($field['required']) ||
2371 !empty($this->_params
['fields'][$fieldName])
2374 // 1. In many cases we want select clause to be built in slightly different way
2375 // for a particular field of a particular type.
2376 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2378 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2379 if ($selectClause) {
2380 $select[] = $selectClause;
2384 // include statistics columns only if set
2385 if (!empty($field['statistics'])) {
2386 foreach ($field['statistics'] as $stat => $label) {
2387 $alias = "{$tableName}_{$fieldName}_{$stat}";
2388 switch (strtolower($stat)) {
2391 $select[] = "$stat({$field['dbAlias']}) as $alias";
2392 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2393 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2394 $this->_statFields
[$label] = $alias;
2395 $this->_selectAliases
[] = $alias;
2399 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2400 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2401 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2402 $this->_statFields
[$label] = $alias;
2403 $this->_selectAliases
[] = $alias;
2406 case 'count_distinct':
2407 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2408 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2409 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type
::T_INT
;
2410 $this->_statFields
[$label] = $alias;
2411 $this->_selectAliases
[] = $alias;
2415 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2416 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2417 $this->_columnHeaders
["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
2418 $this->_statFields
[$label] = $alias;
2419 $this->_selectAliases
[] = $alias;
2425 $alias = "{$tableName}_{$fieldName}";
2426 $select[] = "{$field['dbAlias']} as $alias";
2427 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array
::value('title', $field);
2428 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
2429 $this->_selectAliases
[] = $alias;
2435 // select for group bys
2436 if (array_key_exists('group_bys', $table)) {
2437 foreach ($table['group_bys'] as $fieldName => $field) {
2439 if ($tableName == 'civicrm_address') {
2440 $this->_addressField
= TRUE;
2442 if ($tableName == 'civicrm_email') {
2443 $this->_emailField
= TRUE;
2445 if ($tableName == 'civicrm_phone') {
2446 $this->_phoneField
= TRUE;
2448 // 1. In many cases we want select clause to be built in slightly different way
2449 // for a particular field of a particular type.
2450 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2452 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2453 if ($selectClause) {
2454 $select[] = $selectClause;
2458 if (!empty($this->_params
['group_bys']) &&
2459 !empty($this->_params
['group_bys'][$fieldName]) &&
2460 !empty($this->_params
['group_bys_freq'])
2462 switch (CRM_Utils_Array
::value($fieldName, $this->_params
['group_bys_freq'])) {
2464 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2465 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2466 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2467 $field['title'] = 'Week';
2471 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2472 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2473 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2474 $field['title'] = 'Year';
2478 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2479 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2480 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2481 $field['title'] = 'Month';
2485 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2486 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2487 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2488 $field['title'] = 'Quarter';
2491 // for graphs and charts -
2492 if (!empty($this->_params
['group_bys_freq'][$fieldName])) {
2493 $this->_interval
= $field['title'];
2494 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['title']
2495 = $field['title'] . ' Beginning';
2496 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2497 $this->_columnHeaders
["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params
['group_bys_freq'][$fieldName];
2499 // just to make sure these values are transferred to rows.
2500 // since we 'll need them for calculation purpose,
2501 // e.g making subtotals look nicer or graphs
2502 $this->_columnHeaders
["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2503 $this->_columnHeaders
["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2510 $this->_selectClauses
= $select;
2511 $this->_select
= "SELECT " . implode(', ', $select) . " ";
2515 * Build select clause for a single field.
2517 * @param string $tableName
2518 * @param string $tableKey
2519 * @param string $fieldName
2520 * @param string $field
2524 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2529 * Build where clause.
2531 public function where() {
2532 $this->storeWhereHavingClauseArray();
2534 if (empty($this->_whereClauses
)) {
2535 $this->_where
= "WHERE ( 1 ) ";
2536 $this->_having
= "";
2539 $this->_where
= "WHERE " . implode(' AND ', $this->_whereClauses
);
2542 if ($this->_aclWhere
) {
2543 $this->_where
.= " AND {$this->_aclWhere} ";
2546 if (!empty($this->_havingClauses
)) {
2547 // use this clause to construct group by clause.
2548 $this->_having
= "HAVING " . implode(' AND ', $this->_havingClauses
);
2553 * Store Where clauses into an array.
2555 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2556 * temp table that may not be part of the final where clause or added
2557 * in other functions
2559 public function storeWhereHavingClauseArray() {
2560 foreach ($this->_columns
as $tableName => $table) {
2561 if (array_key_exists('filters', $table)) {
2562 foreach ($table['filters'] as $fieldName => $field) {
2563 // respect pseudofield to filter spec so fields can be marked as
2564 // not to be handled here
2565 if (!empty($field['pseudofield'])) {
2569 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
2570 if (CRM_Utils_Array
::value('operatorType', $field) ==
2571 CRM_Report_Form
::OP_MONTH
2573 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2574 $value = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
2575 if (is_array($value) && !empty($value)) {
2577 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
2582 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
2583 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
2584 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
2585 $fromTime = CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
);
2586 $toTime = CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
);
2587 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2591 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
2593 $clause = $this->whereClause($field,
2595 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
2596 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
2597 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
2602 if (!empty($clause)) {
2603 if (!empty($field['having'])) {
2604 $this->_havingClauses
[] = $clause;
2607 $this->_whereClauses
[] = $clause;
2619 public function processReportMode() {
2620 $this->setOutputMode();
2623 = CRM_Utils_Request
::retrieve(
2626 CRM_Core_DAO
::$_nullObject
2629 $this->_absoluteUrl
= FALSE;
2631 $this->assign('printOnly', FALSE);
2633 if ($this->_outputMode
== 'print' ||
2634 ($this->_sendmail
&& !$this->_outputMode
)
2636 $this->assign('printOnly', TRUE);
2638 $this->addPaging
= FALSE;
2639 $this->assign('outputMode', 'print');
2640 $this->_outputMode
= 'print';
2641 if ($this->_sendmail
) {
2642 $this->_absoluteUrl
= TRUE;
2645 elseif ($this->_outputMode
== 'pdf') {
2647 $this->addPaging
= FALSE;
2648 $this->_absoluteUrl
= TRUE;
2650 elseif ($this->_outputMode
== 'csv') {
2652 $this->_absoluteUrl
= TRUE;
2653 $this->addPaging
= FALSE;
2655 elseif ($this->_outputMode
== 'group') {
2656 $this->assign('outputMode', 'group');
2658 elseif ($this->_outputMode
== 'create_report' && $this->_criteriaForm
) {
2659 $this->assign('outputMode', 'create_report');
2661 elseif ($this->_outputMode
== 'copy' && $this->_criteriaForm
) {
2662 $this->_createNew
= TRUE;
2665 $this->assign('outputMode', $this->_outputMode
);
2666 $this->assign('printOnly', $printOnly);
2667 // Get today's date to include in printed reports
2669 $reportDate = CRM_Utils_Date
::customFormat(date('Y-m-d H:i'));
2670 $this->assign('reportDate', $reportDate);
2675 * Post Processing function for Form.
2677 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2678 * This function is not accessed when the api calls the report.
2680 public function beginPostProcess() {
2681 $this->setParams($this->controller
->exportValues($this->_name
));
2682 if (empty($this->_params
) &&
2685 $this->setParams($this->_formValues
);
2688 // hack to fix params when submitted from dashboard, CRM-8532
2689 // fields array is missing because form building etc is skipped
2690 // in dashboard mode for report
2691 //@todo - this could be done in the dashboard no we have a setter
2692 if (empty($this->_params
['fields']) && !$this->_noFields
) {
2693 $this->setParams($this->_formValues
);
2696 $this->_formValues
= $this->_params
;
2697 if (CRM_Core_Permission
::check('administer Reports') &&
2698 isset($this->_id
) &&
2699 ($this->_instanceButtonName
==
2700 $this->controller
->getButtonName() . '_save' ||
2701 $this->_chartButtonName
== $this->controller
->getButtonName()
2704 $this->assign('updateReportButton', TRUE);
2707 $this->processReportMode();
2709 if ($this->_outputMode
== 'save' ||
$this->_outputMode
== 'copy') {
2710 $this->_createNew
= ($this->_outputMode
== 'copy');
2711 // Do not pass go. Do not collect another chance to re-run the same query.
2712 // This will be called from the button - there is an earlier response to the url
2713 // perhaps they can still be consolidated more.
2714 CRM_Report_Form_Instance
::postProcess($this);
2716 $this->beginPostProcessCommon();
2720 * BeginPostProcess function run in both report mode and non-report mode (api).
2722 public function beginPostProcessCommon() {}
2725 * Build the report query.
2727 * @param bool $applyLimit
2731 public function buildQuery($applyLimit = TRUE) {
2734 $this->customDataFrom();
2739 // order_by columns not selected for display need to be included in SELECT
2740 $unselectedSectionColumns = $this->unselectedSectionColumns();
2741 foreach ($unselectedSectionColumns as $alias => $section) {
2742 $this->_select
.= ", {$section['dbAlias']} as {$alias}";
2745 if ($applyLimit && empty($this->_params
['charts'])) {
2748 CRM_Utils_Hook
::alterReportVar('sql', $this, $this);
2750 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2751 $this->addToDeveloperTab($sql);
2756 * Build group by clause.
2758 public function groupBy() {
2759 $groupBys = array();
2760 if (!empty($this->_params
['group_bys']) &&
2761 is_array($this->_params
['group_bys'])
2763 foreach ($this->_columns
as $tableName => $table) {
2764 if (array_key_exists('group_bys', $table)) {
2765 foreach ($table['group_bys'] as $fieldName => $field) {
2766 if (!empty($this->_params
['group_bys'][$fieldName])) {
2767 $groupBys[] = $field['dbAlias'];
2774 if (!empty($groupBys)) {
2775 $this->_groupBy
= "GROUP BY " . implode(', ', $groupBys);
2780 * Build order by clause.
2782 public function orderBy() {
2783 $this->_orderBy
= "";
2784 $this->_sections
= array();
2785 $this->storeOrderByArray();
2786 if (!empty($this->_orderByArray
) && !$this->_rollup
== 'WITH ROLLUP') {
2787 $this->_orderBy
= "ORDER BY " . implode(', ', $this->_orderByArray
);
2789 $this->assign('sections', $this->_sections
);
2793 * Extract order by fields and store as an array.
2795 * In some cases other functions want to know which fields are selected for ordering by
2796 * Separating this into a separate function allows it to be called separately from constructing
2797 * the order by clause
2799 public function storeOrderByArray() {
2800 $orderBys = array();
2802 if (!empty($this->_params
['order_bys']) &&
2803 is_array($this->_params
['order_bys']) &&
2804 !empty($this->_params
['order_bys'])
2807 // Process order_bys in user-specified order
2808 foreach ($this->_params
['order_bys'] as $orderBy) {
2809 $orderByField = array();
2810 foreach ($this->_columns
as $tableName => $table) {
2811 if (array_key_exists('order_bys', $table)) {
2812 // For DAO columns defined in $this->_columns
2813 $fields = $table['order_bys'];
2815 elseif (array_key_exists('extends', $table)) {
2816 // For custom fields referenced in $this->_customGroupExtends
2817 $fields = CRM_Utils_Array
::value('fields', $table, array());
2822 if (!empty($fields) && is_array($fields)) {
2823 foreach ($fields as $fieldName => $field) {
2824 if ($fieldName == $orderBy['column']) {
2825 $orderByField = array_merge($field, $orderBy);
2826 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2833 if (!empty($orderByField)) {
2834 $this->_orderByFields
[] = $orderByField;
2835 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2837 // Record any section headers for assignment to the template
2838 if (!empty($orderBy['section'])) {
2839 $orderByField['pageBreak'] = CRM_Utils_Array
::value('pageBreak', $orderBy);
2840 $this->_sections
[$orderByField['tplField']] = $orderByField;
2846 $this->_orderByArray
= $orderBys;
2848 $this->assign('sections', $this->_sections
);
2852 * Determine unselected columns.
2856 public function unselectedSectionColumns() {
2857 $selectColumns = array();
2858 foreach ($this->_columns
as $tableName => $table) {
2859 if (array_key_exists('fields', $table)) {
2860 foreach ($table['fields'] as $fieldName => $field) {
2861 if (!empty($field['required']) ||
2862 !empty($this->_params
['fields'][$fieldName])
2865 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2871 if (is_array($this->_sections
)) {
2872 return array_diff_key($this->_sections
, $selectColumns);
2880 * Build output rows.
2882 * @param string $sql
2883 * @param array $rows
2885 public function buildRows($sql, &$rows) {
2886 $dao = CRM_Core_DAO
::executeQuery($sql);
2887 if (!is_array($rows)) {
2891 // use this method to modify $this->_columnHeaders
2892 $this->modifyColumnHeaders();
2894 $unselectedSectionColumns = $this->unselectedSectionColumns();
2896 while ($dao->fetch()) {
2898 foreach ($this->_columnHeaders
as $key => $value) {
2899 if (property_exists($dao, $key)) {
2900 $row[$key] = $dao->$key;
2904 // section headers not selected for display need to be added to row
2905 foreach ($unselectedSectionColumns as $key => $values) {
2906 if (property_exists($dao, $key)) {
2907 $row[$key] = $dao->$key;
2916 * Calculate section totals.
2918 * When "order by" fields are marked as sections, this assigns to the template
2919 * an array of total counts for each section. This data is used by the Smarty
2920 * plugin {sectionTotal}.
2922 public function sectionTotals() {
2924 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2925 if (empty($this->_selectAliases
)) {
2929 if (!empty($this->_sections
)) {
2930 // build the query with no LIMIT clause
2931 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
2932 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2934 // pull section aliases out of $this->_sections
2935 $sectionAliases = array_keys($this->_sections
);
2938 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
2939 $ifnulls[] = "ifnull($alias, '') as $alias";
2942 // Group (un-limited) report by all aliases and get counts. This might
2943 // be done more efficiently when the contents of $sql are known, ie. by
2944 // overriding this method in the report class.
2946 $query = "select " . implode(", ", $ifnulls) .
2947 ", count(*) as ct from ($sql) as subquery group by " .
2948 implode(", ", $sectionAliases);
2950 // initialize array of total counts
2952 $dao = CRM_Core_DAO
::executeQuery($query);
2953 while ($dao->fetch()) {
2955 // let $this->_alterDisplay translate any integer ids to human-readable values.
2956 $rows[0] = $dao->toArray();
2957 $this->alterDisplay($rows);
2960 // add totals for all permutations of section values
2963 $aliasCount = count($sectionAliases);
2964 foreach ($sectionAliases as $alias) {
2965 $values[] = $row[$alias];
2966 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
2967 if ($i == $aliasCount) {
2968 // the last alias is the lowest-level section header; use count as-is
2969 $totals[$key] = $dao->ct
;
2972 // other aliases are higher level; roll count into their total
2973 $totals[$key] +
= $dao->ct
;
2977 $this->assign('sectionTotals', $totals);
2982 * Modify column headers.
2984 public function modifyColumnHeaders() {
2985 // use this method to modify $this->_columnHeaders
2989 * Assign rows to the template.
2991 * @param array $rows
2993 public function doTemplateAssignment(&$rows) {
2994 $this->assign_by_ref('columnHeaders', $this->_columnHeaders
);
2995 $this->assign_by_ref('rows', $rows);
2996 $this->assign('statistics', $this->statistics($rows));
3000 * Build report statistics.
3002 * Override this method to build your own statistics.
3004 * @param array $rows
3008 public function statistics(&$rows) {
3009 $statistics = array();
3011 $count = count($rows);
3013 if ($this->_rollup
&& ($this->_rollup
!= '') && $this->_grandFlag
) {
3017 $this->countStat($statistics, $count);
3019 $this->groupByStat($statistics);
3021 $this->filterStat($statistics);
3027 * Add count statistics.
3029 * @param array $statistics
3032 public function countStat(&$statistics, $count) {
3033 $statistics['counts']['rowCount'] = array(
3034 'title' => ts('Row(s) Listed'),
3038 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
3039 $statistics['counts']['rowsFound'] = array(
3040 'title' => ts('Total Row(s)'),
3041 'value' => $this->_rowsFound
,
3047 * Add group by statistics.
3049 * @param array $statistics
3051 public function groupByStat(&$statistics) {
3052 if (!empty($this->_params
['group_bys']) &&
3053 is_array($this->_params
['group_bys']) &&
3054 !empty($this->_params
['group_bys'])
3056 foreach ($this->_columns
as $tableName => $table) {
3057 if (array_key_exists('group_bys', $table)) {
3058 foreach ($table['group_bys'] as $fieldName => $field) {
3059 if (!empty($this->_params
['group_bys'][$fieldName])) {
3060 $combinations[] = $field['title'];
3065 $statistics['groups'][] = array(
3066 'title' => ts('Grouping(s)'),
3067 'value' => implode(' & ', $combinations),
3073 * Filter statistics.
3075 * @param array $statistics
3077 public function filterStat(&$statistics) {
3078 foreach ($this->_columns
as $tableName => $table) {
3079 if (array_key_exists('filters', $table)) {
3080 foreach ($table['filters'] as $fieldName => $field) {
3081 if ((CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE ||
3082 CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_TIME
) &&
3083 CRM_Utils_Array
::value('operatorType', $field) !=
3084 CRM_Report_Form
::OP_MONTH
3088 CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3089 CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
),
3090 CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
),
3091 CRM_Utils_Array
::value("{$fieldName}_from_time", $this->_params
),
3092 CRM_Utils_Array
::value("{$fieldName}_to_time", $this->_params
)
3094 $from_time_format = !empty($this->_params
["{$fieldName}_from_time"]) ?
'h' : 'd';
3095 $from = CRM_Utils_Date
::customFormat($from, NULL, array($from_time_format));
3097 $to_time_format = !empty($this->_params
["{$fieldName}_to_time"]) ?
'h' : 'd';
3098 $to = CRM_Utils_Date
::customFormat($to, NULL, array($to_time_format));
3101 $statistics['filters'][] = array(
3102 'title' => $field['title'],
3103 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
3106 elseif (in_array($rel = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
),
3107 array_keys($this->getOperationPair(CRM_Report_Form
::OP_DATE
))
3109 $pair = $this->getOperationPair(CRM_Report_Form
::OP_DATE
);
3110 $statistics['filters'][] = array(
3111 'title' => $field['title'],
3112 'value' => $pair[$rel],
3117 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
3120 $pair = $this->getOperationPair(
3121 CRM_Utils_Array
::value('operatorType', $field),
3124 $min = CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
);
3125 $max = CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
);
3126 $val = CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
);
3127 if (in_array($op, array('bw', 'nbw')) && ($min ||
$max)) {
3128 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3130 elseif ($val && CRM_Utils_Array
::value('operatorType', $field) & self
::OP_ENTITYREF
) {
3131 $this->setEntityRefDefaults($field, $tableName);
3132 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3133 array('id' => $val) +
3134 CRM_Utils_Array
::value('api', $field['attributes'], array()));
3136 foreach ($result['values'] as $v) {
3137 $values[] = $v['label'];
3139 $value = "{$pair[$op]} " . implode(', ', $values);
3141 elseif ($op == 'nll' ||
$op == 'nnll') {
3142 $value = $pair[$op];
3144 elseif (is_array($val) && (!empty($val))) {
3145 $options = CRM_Utils_Array
::value('options', $field, array());
3146 foreach ($val as $key => $valIds) {
3147 if (isset($options[$valIds])) {
3148 $val[$key] = $options[$valIds];
3151 $pair[$op] = (count($val) == 1) ?
(($op == 'notin' ||
$op ==
3152 'mnot') ?
ts('Is Not') : ts('Is')) : CRM_Utils_Array
::value($op, $pair);
3153 $val = implode(', ', $val);
3154 $value = "{$pair[$op]} " . $val;
3156 elseif (!is_array($val) && (!empty($val) ||
$val == '0') &&
3157 isset($field['options']) &&
3158 is_array($field['options']) && !empty($field['options'])
3160 $value = CRM_Utils_Array
::value($op, $pair) . " " .
3161 CRM_Utils_Array
::value($val, $field['options'], $val);
3164 $value = CRM_Utils_Array
::value($op, $pair) . " " . $val;
3168 $statistics['filters'][] = array(
3169 'title' => CRM_Utils_Array
::value('title', $field),
3180 * End post processing.
3182 * @param array|null $rows
3184 public function endPostProcess(&$rows = NULL) {
3185 if ($this->_storeResultSet
) {
3186 $this->_resultSet
= $rows;
3189 if ($this->_outputMode
== 'print' ||
3190 $this->_outputMode
== 'pdf' ||
3194 $content = $this->compileContent();
3195 $url = CRM_Utils_System
::url("civicrm/report/instance/{$this->_id}",
3199 if ($this->_sendmail
) {
3200 $config = CRM_Core_Config
::singleton();
3201 $attachments = array();
3203 if ($this->_outputMode
== 'csv') {
3205 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3206 ": {$url}</p>" . '<p>' .
3207 ts('The report is attached as a CSV file.') . '</p>' .
3208 $this->_formValues
['report_footer'];
3210 $csvFullFilename = $config->templateCompileDir
.
3211 CRM_Utils_File
::makeFileName('CiviReport.csv');
3212 $csvContent = CRM_Report_Utils_Report
::makeCsv($this, $rows);
3213 file_put_contents($csvFullFilename, $csvContent);
3214 $attachments[] = array(
3215 'fullPath' => $csvFullFilename,
3216 'mime_type' => 'text/csv',
3217 'cleanName' => 'CiviReport.csv',
3220 if ($this->_outputMode
== 'pdf') {
3221 // generate PDF content
3222 $pdfFullFilename = $config->templateCompileDir
.
3223 CRM_Utils_File
::makeFileName('CiviReport.pdf');
3224 file_put_contents($pdfFullFilename,
3225 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf",
3226 TRUE, array('orientation' => 'landscape')
3229 // generate Email Content
3231 = $this->_formValues
['report_header'] . '<p>' . ts('Report URL') .
3232 ": {$url}</p>" . '<p>' .
3233 ts('The report is attached as a PDF file.') . '</p>' .
3234 $this->_formValues
['report_footer'];
3236 $attachments[] = array(
3237 'fullPath' => $pdfFullFilename,
3238 'mime_type' => 'application/pdf',
3239 'cleanName' => 'CiviReport.pdf',
3243 if (CRM_Report_Utils_Report
::mailReport($content, $this->_id
,
3244 $this->_outputMode
, $attachments
3247 CRM_Core_Session
::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3250 CRM_Core_Session
::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3254 elseif ($this->_outputMode
== 'print') {
3258 if ($chartType = CRM_Utils_Array
::value('charts', $this->_params
)) {
3259 $config = CRM_Core_Config
::singleton();
3260 //get chart image name
3261 $chartImg = $this->_chartId
. '.png';
3262 //get image url path
3264 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL
) .
3266 $uploadUrl .= $chartImg;
3267 //get image doc path to overwrite
3269 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
3270 'openFlashChart/' . $chartImg;
3272 $chart = imagecreatefrompng($uploadUrl);
3273 //convert it into formatted png
3274 CRM_Utils_System
::setHttpHeader('Content-type', 'image/png');
3275 //overwrite with same image
3276 imagepng($chart, $uploadImg);
3278 imagedestroy($chart);
3280 CRM_Utils_PDF_Utils
::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3282 CRM_Utils_System
::civiExit();
3284 elseif ($this->_outputMode
== 'csv') {
3285 CRM_Report_Utils_Report
::export2csv($this, $rows);
3287 elseif ($this->_outputMode
== 'group') {
3288 $group = $this->_params
['groups'];
3289 $this->add2group($group);
3294 * Set store result set indicator to TRUE.
3296 * @todo explain what this does
3298 public function storeResultSet() {
3299 $this->_storeResultSet
= TRUE;
3307 public function getResultSet() {
3308 return $this->_resultSet
;
3312 * Use the form name to create the tpl file name.
3316 public function getTemplateFileName() {
3317 $defaultTpl = parent
::getTemplateFileName();
3318 $template = CRM_Core_Smarty
::singleton();
3319 if (!$template->template_exists($defaultTpl)) {
3320 $defaultTpl = 'CRM/Report/Form.tpl';
3326 * Compile the report content.
3328 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3332 public function compileContent() {
3333 $templateFile = $this->getHookedTemplateFileName();
3334 return $this->_formValues
['report_header'] .
3335 CRM_Core_Form
::$_template->fetch($templateFile) .
3336 $this->_formValues
['report_footer'];
3341 * Post process function.
3343 public function postProcess() {
3344 // get ready with post process params
3345 $this->beginPostProcess();
3348 $sql = $this->buildQuery();
3350 // build array of result based on column headers. This method also allows
3351 // modifying column headers before using it to build result set i.e $rows.
3353 $this->buildRows($sql, $rows);
3355 // format result set.
3356 $this->formatDisplay($rows);
3358 // assign variables to templates
3359 $this->doTemplateAssignment($rows);
3361 // do print / pdf / instance stuff if needed
3362 $this->endPostProcess($rows);
3368 * @param int $rowCount
3372 public function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
3373 // lets do the pager if in html mode
3374 $this->_limit
= NULL;
3376 // CRM-14115, over-ride row count if rowCount is specified in URL
3377 if ($this->_dashBoardRowCount
) {
3378 $rowCount = $this->_dashBoardRowCount
;
3380 if ($this->addPaging
) {
3381 $this->_select
= str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select
);
3383 $pageId = CRM_Utils_Request
::retrieve('crmPID', 'Integer', CRM_Core_DAO
::$_nullObject);
3385 // @todo all http vars should be extracted in the preProcess
3386 // - not randomly in the class
3387 if (!$pageId && !empty($_POST)) {
3388 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3389 $pageId = max((int) $_POST['crmPID_B'], 1);
3391 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3392 $pageId = max((int) $_POST['crmPID'], 1);
3394 unset($_POST['crmPID_B'], $_POST['crmPID']);
3397 $pageId = $pageId ?
$pageId : 1;
3398 $this->set(CRM_Utils_Pager
::PAGE_ID
, $pageId);
3399 $offset = ($pageId - 1) * $rowCount;
3401 $offset = CRM_Utils_Type
::escape($offset, 'Int');
3402 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
3404 $this->_limit
= " LIMIT $offset, $rowCount";
3405 return array($offset, $rowCount);
3407 if ($this->_limitValue
) {
3408 if ($this->_offsetValue
) {
3409 $this->_limit
= " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3412 $this->_limit
= " LIMIT " . $this->_limitValue
;
3420 * @param int $rowCount
3422 public function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
3424 // CRM-14115, over-ride row count if rowCount is specified in URL
3425 if ($this->_dashBoardRowCount
) {
3426 $rowCount = $this->_dashBoardRowCount
;
3429 if ($this->_limit
&& ($this->_limit
!= '')) {
3430 $sql = "SELECT FOUND_ROWS();";
3431 $this->_rowsFound
= CRM_Core_DAO
::singleValueQuery($sql);
3433 'total' => $this->_rowsFound
,
3434 'rowCount' => $rowCount,
3435 'status' => ts('Records') . ' %%StatusMessage%%',
3436 'buttonBottom' => 'PagerBottomButton',
3437 'buttonTop' => 'PagerTopButton',
3438 'pageID' => $this->get(CRM_Utils_Pager
::PAGE_ID
),
3441 $pager = new CRM_Utils_Pager($params);
3442 $this->assign_by_ref('pager', $pager);
3443 $this->ajaxResponse
['totalRows'] = $this->_rowsFound
;
3448 * Build where clause for groups.
3450 * @param string $field
3451 * @param mixed $value
3456 public function whereGroupClause($field, $value, $op) {
3458 $smartGroupQuery = "";
3460 $group = new CRM_Contact_DAO_Group();
3461 $group->is_active
= 1;
3463 $smartGroups = array();
3464 while ($group->fetch()) {
3465 if (in_array($group->id
, $this->_params
['gid_value']) &&
3466 $group->saved_search_id
3468 $smartGroups[] = $group->id
;
3472 CRM_Contact_BAO_GroupContactCache
::check($smartGroups);
3474 $smartGroupQuery = '';
3475 if (!empty($smartGroups)) {
3476 $smartGroups = implode(',', $smartGroups);
3477 $smartGroupQuery = " UNION DISTINCT
3478 SELECT DISTINCT smartgroup_contact.contact_id
3479 FROM civicrm_group_contact_cache smartgroup_contact
3480 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3483 $sqlOp = $this->getSQLOperator($op);
3484 if (!is_array($value)) {
3485 $value = array($value);
3487 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3489 $contactAlias = $this->_aliases
['civicrm_contact'];
3490 if (!empty($this->relationType
) && $this->relationType
== 'b_a') {
3491 $contactAlias = $this->_aliases
['civicrm_contact_b'];
3493 return " {$contactAlias}.id {$sqlOp} (
3494 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3495 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3496 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3497 {$smartGroupQuery} ) ";
3501 * Build where clause for tags.
3503 * @param string $field
3504 * @param mixed $value
3509 public function whereTagClause($field, $value, $op) {
3510 // not using left join in query because if any contact
3511 // belongs to more than one tag, results duplicate
3513 $sqlOp = $this->getSQLOperator($op);
3514 if (!is_array($value)) {
3515 $value = array($value);
3517 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3518 $entity_table = $this->_tagFilterTable
;
3519 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3520 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3521 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3522 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3526 * Generate membership organization clause.
3528 * @param mixed $value
3529 * @param string $op SQL Operator
3533 public function whereMembershipOrgClause($value, $op) {
3534 $sqlOp = $this->getSQLOperator($op);
3535 if (!is_array($value)) {
3536 $value = array($value);
3539 $tmp_membership_org_sql_list = implode(', ', $value);
3540 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3541 SELECT DISTINCT mem.contact_id
3542 FROM civicrm_membership mem
3543 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3544 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3545 WHERE mt.member_of_contact_id IN (" .
3546 $tmp_membership_org_sql_list . ")
3547 AND mt.is_active = '1'
3548 AND mem_status.is_current_member = '1'
3549 AND mem_status.is_active = '1' ) ";
3553 * Generate Membership Type SQL Clause.
3555 * @param mixed $value
3561 public function whereMembershipTypeClause($value, $op) {
3562 $sqlOp = $this->getSQLOperator($op);
3563 if (!is_array($value)) {
3564 $value = array($value);
3567 $tmp_membership_sql_list = implode(', ', $value);
3568 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3569 SELECT DISTINCT mem.contact_id
3570 FROM civicrm_membership mem
3571 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3572 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3573 WHERE mem.membership_type_id IN (" .
3574 $tmp_membership_sql_list . ")
3575 AND mt.is_active = '1'
3576 AND mem_status.is_current_member = '1'
3577 AND mem_status.is_active = '1' ) ";
3581 * Build acl clauses.
3583 * @param string $tableAlias
3585 public function buildACLClause($tableAlias = 'contact_a') {
3586 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause($tableAlias);
3590 * Add custom data to the columns.
3592 * @param bool $addFields
3593 * @param array $permCustomGroupIds
3595 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3596 if (empty($this->_customGroupExtends
)) {
3599 if (!is_array($this->_customGroupExtends
)) {
3600 $this->_customGroupExtends
= array($this->_customGroupExtends
);
3602 $customGroupWhere = '';
3603 if (!empty($permCustomGroupIds)) {
3604 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3608 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3609 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3610 FROM civicrm_custom_group cg
3611 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3612 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends
) . "') AND
3614 cg.is_active = 1 AND
3615 cf.is_active = 1 AND
3616 cf.is_searchable = 1
3617 ORDER BY cg.weight, cf.weight";
3618 $customDAO = CRM_Core_DAO
::executeQuery($sql);
3621 while ($customDAO->fetch()) {
3622 if ($customDAO->table_name
!= $curTable) {
3623 $curTable = $customDAO->table_name
;
3624 $curFields = $curFilters = array();
3627 $this->_columns
[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3628 $this->_columns
[$curTable]['extends'] = $customDAO->extends;
3629 $this->_columns
[$curTable]['grouping'] = $customDAO->table_name
;
3630 $this->_columns
[$curTable]['group_title'] = $customDAO->title
;
3637 if (!array_key_exists($colKey, $this->_columns
[$curTable])) {
3638 $this->_columns
[$curTable][$colKey] = array();
3642 $fieldName = 'custom_' . $customDAO->cf_id
;
3645 // this makes aliasing work in favor
3646 $curFields[$fieldName] = array(
3647 'name' => $customDAO->column_name
,
3648 'title' => $customDAO->label
,
3649 'dataType' => $customDAO->data_type
,
3650 'htmlType' => $customDAO->html_type
,
3653 if ($this->_customGroupFilters
) {
3654 // this makes aliasing work in favor
3655 $curFilters[$fieldName] = array(
3656 'name' => $customDAO->column_name
,
3657 'title' => $customDAO->label
,
3658 'dataType' => $customDAO->data_type
,
3659 'htmlType' => $customDAO->html_type
,
3663 switch ($customDAO->data_type
) {
3666 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_DATE
;
3667 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_DATE
;
3668 // CRM-6946, show time part for datetime date fields
3669 if ($customDAO->time_format
) {
3670 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_TIMESTAMP
;
3675 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_SELECT
;
3676 $curFilters[$fieldName]['options'] = array(
3677 '' => ts('- select -'),
3681 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3685 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_INT
;
3686 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_INT
;
3690 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3691 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_MONEY
;
3695 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_FLOAT
;
3696 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_FLOAT
;
3700 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3702 if (!empty($customDAO->option_group_id
)) {
3703 if (in_array($customDAO->html_type
, array(
3708 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3711 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3713 if ($this->_customGroupFilters
) {
3714 $curFilters[$fieldName]['options'] = array();
3715 $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(
3717 $customDAO->option_group_id
,
3721 while ($ogDAO->fetch()) {
3722 $curFilters[$fieldName]['options'][$ogDAO->value
] = $ogDAO->label
;
3724 CRM_Utils_Hook
::customFieldOptions($customDAO->cf_id
, $curFilters[$fieldName]['options'], FALSE);
3729 case 'StateProvince':
3730 if (in_array($customDAO->html_type
, array(
3731 'Multi-Select State/Province',
3733 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3736 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3738 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::stateProvince();
3742 if (in_array($customDAO->html_type
, array(
3743 'Multi-Select Country',
3745 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT_SEPARATOR
;
3748 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form
::OP_MULTISELECT
;
3750 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant
::country();
3753 case 'ContactReference':
3754 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3755 $curFilters[$fieldName]['name'] = 'display_name';
3756 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3758 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3759 $curFields[$fieldName]['name'] = 'display_name';
3760 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3764 $curFields[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3765 $curFilters[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
3768 if (!array_key_exists('type', $curFields[$fieldName])) {
3769 $curFields[$fieldName]['type'] = CRM_Utils_Array
::value('type', $curFilters[$fieldName], array());
3773 $this->_columns
[$curTable]['fields'] = array_merge($this->_columns
[$curTable]['fields'], $curFields);
3775 if ($this->_customGroupFilters
) {
3776 $this->_columns
[$curTable]['filters'] = array_merge($this->_columns
[$curTable]['filters'], $curFilters);
3778 if ($this->_customGroupGroupBy
) {
3779 $this->_columns
[$curTable]['group_bys'] = array_merge($this->_columns
[$curTable]['group_bys'], $curFields);
3785 * Build custom data from clause.
3787 public function customDataFrom() {
3788 if (empty($this->_customGroupExtends
)) {
3791 $mapper = CRM_Core_BAO_CustomQuery
::$extendsMap;
3793 foreach ($this->_columns
as $table => $prop) {
3794 if (substr($table, 0, 13) == 'civicrm_value' ||
3795 substr($table, 0, 12) == 'custom_value'
3797 $extendsTable = $mapper[$prop['extends']];
3799 // check field is in params
3800 if (!$this->isFieldSelected($prop)) {
3803 $baseJoin = CRM_Utils_Array
::value($prop['extends'], $this->_customGroupExtendsJoin
, "{$this->_aliases[$extendsTable]}.id");
3805 $customJoin = is_array($this->_customGroupJoin
) ?
$this->_customGroupJoin
[$table] : $this->_customGroupJoin
;
3807 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3808 // handle for ContactReference
3809 if (array_key_exists('fields', $prop)) {
3810 foreach ($prop['fields'] as $fieldName => $field) {
3811 if (CRM_Utils_Array
::value('dataType', $field) ==
3814 $columnName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField
::getKeyID($fieldName), 'column_name');
3816 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3825 * Check if the field is selected.
3827 * @param string $prop
3831 public function isFieldSelected($prop) {
3836 if (!empty($this->_params
['fields'])) {
3837 foreach (array_keys($prop['fields']) as $fieldAlias) {
3838 $customFieldId = CRM_Core_BAO_CustomField
::getKeyID($fieldAlias);
3839 if ($customFieldId) {
3840 if (array_key_exists($fieldAlias, $this->_params
['fields'])) {
3844 //might be survey response field.
3845 if (!empty($this->_params
['fields']['survey_response']) &&
3846 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3854 if (!empty($this->_params
['group_bys']) && $this->_customGroupGroupBy
) {
3855 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3856 if (array_key_exists($fieldAlias, $this->_params
['group_bys']) &&
3857 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3864 if (!empty($this->_params
['order_bys'])) {
3865 foreach (array_keys($prop['fields']) as $fieldAlias) {
3866 foreach ($this->_params
['order_bys'] as $orderBy) {
3867 if ($fieldAlias == $orderBy['column'] &&
3868 CRM_Core_BAO_CustomField
::getKeyID($fieldAlias)
3876 if (!empty($prop['filters']) && $this->_customGroupFilters
) {
3877 foreach ($prop['filters'] as $fieldAlias => $val) {
3886 if (isset($this->_params
[$fieldAlias . '_' . $attach]) &&
3887 (!empty($this->_params
[$fieldAlias . '_' . $attach])
3888 ||
($attach != 'relative' &&
3889 $this->_params
[$fieldAlias . '_' . $attach] == '0')
3895 if (!empty($this->_params
[$fieldAlias . '_op']) &&
3896 in_array($this->_params
[$fieldAlias . '_op'], array('nll', 'nnll'))
3907 * Check for empty order_by configurations and remove them.
3909 * Also set template to hide them.
3911 * @param array $formValues
3913 public function preProcessOrderBy(&$formValues) {
3914 // Object to show/hide form elements
3915 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3917 $_showHide->addShow('optionField_1');
3919 // Cycle through order_by options; skip any empty ones, and hide them as well
3922 if (!empty($formValues['order_bys'])) {
3923 foreach ($formValues['order_bys'] as $order_by) {
3924 if ($order_by['column'] && $order_by['column'] != '-') {
3925 $_showHide->addShow('optionField_' . $n);
3926 $orderBys[$n] = $order_by;
3931 for ($i = $n; $i <= 5; $i++
) {
3933 $_showHide->addHide('optionField_' . $i);
3937 // overwrite order_by options with modified values
3938 if (!empty($orderBys)) {
3939 $formValues['order_bys'] = $orderBys;
3942 $formValues['order_bys'] = array(1 => array('column' => '-'));
3945 // assign show/hide data to template
3946 $_showHide->addToTemplate();
3950 * Check if table name has columns in SELECT clause.
3952 * @param string $tableName
3953 * Name of table (index of $this->_columns array).
3957 public function isTableSelected($tableName) {
3958 return in_array($tableName, $this->selectedTables());
3962 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3964 * If the array is unset it will be built.
3969 public function selectedTables() {
3970 if (!$this->_selectedTables
) {
3971 $orderByColumns = array();
3972 if (array_key_exists('order_bys', $this->_params
) &&
3973 is_array($this->_params
['order_bys'])
3975 foreach ($this->_params
['order_bys'] as $orderBy) {
3976 $orderByColumns[] = $orderBy['column'];
3980 foreach ($this->_columns
as $tableName => $table) {
3981 if (array_key_exists('fields', $table)) {
3982 foreach ($table['fields'] as $fieldName => $field) {
3983 if (!empty($field['required']) ||
3984 !empty($this->_params
['fields'][$fieldName])
3986 $this->_selectedTables
[] = $tableName;
3991 if (array_key_exists('order_bys', $table)) {
3992 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3993 if (in_array($orderByName, $orderByColumns)) {
3994 $this->_selectedTables
[] = $tableName;
3999 if (array_key_exists('filters', $table)) {
4000 foreach ($table['filters'] as $filterName => $filter) {
4001 if (!empty($this->_params
["{$filterName}_value"]) ||
4002 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4004 CRM_Utils_Array
::value("{$filterName}_op", $this->_params
) ==
4007 $this->_selectedTables
[] = $tableName;
4014 return $this->_selectedTables
;
4018 * Add address fields.
4020 * @deprecated - use getAddressColumns which is a more accurate description
4021 * and also accepts an array of options rather than a long list
4023 * adding address fields to construct function in reports
4025 * @param bool $groupBy
4026 * Add GroupBy? Not appropriate for detail report.
4027 * @param bool $orderBy
4028 * Add GroupBy? Not appropriate for detail report.
4029 * @param bool $filters
4030 * @param array $defaults
4033 * address fields for construct clause
4035 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4036 $addressFields = array(
4037 'civicrm_address' => array(
4038 'dao' => 'CRM_Core_DAO_Address',
4040 'address_name' => array(
4041 'title' => ts('Address Name'),
4042 'default' => CRM_Utils_Array
::value('name', $defaults, FALSE),
4045 'street_address' => array(
4046 'title' => ts('Street Address'),
4047 'default' => CRM_Utils_Array
::value('street_address', $defaults, FALSE),
4049 'supplemental_address_1' => array(
4050 'title' => ts('Supplementary Address Field 1'),
4051 'default' => CRM_Utils_Array
::value('supplemental_address_1', $defaults, FALSE),
4053 'supplemental_address_2' => array(
4054 'title' => ts('Supplementary Address Field 2'),
4055 'default' => CRM_Utils_Array
::value('supplemental_address_2', $defaults, FALSE),
4057 'street_number' => array(
4058 'name' => 'street_number',
4059 'title' => ts('Street Number'),
4061 'default' => CRM_Utils_Array
::value('street_number', $defaults, FALSE),
4063 'street_name' => array(
4064 'name' => 'street_name',
4065 'title' => ts('Street Name'),
4067 'default' => CRM_Utils_Array
::value('street_name', $defaults, FALSE),
4069 'street_unit' => array(
4070 'name' => 'street_unit',
4071 'title' => ts('Street Unit'),
4073 'default' => CRM_Utils_Array
::value('street_unit', $defaults, FALSE),
4076 'title' => ts('City'),
4077 'default' => CRM_Utils_Array
::value('city', $defaults, FALSE),
4079 'postal_code' => array(
4080 'title' => ts('Postal Code'),
4081 'default' => CRM_Utils_Array
::value('postal_code', $defaults, FALSE),
4083 'postal_code_suffix' => array(
4084 'title' => ts('Postal Code Suffix'),
4085 'default' => CRM_Utils_Array
::value('postal_code_suffix', $defaults, FALSE),
4087 'country_id' => array(
4088 'title' => ts('Country'),
4089 'default' => CRM_Utils_Array
::value('country_id', $defaults, FALSE),
4091 'state_province_id' => array(
4092 'title' => ts('State/Province'),
4093 'default' => CRM_Utils_Array
::value('state_province_id', $defaults, FALSE),
4095 'county_id' => array(
4096 'title' => ts('County'),
4097 'default' => CRM_Utils_Array
::value('county_id', $defaults, FALSE),
4100 'grouping' => 'location-fields',
4105 $addressFields['civicrm_address']['filters'] = array(
4106 'street_number' => array(
4107 'title' => ts('Street Number'),
4109 'name' => 'street_number',
4111 'street_name' => array(
4112 'title' => ts('Street Name'),
4113 'name' => 'street_name',
4114 'operator' => 'like',
4116 'postal_code' => array(
4117 'title' => ts('Postal Code'),
4119 'name' => 'postal_code',
4122 'title' => ts('City'),
4123 'operator' => 'like',
4126 'country_id' => array(
4127 'name' => 'country_id',
4128 'title' => ts('Country'),
4129 'type' => CRM_Utils_Type
::T_INT
,
4130 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4131 'options' => CRM_Core_PseudoConstant
::country(),
4133 'state_province_id' => array(
4134 'name' => 'state_province_id',
4135 'title' => ts('State/Province'),
4136 'type' => CRM_Utils_Type
::T_INT
,
4137 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4138 'options' => array(),
4140 'county_id' => array(
4141 'name' => 'county_id',
4142 'title' => ts('County'),
4143 'type' => CRM_Utils_Type
::T_INT
,
4144 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
4145 'options' => array(),
4151 $addressFields['civicrm_address']['order_bys'] = array(
4152 'street_name' => array('title' => ts('Street Name')),
4153 'street_number' => array('title' => 'Odd / Even Street Number'),
4154 'street_address' => NULL,
4156 'postal_code' => NULL,
4161 $addressFields['civicrm_address']['group_bys'] = array(
4162 'street_address' => NULL,
4164 'postal_code' => NULL,
4165 'state_province_id' => array(
4166 'title' => ts('State/Province'),
4168 'country_id' => array(
4169 'title' => ts('Country'),
4171 'county_id' => array(
4172 'title' => ts('County'),
4176 return $addressFields;
4180 * Do AlterDisplay processing on Address Fields.
4183 * @param array $rows
4184 * @param int $rowNum
4185 * @param string $baseUrl
4186 * @param string $linkText
4190 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4191 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4192 $entryFound = FALSE;
4194 if (array_key_exists('civicrm_address_country_id', $row)) {
4195 if ($value = $row['civicrm_address_country_id']) {
4196 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant
::country($value, FALSE);
4197 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4198 "reset=1&force=1&{$criteriaQueryParams}&" .
4199 "country_id_op=in&country_id_value={$value}",
4200 $this->_absoluteUrl
, $this->_id
4202 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4203 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4204 array(1 => $linkText)
4210 if (array_key_exists('civicrm_address_county_id', $row)) {
4211 if ($value = $row['civicrm_address_county_id']) {
4212 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant
::county($value, FALSE);
4213 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4214 "reset=1&force=1&{$criteriaQueryParams}&" .
4215 "county_id_op=in&county_id_value={$value}",
4216 $this->_absoluteUrl
, $this->_id
4218 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4219 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4220 array(1 => $linkText)
4225 // handle state province
4226 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4227 if ($value = $row['civicrm_address_state_province_id']) {
4228 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant
::stateProvince($value, FALSE);
4230 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4231 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4232 $this->_absoluteUrl
, $this->_id
4234 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4235 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4236 array(1 => $linkText)
4246 * Do AlterDisplay processing on Address Fields.
4249 * @param array $rows
4250 * @param int $rowNum
4251 * @param string $baseUrl
4252 * @param string $linkText
4256 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4257 $entryFound = FALSE;
4258 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4259 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4260 $addLinks = array('gender_id' => 'Gender');
4261 foreach (array('prefix_id', 'suffix_id', 'gender_id') as $fieldName) {
4262 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4263 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4264 $rows[$rowNum]['civicrm_contact_' . $fieldName] = CRM_Core_Pseudoconstant
::getLabel('CRM_Contact_BAO_Contact', $fieldName, $value);
4265 if (($title = CRM_Utils_Array
::value($fieldName, $addLinks)) != FALSE) {
4266 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4276 * Adjusts dates passed in to YEAR() for fiscal year.
4278 * @param string $fieldName
4282 public function fiscalYearOffset($fieldName) {
4283 $config = CRM_Core_Config
::singleton();
4284 $fy = $config->fiscalYearStart
;
4285 if (CRM_Utils_Array
::value('yid_op', $this->_params
) == 'calendar' ||
4286 ($fy['d'] == 1 && $fy['M'] == 1)
4288 return "YEAR( $fieldName )";
4290 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4291 ($fy['d'] > 1 ?
(" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4295 * Add Address into From Table if required.
4297 public function addAddressFromClause() {
4298 // include address field if address column is to be included
4299 if ((isset($this->_addressField
) &&
4300 $this->_addressField
4302 $this->isTableSelected('civicrm_address')
4305 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4306 ON ({$this->_aliases['civicrm_contact']}.id =
4307 {$this->_aliases['civicrm_address']}.contact_id) AND
4308 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4313 * Add Phone into From Table if required.
4315 public function addPhoneFromClause() {
4316 // include address field if address column is to be included
4317 if ($this->isTableSelected('civicrm_phone')
4320 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4321 ON ({$this->_aliases['civicrm_contact']}.id =
4322 {$this->_aliases['civicrm_phone']}.contact_id) AND
4323 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4328 * Get phone columns to add to array.
4330 * @param array $options
4331 * - prefix Prefix to add to table (in case of more than one instance of the table)
4332 * - prefix_label Label to give columns from this phone table instance
4335 * phone columns definition
4337 public function getPhoneColumns($options = array()) {
4338 $defaultOptions = array(
4340 'prefix_label' => '',
4343 $options = array_merge($defaultOptions, $options);
4346 $options['prefix'] . 'civicrm_phone' => array(
4347 'dao' => 'CRM_Core_DAO_Phone',
4349 $options['prefix'] . 'phone' => array(
4350 'title' => ts($options['prefix_label'] . 'Phone'),
4360 * Get address columns to add to array.
4362 * @param array $options
4363 * - prefix Prefix to add to table (in case of more than one instance of the table)
4364 * - prefix_label Label to give columns from this address table instance
4367 * address columns definition
4369 public function getAddressColumns($options = array()) {
4372 'prefix_label' => '',
4376 'defaults' => array(),
4378 return $this->addAddressFields(
4379 $options['group_by'],
4380 $options['order_by'],
4381 $options['filters'],
4382 $options['defaults']
4387 * Get a standard set of contact fields.
4391 public function getBasicContactFields() {
4393 'sort_name' => array(
4394 'title' => ts('Contact Name'),
4399 'no_display' => TRUE,
4402 'prefix_id' => array(
4403 'title' => ts('Contact Prefix'),
4405 'first_name' => array(
4406 'title' => ts('First Name'),
4408 'nick_name' => array(
4409 'title' => ts('Nick Name'),
4411 'middle_name' => array(
4412 'title' => ts('Middle Name'),
4414 'last_name' => array(
4415 'title' => ts('Last Name'),
4417 'suffix_id' => array(
4418 'title' => ts('Contact Suffix'),
4420 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4421 'email_greeting_display' => array('title' => ts('Email Greeting')),
4422 'addressee_display' => array('title' => ts('Address Greeting')),
4423 'contact_type' => array(
4424 'title' => ts('Contact Type'),
4426 'contact_sub_type' => array(
4427 'title' => ts('Contact Subtype'),
4429 'gender_id' => array(
4430 'title' => ts('Gender'),
4432 'birth_date' => array(
4433 'title' => ts('Birth Date'),
4436 'title' => ts('Age'),
4437 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4439 'job_title' => array(
4440 'title' => ts('Contact Job title'),
4442 'organization_name' => array(
4443 'title' => ts('Organization Name'),
4445 'external_identifier' => array(
4446 'title' => ts('Contact identifier from external system'),
4452 * Add contact to group.
4454 * @param int $groupID
4456 public function add2group($groupID) {
4457 if (is_numeric($groupID) && isset($this->_aliases
['civicrm_contact'])) {
4458 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4460 // here are we are prepending / adding contact id field that could be used for adding group
4461 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4462 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select
)) {
4463 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select
);
4466 $select = str_ireplace('SELECT ', $select, $this->_select
);
4469 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4470 $sql = str_replace('WITH ROLLUP', '', $sql);
4471 $dao = CRM_Core_DAO
::executeQuery($sql);
4473 $contact_ids = array();
4474 // Add resulting contacts to group
4475 while ($dao->fetch()) {
4476 if ($dao->addtogroup_contact_id
) {
4477 $contact_ids[$dao->addtogroup_contact_id
] = $dao->addtogroup_contact_id
;
4481 if (!empty($contact_ids)) {
4482 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contact_ids, $groupID);
4483 CRM_Core_Session
::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4486 CRM_Core_Session
::setStatus(ts("The listed records(s) cannot be added to the group."));
4492 * Show charts on print screen.
4494 public static function uploadChartImage() {
4495 // upload strictly for '.png' images
4496 $name = trim(basename(CRM_Utils_Request
::retrieve('name', 'String', CRM_Core_DAO
::$_nullObject, FALSE, NULL, 'GET')));
4497 if (preg_match('/\.png$/', $name)) {
4499 // POST data is usually string data, but we are passing a RAW .png
4500 // so PHP is a bit confused and $_POST is empty. But it has saved
4501 // the raw bits into $HTTP_RAW_POST_DATA
4503 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4505 // prepare the directory
4506 $config = CRM_Core_Config
::singleton();
4508 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir
) .
4510 if (!file_exists($defaultPath)) {
4511 mkdir($defaultPath, 0777, TRUE);
4514 // full path to the saved image including filename
4515 $destination = $defaultPath . $name;
4518 $jfh = fopen($destination, 'w') or die("can't open file");
4519 fwrite($jfh, $httpRawPostData);
4521 CRM_Utils_System
::civiExit();
4526 * Apply common settings to entityRef fields.
4528 * @param array $field
4529 * @param string $table
4531 private function setEntityRefDefaults(&$field, $table) {
4532 $field['attributes'] = $field['attributes'] ?
$field['attributes'] : array();
4533 $field['attributes'] +
= array(
4534 'entity' => CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table)),
4536 'placeholder' => ts('- select -'),
4541 * Add link fields to the row.
4543 * Function adds the _link & _hover fields to the row.
4546 * @param string $baseUrl
4547 * @param string $linkText
4548 * @param string $value
4549 * @param string $fieldName
4550 * @param string $tablePrefix
4551 * @param string $fieldLabel
4555 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4556 $criteriaQueryParams = CRM_Report_Utils_Report
::getPreviewCriteriaQueryParams($this->_defaults
, $this->_params
);
4557 $url = CRM_Report_Utils_Report
::getNextUrl($baseUrl,
4558 "reset=1&force=1&{$criteriaQueryParams}&" .
4559 $fieldName . "_op=in&{$fieldName}_value={$value}",
4560 $this->_absoluteUrl
, $this->_id
4562 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4563 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4564 array(1 => $linkText, 2 => $fieldLabel)
4569 * Generate temporary table to hold all contributions with permissioned FTs.
4571 * @param object $query
4572 * @param string $alias
4573 * @param bool $return
4575 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4576 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
4579 $financialTypes = NULL;
4580 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4581 if (empty($financialTypes)) {
4583 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant
::financialType()));
4586 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4589 $temp = CRM_Utils_Array
::value('civicrm_line_item', $query->_aliases
);
4590 $query->_aliases
['civicrm_line_item'] = $alias;
4592 if (empty($query->_where
)) {
4593 $query->_where
= "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4595 CRM_Core_DAO
::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4596 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4597 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4598 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4599 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4600 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4602 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4603 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4604 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4605 CRM_Core_DAO
::executeQuery($sql);
4607 $query->_aliases
['civicrm_line_item'] = $temp;
4609 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4613 $query->_from
.= $from;
4617 * Get label for show results buttons.
4621 public function getResultsLabel() {
4622 $showResultsLabel = $this->resultsDisplayed() ?
ts('Refresh results') : ts('View results');
4623 return $showResultsLabel;
4627 * Determine the output mode from the url or input.
4630 * - pdf : Render as pdf
4631 * - csv : Render as csv
4632 * - print : Render in print format
4633 * - save : save the report and display the new report
4634 * - copy : save the report as a new instance and display that.
4635 * - group : go to the add to group screen.
4637 * Potentially chart variations could also be included but the complexity
4638 * is that we might print a bar chart as a pdf.
4640 protected function setOutputMode() {
4641 $buttonName = $this->controller
->getButtonName();
4642 $this->_outputMode
= CRM_Utils_Request
::retrieve(
4645 CRM_Core_DAO
::$_nullObject,
4647 CRM_Utils_Array
::value('task', $this->_params
)
4651 if ($buttonName == $this->_instanceButtonName
) {
4652 $this->_outputMode
= 'save';
4654 if ($buttonName == $this->_printButtonName
) {
4655 $this->_outputMode
= 'print';
4657 if ($buttonName == $this->_pdfButtonName
) {
4658 $this->_outputMode
= 'pdf';
4660 if ($this->_csvButtonName
== $buttonName) {
4661 $this->_outputMode
= 'csv';
4663 if ($this->_groupButtonName
== $buttonName) {
4664 $this->_outputMode
= 'group';
4666 if ($buttonName == $this->_createNewButtonName
) {
4667 $this->_outputMode
= 'copy';